Friday, May 5, 2023

Importing data into a MySQL database using LOAD DATA

Database and development teams often load data from plain text files into their MySQL databases. The files might be used to add lookup data, support test and development environments, populate new MySQL instances, load data from regular feeds, or in other ways support their operations. To help with the import process, MySQL provides the LOAD DATA statement, which reads rows from a text file and inserts them into the target table.

In this article, I show how to use the LOAD DATA statement to add data from comma-separated values (CSV) files and other plain text files. Although the examples are fairly basic, they demonstrate the fundamental components that go into a LOAD DATA statement and some of the issues you might run up against along the way. Each example retrieves data from a file on the local system and adds the data to the manufacturers table in the travel database, which you’ve seen in previous articles in this series.

Note: The examples in this article are based on a local instance of MySQL that hosts a very simple database and table. The last section of the article—“Appendix: Preparing your MySQL environment”—provides information about how I set up my system and includes a SQL script for creating the database and table on which the examples are based.

Connecting to the MySQL server

Importing data from a text file into a MySQL database is in itself a fairly straightforward process. Often the most difficult part of the operation is setting up your environment to ensure that it will allow you to run a LOAD DATA statement and import the data into the target table. As with any SQL statement in MySQL, you must have been granted the privileges necessary to carry out your operations (a topic beyond the scope of this article). However, there are a few other issues to be aware of in order to import data, starting with the LOCAL option.

When you create a LOAD DATA statement, you can include the LOCAL option as part of the statement definition. The option determines the statement’s security requirements as well as whether the source text file is located on the client system or the server hosting the MySQL instance:

  • If you do not specify the LOCAL option, the source text file must be located on the MySQL host. When you run the LOAD DATA statement, MySQL reads the file directly from the directory and inserts the data into the target table. This approach generally performs a little better than when you include the LOCAL option because the data is loaded more directly. However, getting the connection right is much more difficult (and the topic for many online discussions).
  • If you specify the LOCAL option, the source text file must be located on the client machine. The client reads the file and sends the content to the server, where it is stored in a temporary file until it is loaded into the target table for processing. The LOCAL option also works if the client and MySQL are on the same machine, which is the approach I’ve taken for this article. Connectivity is typically much easier to establish when you use the LOCAL option.

For the examples in this article, I have used the LOCAL option. Not only are the MySQL connectivity requirements more complicated without it, but they are also not well documented, adding to the frustration should you run into any glitches. If you check out the various forum postings that discuss connectivity issues around the LOAD DATA statement, you’ll find that in many cases, people responding to a post suggest the use of the LOCAL option as a simple workaround to the various challenges.

I also think that for many database administrators and developers, locating source files on the client side is preferable to uploading those files to the MySQL server, if they’re even permitted to do so. If you use the LOCAL option, you do not need the FILE privilege to run a LOAD DATA statement, and you can store the source text file in any local folder that can be accessed by the client application, which in this case, is MySQL Workbench.

Note: The MySQL documentation states that “if LOCAL is specified, the file must be located on the client host.” However, I was able to run a LOAD DATA statement that included the LOCAL option and that pulled data from other systems on my network. The first was another Mac computer and the other was Windows 11 virtual machine. I have not tested this capability beyond that.

When using the LOCAL option, you must ensure that data-loading is enabled on both the client side and server side. To enable it on the client side in Workbench, you should modify your connection on the tool’s home screen. In the main window, right-click the connection and click Edit connection. On the Connection page of the Manage Server Connections dialog box, select the Advanced tab and add the following command in the Others box:

OPT_LOCAL_INFILE=1

The command sets the local-infile option to ON, making it possible to run a LOAD DATA statement that includes the LOCAL option. The following figure shows the setting (outlined in red) as it appears on the connection’s Advanced tab. This setting applies only to this user’s connections in Workbench. Other connections must be configured individually.

In addition to enabling the local-infile option, you must also enable the local_infile global variable on the server, if it’s not already enabled. (The only difference between these two names is that the global variable uses an underscore rather than a dash.) To confirm the variable’s setting, you can run a SHOW GLOBAL VARIABLES statement against your MySQL instance:

SHOW GLOBAL VARIABLES LIKE 'local_infile';

If the statement returns a value of ON, then you’re all set. If the statement returns OFF, then you should run the following SET statement to enable the variable:

SET GLOBAL local_infile = 1;

Once you’ve enabled local data-loading on both the client and server, you should be ready to run your LOAD DATA statements. The examples that follow demonstrate different aspects of importing data from a text file. I’ll show you the contents of each file as we work through the examples. You can then create them on your own system if you want to try out the examples for yourself.

Introducing the LOAD DATA statement

Before we get into the first example, it’s important to understand the basic components that go into a LOAD DATA statement, which includes a number of clauses and subclauses. The following syntax simplifies the statement somewhat to give you an overview of the statement’s essential elements and how they fit together:

LOAD DATA [LOCAL] 
INFILE 'file_name'
[REPLACE | IGNORE]
INTO TABLE table_name
FIELDS
  [TERMINATED BY 'string']
  [[OPTIONALLY] ENCLOSED BY 'char']
  [ESCAPED BY 'char']
LINES
  [STARTING BY 'string']
  [TERMINATED BY 'string']
IGNORE n LINES
[(column_list)]

The LOAD DATA clause is where you specify whether to include the LOCAL option. As I mentioned earlier, this is the approach I’ve taken in this article. The next clause, INFILE, specifies the path and filename (in quotes) of the source text file. You can provide an absolute path or relative path. If relative, the path is relative to the invocation directory.

You can then specify either REPLACE or IGNORE, which are both optional. The REPLACE option tells MySQL to replace existing rows that have the same unique key value. The IGNORE option tells MySQL to ignore rows with the same key value. The IGNORE option has the same effect as the LOCAL option, so if you’re using LOCAL, you never need to use IGNORE. However, you can use the REPLACE option with LOCAL.

The INTO TABLE clause specifies the name of the target table. The main thing here is to be sure that you’ve been granted the privileges necessary to add data to that table.

The FIELDS clause comes next, and it supports one or more of the following three subclauses:

  • The TERMINATED BY subclause specifies the string used in the text file to terminate each field. The string can be one or more characters. The default value is \t for tab, which means that tabs are used to separate field values.
  • The ENCLOSED BY subclause specifies the character used in the text file to enclose values, such as quotation marks around string values. The OPTIONALLY keyword, which itself is optional, is used “if the input values are not necessarily enclosed within quotation marks,” according to MySQL documentation. (More on that in a bit.) The default value for the ENCLOSED BY subclause is an empty string, indicating that the fields are not enclosed in quoting characters.
  • The ESCAPED BY subclause specifies the character used in the text file for escaping characters that could impact how MySQL interprets the data. The default value is a backslash (\), which is also used in MySQL to escape characters, including the backslash itself. Many programming languages also use the backslash to escape characters.

The FIELDS clause is itself optional, but if you include it, you must specify at least one of the subclauses.

Note: The OPTIONALLY option in the ENCLOSED BY subclause is one of the most confusing elements in the LOAD DATA statement. Its use made no difference in the various tests I ran. For example, in one test, I enclosed all the values in the manufacturer fields in double quotation marks except for one. MySQL imported the data correctly whether or not I included the OPTIONALLY option. I also tested the option using NULL values and empty strings and received the same results. There might be use cases in which the option does make a difference, but I have yet to discover them. However, the FIELDS and LINES clauses in the LOAD DATA statement are the same as the SELECT…INTO OUTFILE statement, and much of the discussion in the MySQL documentation about the OPTIONALLY option is related to SELECT…INTO OUTFILE, so perhaps that is where it is most relevant.

Like the FIELDS clause, the LINES clause is also optional. The LINES clause supports the following two subclauses:

  • The STARTING BY clause specifies the common prefix used at the beginning of each line in the text file. The default value is an empty string, indicating that no specific prefix is used. If a prefix is specified and a line does not contain that prefix, MySQL skips the line when importing the data.
  • The TERMINATED BY clause specifies the string used in the text file to terminate each line. The string can be one or more characters. The default value is \n, which refers to a newline character (linefeed). I created my text file in Apple’s TextEdit app, so the default worked on my system, but not all systems operate the same. For example, if you create the text files in Windows, you might need to specify '\r\n' as the TERMINATED BY value.

If you include both the FIELDS clause and LINES clause, the FIELDS clause must come first. The IGNORE n LINES clause comes after these two clauses. The IGNORE n LINES clause specifies the number of lines to skip at the beginning of the file when importing the data. The clause is commonly used when the file contains a header row, in which case, the clause would be written as IGNORE 1 LINES.

The final clause is the list of columns, which are enclosed in parentheses and separated by commas. Although this clause is optional, you will likely include it in most of your statements, unless you’re source data contains a field for every column and the fields are in the same order as the columns.

The LOAD DATA statement contains a few other clauses, but the ones I’ve shown you here are plenty for you to get started. Even so, I recommend that you review the MySQL topic LOAD DATA Statement to learn more about the statement’s various elements.

Importing a CSV file

Now that you’ve been introduced to the LOAD DATA statement, let’s look at some examples that show it in action. You can refer back to the previous section if needed as you work through the following sections.

In preparation for the first example, I created a file named manufacturers1.csv and added the following data:

101,Airbus
102,Beagle Aircraft Limited
103,Beechcraft
104,Boeing
105,Bombardier
106,Cessna
107,Embraer

I saved the file to the folder /Users/mac3/Documents/TravelData/ on my local computer. If you plan to try out the examples for yourself, you can save the files to any location on your system that Workbench can access. Just be sure to update the file path in the examples before you run your statements.

After I created the manufacturers1.csv file, I ran the following LOAD DATA statement, which saves the data to the manufacturers table in the travel database:

LOAD DATA LOCAL INFILE 
  '/Users/mac3/Documents/TravelData/manufacturers1.csv' 
INTO TABLE manufacturers 
FIELDS TERMINATED BY ',' 
(manufacturer_id, manufacturer);

As you can see, the LOAD DATA clause includes the LOCAL option, and the INFILE clause specifies the source file. These are followed by the INTO TABLE clause, which points to the manufacturers table.

The next clause, FIELDS, includes the TERMINATED BY subclause, which specifies that a comma is used as the field separator, rather than the default tab. The statement then provides the names of the two target columns—manufacturer_id and manufacturer—which are enclosed in parentheses.

When you run the statement, MySQL extracts the data from the file and populates the manufacturers table. You can verify that the data has been added to the table by running the following SELECT statement:

SELECT * FROM manufacturers;

The SELECT statement returns the results shown in the following figure, which indicates that the data was successfully inserted into the table. Keep this statement handy because you can use it to verify your results for the remaining examples.

To keep things simple for this article, you can also run the following TRUNCATE statement to remove the data from the manufacturers table in preparation for the next example:

TRUNCATE TABLE manufacturers;

You should keep this statement handy as well. You’ll want to run it after most of the following examples, except in a couple instances where I demonstrate specific concepts, in which case, I’ll let you know not to run it.

Ignoring the first lines in an import file

Some of the source files that you work with might contain a header row that lists the field names or include other types of information, such as comments about when and where the file was generated. You can skip these rows when importing the data by including the IGNORE n LINES clause in your LOAD DATA statement.

To see how this works, create a text file named manufacturers2.csv file, add the following data to the file, and save it to the same location as the manufacturers1.csv file:

manufacturer_id,manufacturer
101,Airbus
102,Beagle Aircraft Limited
103,Beechcraft
104,Boeing
105,Bombardier
106,Cessna
107,Embraer

Now run the following LOAD DATA statement, which includes an IGNORE 1 LINES clause that tells MySQL to skip the first row:

LOAD DATA LOCAL INFILE 
  '/Users/mac3/Documents/TravelData/manufacturers2.csv' 
INTO TABLE manufacturers 
FIELDS TERMINATED BY ',' 
IGNORE 1 LINES
(manufacturer_id, manufacturer);

After you execute the LOAD DATA statement, you can again run your SELECT statement to verify that the correct data has been added. The results should indicate that the header row has been omitted. You can then run your TRUNCATE statement again in preparation for the next example.

The IGNORE n LINES clause is not limited to one row. For instance, the following IGNORE n LINES clause specifies five rows rather than one:

LOAD DATA LOCAL INFILE 
  '/Users/mac3/Documents/TravelData/manufacturers2.csv' 
INTO TABLE manufacturers 
FIELDS TERMINATED BY ',' 
IGNORE 5 LINES
(manufacturer_id, manufacturer);

When you run the SELECT statement this time, you should get the results shown in the following figure. (Don’t truncate the table for this example or the next one because I want to point out of a couple other issues.)

As you can see, the table contains only the last three rows from the source file. However, suppose that you were to run the statement again, only this time, specifying only one row in the IGNORE n LINES clause:

LOAD DATA LOCAL INFILE 
  '/Users/mac3/Documents/TravelData/manufacturers2.csv' 
INTO TABLE manufacturers 
FIELDS TERMINATED BY ',' 
IGNORE 1 LINES
(manufacturer_id, manufacturer);

When you execute the statement, MySQL tries to insert all seven rows of data into the target table, but only the first four rows succeed. After running the statement, MySQL returns the following message:

4 row(s) affected, 3 warning(s): 1062 Duplicate entry '105' for key 'manufacturers.PRIMARY' 1062 Duplicate entry '106' for key 'manufacturers.PRIMARY' 1062 Duplicate entry '107' for key 'manufacturers.PRIMARY' Records: 7 Deleted: 0 Skipped: 3 Warnings: 3

The message indicates that the existing rows with manufacturer_id values of 105, 106, and 107 were skipped. That is, no new rows with these values were inserted into the table. Only the first four rows were added. If you run the SELECT statement again, you should receive results similar to those shown in the following figure. (Once again, don’t truncate the table; leave it for the next example.)

The table now contains all seven rows of data, but if you look closely at the timestamps in the figure, you’ll see that the last three rows precede the first five rows by nearly 30 seconds. (I ran the last two LOAD DATA statements fairly close together.)

Now suppose you run the same LOAD DATA statement again, only this time you include the REPLACE option:

LOAD DATA LOCAL INFILE 
  '/Users/mac3/Documents/TravelData/manufacturers2.csv' 
REPLACE
INTO TABLE manufacturers 
FIELDS TERMINATED BY ',' 
IGNORE 1 LINES
(manufacturer_id, manufacturer);

When you execute the statement, MySQL now returns the following message:

14 row(s) affected Records: 7 Deleted: 7 Skipped: 0 Warnings: 0

The message indicates that 14 rows were processed. However, only seven records were affected, and seven were deleted. This means that the database engine deleted the seven existing records and re-added them to the table. You can verify this be running the SELECT statement again. Your results should show different timestamps than in the previous results, with the all values very close, if not the same.

You can now rerun your TRUNCATE TABLE statement to prepare the manufacturers table for the next example.

Working with quoted fields in the import file

When importing data, your text files might include some or all fields enclosed in quotation marks. For example, I created the manufacturers3.csv file using the following data, which includes single quotation marks around the string values:

manufacturer_id,manufacturer
101,'Airbus'
102,'Beagle Aircraft Limited'
103,'Beechcraft'
104,'Boeing'
105,'Bombardier'
106,'Cessna'
107,'Embraer'

To handle the quoted fields, you can add an ENCLOSED BY subclause to your FIELDS clause, as shown in the following example:

LOAD DATA LOCAL INFILE 
  '/Users/mac3/Documents/TravelData/manufacturers3.csv' 
INTO TABLE manufacturers 
FIELDS TERMINATED BY ',' ENCLOSED BY '\''
IGNORE 1 LINES
(manufacturer_id, manufacturer);

The ENCLOSED BY subclause specifies that a single quotation mark is used to enclose fields. The quotation mark is preceded by a backslash to escape the character when submitting it to the database engine. If you don’t use the ENCLOSED BY subclause, the database engine will treat the quotation marks as literal values and store them along with the rest of the values.

After you execute the LOAD DATA statement, you can run your SELECT statement to verify the results and then run your TRUNCATE statement to prepare the manufacturers table for the next example.

When you specify a single quotation mark in the ENCLOSED BY subclause, you can enclose it in double quotes, rather than escaping it with a backslash:

LOAD DATA LOCAL INFILE 
  '/Users/mac3/Documents/TravelData/manufacturers3.csv' 
INTO TABLE manufacturers 
FIELDS TERMINATED BY ',' ENCLOSED BY "'"
IGNORE 1 LINES
(manufacturer_id, manufacturer);

In some cases, the text file will use double quotation marks to enclose field values, rather than single quotation marks. To demonstrate how to handle these, I created the manufacturers4.csv file using the following data:

manufacturer_id,manufacturer
101,"Airbus"
102,"Beagle Aircraft Limited"
103,"Beechcraft"
104,"Boeing"
105,"Bombardier"
106,"Cessna"
107,"Embraer"

To handle this file, the ENCLOSED BY subclause should be modified to specify a double quotation mark, enclosing it in single quotation marks:

LOAD DATA LOCAL INFILE 
  '/Users/mac3/Documents/TravelData/manufacturers4.csv' 
INTO TABLE manufacturers 
FIELDS TERMINATED BY ',' ENCLOSED BY '"'
IGNORE 1 LINES
(manufacturer_id, manufacturer);

After you run this LOAD DATA statement, you can once again run your SELECT statement to verify the results. Once you’ve reviewed them, you can then run your TRUNCATE statement in preparation for the next example. (You should do this for all the remaining examples.)

Working with different formats in your text files

The text files that you work with might be table-delimited rather than comma-delimited, and they might include other elements that require special handling. Consider the manufacturers5.txt file, which I created with the following data:

manufacturer_id        manufacturer
*,*101  "Airbus"
*,*102  "Beagle Aircraft Limited"
*,*103  "Beechcraft"
*,*104  "Boeing"
*,*105  "Bombardier"
*,*106  "Cessna"
*,*107  "Embraer"

In this case, a tab is used as the field separator, and each line is preceded by the *,* characters. As a result, you don’t need to specify the TERMINATED BY subclause in the FIELDS clause because the tab is the default value, but you do need to take steps to handle the line prefix. For this, you should add a LINES clause with a STARTING BY subclause that specifies the prefix characters:

LOAD DATA LOCAL INFILE 
  '/Users/mac3/Documents/TravelData/manufacturers5.txt' 
INTO TABLE manufacturers 
FIELDS ENCLOSED BY '"'
LINES STARTING BY '*,*'
IGNORE 1 LINES
(manufacturer_id, manufacturer);

When you run this statement, MySQL will use the prefix characters to determine which rows to add, while stripping out the characters in the process.

As already pointed out, the preceding example does not include a TERMINATED BY subclause in the FIELDS clause. It also does not include a TERMINATED BY subclause in the LINES clause because the text file uses the default linefeed value. However, you can still include both clauses if you want:

LOAD DATA LOCAL INFILE 
  '/Users/mac3/Documents/TravelData/manufacturers5.txt' 
INTO TABLE manufacturers 
FIELDS TERMINATED BY '\t' ENCLOSED BY '"'
LINES TERMINATED BY '\n' STARTING BY '*,*'
IGNORE 1 LINES
(manufacturer_id, manufacturer);

When using the STARTING BY subclause, be aware that your text file must use these prefixes consistently or you might get unexpected results. For example, the following text file, manufacturers6.txt, includes a line with two records but no prefix in front of the first record:

manufacturer_id        manufacturer
*,*101  "Airbus"
*,*102  "Beagle Aircraft Limited"
*,*103  "Beechcraft"
104     "Boeing" *,*105 "Bombardier"
*,*106  "Cessna"
*,*107  "Embraer"

After you’ve created the file on your system, you can run the following LOAD DATA statement to see what happens:

LOAD DATA LOCAL INFILE 
  '/Users/mac3/Documents/TravelData/manufacturers6.txt' 
INTO TABLE manufacturers 
FIELDS ENCLOSED BY '"'
LINES STARTING BY '*,*'
IGNORE 1 LINES
(manufacturer_id, manufacturer);

When you execute this statement, MySQL skips the record with a manufacturer_id value of 104 but still adds the record with a value of 105. You can verify this by again running your SELECT statement, which returns the results shown in the following figure.

In some cases, you might run into text files whose lines are terminated with nontraditional characters (as opposed to the usual linefeeds or returns). For example, I created the manufacturers7.txt file using the following data, which separates the lines with triple hash marks (###):

manufacturer_id        manufacturer###101      "Airbus"###102  "Beagle Aircraft Limited"###103 "Beechcraft"###104      "Boeing"###105  "Bombardier"###106      "Cessna"###107  "Embraer"

To accommodate this file, you need to include a TERMINATED BY subclause in your LINES clause that specifies the hashmarks:

LOAD DATA LOCAL INFILE 
  '/Users/mac3/Documents/TravelData/manufacturers7.txt' 
INTO TABLE manufacturers 
FIELDS ENCLOSED BY '"'
LINES TERMINATED BY '###'
IGNORE 1 LINES
(manufacturer_id, manufacturer);

When you run this statement, the database engine will know how to interpret the hashmarks and will insert the data accordingly, stripping out the hashmarks in the process.

In some cases, you might also run into a text file that uses a character other than the backslash to escape characters within fields. For example, the manufacturers8.txt file contains seven lines of comma-delimited fields, one of which includes a comma in the manufacturer name:

manufacturer_id,manufacturer
101,Airbus
102,Beagle Aircraft Limited
103,Beechcraft
104,Aviat Aircraft^, Inc.
105,Bombardier
106,Cessna
107,Embraer

In this case, the name’s comma is escaped with a caret (^). Because this character is not a backslash (the default escape character), you need to add an ESCAPE BY clause that specifies the caret, as shown in the following example:

LOAD DATA LOCAL INFILE 
  '/Users/mac3/Documents/TravelData/manufacturers8.txt' 
INTO TABLE manufacturers 
FIELDS TERMINATED BY ',' ESCAPED BY'^'
IGNORE 1 LINES
(manufacturer_id, manufacturer);

If you do not include the ESCAPE BY clause, the database engine will retain the caret but truncate the manufacturer name, as in Aviat Aircraft^. However, if you include the clause, MySQL will strip out the caret and treat the comma as a literal value, resulting in a column value of Aviat Aircraft, Inc., rather than the truncated version.

Getting started with importing data in MySQL

As mentioned earlier, the LOAD DATA statement includes other elements than what I’ve shown you here. There are also other options for importing data, such as the mysqlimport command-line utility, which generates and sends LOAD DATA statements to the MySQL server. Most of the utility’s options correlate directly to the LOAD DATA statement. Another option is the Table Data Import wizard in MySQL Workbench. The wizard walks you through the process of importing data from a CSV or JSON file.

If you work with MySQL databases on a regular bases, chances are good that you’ll want to import data from text files, even if only to set up test or development environments. In most cases, what I’ve shown you here will be enough to get you started with the LOAD DATA statement. Just know that that you might run into situations that I haven’t covered, in which case, it’s always a good idea to review other MySQL documentation to help you fill in the gaps.

Appendix: Preparing your MySQL environment

When creating the examples for this article, I used a Mac computer that was set up with a local instance of MySQL 8.0.29 (Community Server edition). I also used MySQL Workbench to interface with MySQL. The examples import data from a set of sample text files that I created in Apple’s text editor, TextEdit.

I provide you with the files’ contents throughout the article, along with the example LOAD DATA statements. If you plan to try out these examples, you can create the files on your own system as you work through those examples. Before you get started, however, you should run the following script against your MySQL instance:

DROP DATABASE IF EXISTS travel;

CREATE DATABASE travel;
USE travel;
CREATE TABLE manufacturers (
  manufacturer_id INT UNSIGNED NOT NULL,
  manufacturer VARCHAR(50) NOT NULL,
  create_date TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
  last_update TIMESTAMP NOT NULL 
    DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
  PRIMARY KEY (manufacturer_id) );

The script creates the travel database and adds the manufacturers table. Otherwise, that’s all you need for the try out the examples (in addition to creating the source text files). For most of the examples, I simply truncated the data to prepare the table for the next example. If you already created the database and table for previous articles, I recommend that you re-create them now or at least truncate the manufacturers table before getting started.

 

The post Importing data into a MySQL database using LOAD DATA appeared first on Simple Talk.



from Simple Talk https://ift.tt/jGM42Nz
via

Monday, May 1, 2023

PostgreSQL Basics: Essential psql Tips and Tricks

Having access to the psql command-line tool is essential for any developers or DBAs that are actively working with and connecting to PostgreSQL databases. In our first article, we discussed the brief history of psql and demonstrated how to install it on your platform of choice and connect to a PostgreSQL database.

In this article we’ll get you up and running with all of the essential things you need to know to start on your journey to becoming a psql power-user. From basic command syntax to the most common (and helpful) meta-commands, it’s all covered throughout the rest of the article.

To get the most value out of this content, you should have psql installed and connected to a PostgreSQL database so that you can try the commands as you read.

Essential Usability Tips

The psql utility is packed with many helpful commands to help you explore and manage your database. Any slash command (\) is used to specify a meta-command that will typically run the necessary SQL queries in the background and return the results in a readable format.

First, let’s look at a few tips about how psql works as a command line tool. Knowing how to enable certain features or find help for each meta-command will go a long way in helping you to be a successful user of the tool.

The Semicolon is Required

PostgreSQL adheres to the ANSI SQL standard which specifies the semicolon for statement termination. In psql, you signal the end of a SQL statement by adding the semicolon and pressing enter.

If you don’t add a semicolon, psql will simply provide a new line for you to keep typing as shown below.

pagila_dev=# select * from film
pagila_dev-# ;

The query will not be executed until the semicolon is added.

Command History and Paging

psql is a terminal application and as such it keeps a history of the queries and commands that you have executed. Therefore, you can use the up and down arrows on your keyboard to page through previous commands and statements. This is helpful when you want to run a statement multiple times but change a filter each time.

The history is stored in a file on your local client which means it will be different from computer to computer. You can also configure psql to create a different history file per database or server using the HISTFILE variable in the .psqlrc file.

To see a list of the commands that be been run, use the \s command.

postgres=# \s

\c pagila_
\c pagila_dev
\df
\x
\df
select * from film
;
\s

Autocompletion

psql supports tab-based autocompletion. For many commands, you can use the TAB key to trigger autocompletion or suggestion. If you want to list a table or connect to a different database, begin with the meta-command and then begin to type the object name and press TAB. If there would be more than one match, psql will provide possible matches similar to a Linux terminal.

Expanded Results Table Formatting

One of the first helpful hints I learned early on with psql was that there are two modes for displaying both query and meta-command results. Normally, psql will do the hard work of formatting rows and columns of data in a monospaced font with the right amount of padding for everything to line up – within reason. When terminal wrapping takes place, however, it can be challenging to figure out which data goes with which column.

In these cases, you can print the results in an “expanded” format which is essentially a crosstab of each row showing the column headings on the left and each value on the right. In this format you can page through results one at a time.

You can toggle expanded mode on and off by using the \x command. Below we show a listing of objects in the database, first in the normal table mode and then with expanded mode turned on.

postgres=# \d
                  List of relations
 Schema |          Name           | Type  |  Owner
--------+-------------------------+-------+----------
 public | example_tbl             | table | postgres
 public | pg_stat_statements      | view  | postgres
 public | pg_stat_statements_info | view  | postgres
(3 rows)

postgres=# \x
Expanded display is on.
postgres=# \d
List of relations
-[ RECORD 1 ]-------------------
Schema | public
Name   | example_tbl
Type   | table
Owner  | postgres
-[ RECORD 2 ]-------------------
Schema | public
Name   | pg_stat_statements
Type   | view
Owner  | postgres
-[ RECORD 3 ]-------------------
Schema | public
Name   | pg_stat_statements_info
Type   | view
Owner  | postgres

Quitting the psql Session

Finally, I’d hate for you to feel like you can’t get out of the interactive shell. Any time you want to quit your current psql session, simply use the \q meta-command to get back to your terminal prompt.

postgres=# \q

ryan@redgate-laptop:~$

System Objects and Additional Details

As we review some of the essential commands below you will notice a pattern where many of the commands have multiple forms. Adding a capital S to the end of many commands will include system objects in the output. Also, including a + at the end of the command will return additional details, analogous to a an advanced output mode.

For example, the two commands below both list the tables, views, and sequences of a database, but the second form provides additional details.

postgres=# \d
                  List of relations
 Schema |          Name           | Type  |  Owner
--------+-------------------------+-------+----------
 public | example_tbl             | table | postgres
 public | pg_stat_statements      | view  | postgres
 public | pg_stat_statements_info | view  | postgres
...

postgres=# \d+
                                              List of relations
 Schema |          Name           | Type  |  Owner   | Persistence | Access method |    Size    | Description
--------+-------------------------+-------+----------+-------------+---------------+------------+-------------
 public | example_tbl             | table | postgres | permanent   | heap          | 8192 bytes |
 public | pg_stat_statements      | view  | postgres | permanent   |               | 0 bytes    |
 public | pg_stat_statements_info | view  | postgres | permanent   |               | 0 bytes    |

postgres=# \dS+
                                               List of relations
   Schema   |              Name               | Type  |  Owner   | Persistence | Access method |    Size    | Description
------------+---------------------------------+-------+----------+-------------+---------------+------------+-------------
 pg_catalog | pg_aggregate                    | table | postgres | permanent   | heap          | 56 kB      |
 pg_catalog | pg_am                           | table | postgres | permanent   | heap          | 40 kB      |
 pg_catalog | pg_amop                         | table | postgres | permanent   | heap          | 88 kB      |
 pg_catalog | pg_amproc                       | table | postgres | permanent   | heap          | 72 kB      |
 pg_catalog | pg_attrdef                      | table | postgres | permanent   | heap          | 8192 bytes |
...
 public     | example_tbl                     | table | postgres | permanent   | heap          | 8192 bytes |
 public     | pg_stat_statements              | view  | postgres | permanent   |               | 0 bytes    |
 public     | pg_stat_statements_info         | view  | postgres | permanent   |               | 0 bytes    |

 

Getting help

Although the output can be overwhelming, you can always view the psql help file that will show you an expansive list of meta-command patterns. Notice that the output is grouped into categories.

postgres=# \?
General
  \copyright             show PostgreSQL usage and distribution terms
  \crosstabview [COLUMNS] execute query and display result in crosstab
  \errverbose            show most recent error message at maximum verbosity
  \g [(OPTIONS)] [FILE]  execute query (and send result to file or |pipe);
                         \g with no arguments is equivalent to a semicolon
  \gdesc                 describe result of query, without executing it
  \gexec                 execute query, then execute each value in its result
  \gset [PREFIX]         execute query and store result in psql variables
  \gx [(OPTIONS)] [FILE] as \g, but forces expanded output mode
  \q                     quit psql
  \watch [SEC]           execute query every SEC seconds

Help
  \? [commands]          show help on backslash commands
  \? options             show help on psql command-line options
  \? variables           show help on special variables
  \h [NAME]              help on syntax of SQL commands, * for all commands

Query Buffer
  \e [FILE] [LINE]       edit the query buffer (or file) with external editor
  \ef [FUNCNAME [LINE]]  edit function definition with external editor
...

Informational
  (options: S = show system objects, + = additional detail)
  \d[S+]                 list tables, views, and sequences
  \d[S+]  NAME           describe table, view, sequence, or index
  \da[S]  [PATTERN]      list aggregates
  \dA[+]  [PATTERN]      list access methods
…

Essential Meta-commands

In my experience with PostgreSQL over the last few years, particularly coming from many years of SQL Server work, learning how to effectively use basic commands in psql has proven to be useful and time saving. Below are the initial set of commands that will help you navigate the PostgreSQL cluster and databases.

There are certainly many more commands than these, but I believe these are the high-level set that you should learn at the outset.

Connecting to a Different Database

The \c command will connect to a new database on the same server. If you connected to the server with the -W switch, then every time you connect to a different database, you will be prompted for the password again, which is almost always a nuisance so I don’t recommend it.

postgres=# \c flywaytest

psql (15.0 (Ubuntu 15.0-1.pgdg20.04+1), server 15.1 (Debian 15.1-1.pgdg110+1))
You are now connected to database "flywaytest" as user "postgres".

flywaytest=#

Notice that the default psql prompt shows the database name of the current connection.

List All Databases

The \l command will list any databases in the current server along with the specified access privileges. Seeing that the database exists in this list does not imply that the current role can connect (\c) to the database. Adding the + will provide additional information including database size.

postgres=# \l+
                                                    List of databases
       Name        |  Owner   | Encoding |  Collate   |   Ctype    | ICU Locale | Locale Provider |   Access privileges
-------------------+----------+----------+------------+------------+------------+-----------------+-----------------------
 advent_of_code    | postgres | UTF8     | en_US.utf8 | en_US.utf8 |            | libc            | postgres=CTc/postgres+
                   |          |          |            |            |            |                 | rptusr=c/postgres
 bulk_example      | postgres | UTF8     | en_US.utf8 | en_US.utf8 |            | libc            |
 flywaytest        | postgres | UTF8     | en_US.utf8 | en_US.utf8 |            | libc            |
 flywaytest_shadow | postgres | UTF8     | en_US.utf8 | en_US.utf8 |            | libc            |

Display Object Details

There are many \d commands in psql. Although most commands aren’t given specific names, most folks in the community refer to this as either the “describe”, “display”, or “details” command. Much like a CLI that allows you to get help for each command by typing something like “help [command]”, psql uses the \d command almost like that.

Most of the \d commands will provide additional details by adding the + to the end. I’ll only show a few examples of that below, but feel free to try it with any of these commands to get more detail.

Display table, view, and sequence objects

The default action for the describe command is to list all tables, views, and sequences in the current database. We showed examples of the detailed output above when discussing the + operator.

postgres=# \d
                  List of relations
 Schema |          Name           | Type  |  Owner
--------+-------------------------+-------+----------
 public | example_tbl             | table | postgres
 public | pg_stat_statements      | view  | postgres
 public | pg_stat_statements_info | view  | postgres

Describe table, view, or sequence details

You can name a specific object to get additional information. Using the + operator will also list constraints and indexes of a table.

postgres=# \d+ example_tbl
                                       Table "public.example_tbl"
 Column |  Type   | Collation | Nullable | Default | Storage  | Compression | Stats target | Description
--------+---------+-----------+----------+---------+----------+-------------+--------------+-------------
 id     | integer |           | not null |         | plain    |             |              |
 notes  | text    |           |          |         | extended |             |              |
Indexes:
    "idx_example_notes" btree (notes)
Access method: heap

Display Specific Object Types

As you might expect, the psql developers provided specific commands for listing individual object types. Adding different letters after the \d command will list only that type of object. All lists support additional detail using the +.

  • E = foreign table (provided by one of many foreign data wrappers)
  • i = indexes
  • m = materialized views
  • s = sequences
  • t = tables
  • v = views
postgres=# \dt

            List of relations
 Schema |    Name     | Type  |  Owner
--------+-------------+-------+----------
 public | example_tbl | table | postgres

Display Roles and Members

Roles are used for connecting to PostgreSQL, assigning database privileges, and specifying object ownership. See our series of posts on PostgreSQL security for more details about Roles.

postgres=# \du
                                        List of roles
 Role name |                         Attributes                         |     Member of
-----------+------------------------------------------------------------+---------------
 dev1      |                                                            | {devgrp}
 dev2      |                                                            | {devgrp}
 devgrp    | Cannot login                                               | {}
 postgres  | Superuser, Create role, Create DB, Replication, Bypass RLS | {}
 read_only | Cannot login                                               | {pg_read_all_data}
 rptusr    |                                                            | {}

Display Installed Extensions

Extensions are one of the more powerful features of PostgreSQL. Knowing what extensions are installed in a specific database helps you maintain better visibility into what features your application may be relying upon.

postgres=# \dx
                                            List of installed extensions
        Name        | Version |   Schema   |                              Description
--------------------+---------+------------+------------------------------------------------------------------------
 pg_stat_statements | 1.10    | public     | track planning and execution statistics of all SQL statements executed
 plpgsql            | 1.0     | pg_catalog | PL/pgSQL procedural language
 tablefunc          | 1.0     | public     | functions that manipulate whole tables, including crosstab

Display Schemas

Often, your application database will have multiple schemas depending on the design and access requirements of your database. By default, psql will only show you the schemas that are part of your search_path, which for most users is just the public schema by default. If you want to see what other schemas are available in your database, \dn will show you user-defined schemas only.

postgres=# \dn
       List of schemas
   Name   |       Owner
----------+-------------------
 accounts | postgres
 public   | pg_database_owner

Display User-defined Functions

PostgreSQL is a function-heavy database. If you come from another database like SQL Server, this may feel a bit counterintuitive because a lot of conversation and training talks about the pitfalls of using functions, particularly in regards to query performance. That said, being able to quickly list the various kinds of functions that are currently in the database, including the input types, is very helpful.

postgres=# \df
                                                         List of functions
 Schema |            Name            | Result data type |                        Argument data types                         | Type
--------+----------------------------+------------------+--------------------------------------------------------------------+------
 public | _group_concat              | text             | text, text                                                         | func
 public | film_in_stock              | SETOF integer    | p_film_id integer, p_store_id integer, OUT p_film_count integer    | func
 public | film_not_in_stock          | SETOF integer    | p_film_id integer, p_store_id integer, OUT p_film_count integer    | func
 public | get_customer_balance       | numeric          | p_customer_id integer, p_effective_date timestamp with time zone   | func
 public | inventory_held_by_customer | integer          | p_inventory_id integer                                             | func
 public | inventory_in_stock         | boolean          | p_inventory_id integer                                             | func
 public | last_day                   | date             | timestamp with time zone                                           | func
 public | rewards_report             | SETOF customer   | min_monthly_purchases integer, min_dollar_amount_purchased numeric | func

Editing SQL Outside of the Terminal

Most of the time psql is being used as an interactive terminal. Sometimes, however, it’s useful to open a query in an editor for larger changes and iterations.

Using the \e command will open the current query buffer (or the most recently executed command) into the editor. Upon exiting the editor, if the SQL query is complete (terminated with a semicolon), it will be executed immediately.

Alternatively, adding a filename after the \e command will open that file for editing and then execute the query if it is complete. (eg. \e my_query.sql)

Finally, you can view the code for a function or view in an external editor by using a specific version of the edit command.

\ef {function name}
\ev {view name}

Show Hidden Meta-command SQL

One final thing to know as you learn more about the psql interactive shell is that it is possible to see the SQL queries that are being run for each meta-command that you run. This can be a very helpful way to learn more about the catalog tables that help run your PostgreSQL instance. Fair warning, there are often multiple SQL queries being executed to get the desired output, so it’s often helpful to only enable it for short periods as you’re trying to learn about something specific.

There are two ways to enable this mode in psql.

Option 1: psql -E connection parameter

This will enable hidden queries (which means they are displayed) for the duration of your psql connection.

psql -E postgresql://[username]:[password]@[hostname]:[port]/[database name]

Option 2: \set meta-command

If you are already connected to a database, you can set the variable which show hidden queries at will.

postgres=# \set ECHO_HIDDEN true

Conclusion

Knowing how to install and use the psql command line tool is an essential skill when using PostgreSQL. Because there is no fully standardized IDE, easily querying details about your database from the catalog tables can be challenging at times, especially if you are new to PostgreSQL. Learning how the basic meta-commands work can dramatically improve your development and administration tasks.

The post PostgreSQL Basics: Essential psql Tips and Tricks appeared first on Simple Talk.



from Simple Talk https://ift.tt/alHYjD4
via

Saturday, April 29, 2023

Introduction to Using Bitbucket and CI/CD for Your App

If you have been in the DevOps space, you should know about version control and must have worked with 0ne. But, have you heard of BitBucket? No? Well, this tutorial is for you.

Bitbucket is a web-based platform that provides hosting services for version control repositories, specifically for source code and development projects. It offers support for two different version control systems: Mercurial and Git. It is owned by Atlassian and used for source code and development projects that use either Mercurial or Git version control systems. It provides a centralized location for storing and managing code, facilitates team collaboration and version control, and includes features such as pull requests, code reviews, and issue tracking. Bitbucket is widely used by software development teams for both personal and enterprise projects.

Bitbucket integrates well with many third-party continuous integrations (CI) tools, including Jenkins, Travis CI, CircleCI, Bamboo, and more. This integration allows developers to automate the build, test, and deployment processes for their software projects, making it easier to identify and resolve bugs and deliver high-quality software more quickly. Bitbucket provides a variety of APIs and integrations that allow developers to connect it with other tools and systems, including issue trackers, chat apps, and other development and collaboration tools.

This tutorial ‌will teach you how to get started with Bitbucket. You will start with learning how to push an HTML project to a Bitbucket repository, configure Bitbucket pages for that respository so it can be viewed over the web browser, create and push a VueJS project to the same Bitbucket repository and then see how to configure CI/CD workflows with CircleCI for that Bitbucket repository.

In this article I am going to go through the follow steps to demonstrate using Bitbucket in your projects

  • Prerequisites
  • Initializing a Hello_World project.
  • Creating a Bitbucket workspace and repository.
  • Pushing your code to your Bitbucket repository.
  • Hosting repository with Bitbucket pages.
  • Using a third-party CI tool with Bitbucket.

Prerequisites

These are the things you will need to have (or expect to get if you want to follow along with the examples in this article)

  • This tutorial uses a Linux machine with An Ubuntu 22.04 LTS OS. Every other OS works fine.
  • A text editor (E.g VScode).
  • A Bitbucket Cloud account. You can register here if you don’t have one.
  • An Atlassian account. If you don’t have one, sign up for a free Atlassian account first.
  • Git installed locally on your machine, otherwise, you can follow this guide to get it installed depending on your OS.
  • Circle CI account created with your Atlassian Bitbucket account

Initializing a Hello_World project

Prior to getting started with Bitbucket, you’ll need to first have a project to work with. For demo and simplicity’s sake, you will create a project that simply outputs “Hello World” to the browser.

Create a project directory to store the files for the hello_world project. You can name this directory whatever you like – this tutorial uses hello_world.

mkdir hello_world #creates the hello_world directory 

cd hello_world #goes into the hello_world directory 

code . #opens up the hello_world directory via your 
       #default code editor

Fig 1: Creating project directory “hello_world”

Create an index.html file and paste in the code snippet below:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Bitcket App</title>
    <!-- Google fonts -->
    <link rel="preconnect" href="https://fonts.googleapis.com">
    <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
    <link href="https://fonts.googleapis.com/css2?family=IBM+Plex+Sans:wght@100&display=swap" rel="stylesheet">
    <!-- Internal styles -->
    <style>
        * {padding: 0; margin: 0; box-sizing: border-box;}
          body {background-color: hsl(46, 100%, 50%);  
          Font-family:'IBM Plex Sans', sans-serif; margin: 
          60px; display: flex; justify-content: center; 
          align-items: center;}
        h1   {color: hsl(0, 4%, 10%); text-align: center;}
        div { border: 5px solid hsl(318, 73%, 22%); width: 500px;
              margin: 0 auto; padding: 10px;}
    </style>
</head>
<body>
    <div>
        <h1>Hello World</h1>
    </div>
</body>

When you view this over a web browser, this is how the web page will look like:

Fig 2: Viewing hello_world project over a web browser

The output above simply displays Hello World to the browser.

Creating a Bitbucket Workspace and Repository

Just like GitHub, you need to have a repository to house the application you’d like to save on Bitbucket. If you are logging in to Bitbucket for the first time, you will be asked to first create a workspace.

A Bitbucket workspace is a container for projects and repositories in Bitbucket, where users can store, manage, and collaborate on their source code. It allows teams to organise their work, assign access permissions to different users, and track changes to code in a centralised location. A workspace can contain multiple repositories, each with its own set of files and folders.

Be sure to click on the create workspace button to create your Bitbucket workspace, just like what the output below does:

Fig 3: Initializing creating a bit bucket workspace

A new page will show up asking you to add the name of your workspace. This tutorial uses my-helloworldworkspace as the name of the workspace. You can name yours whatever you like. Additionally, you have the option of making this workspace public or private. In this tutorial, you’ll on-check the checkbox to enable the workspace to be public as shown in the output below:

Fig 4: Creating a Bitbucket workspace

Once you have created your workspace, you will be directed to your Bitbucket dashboard.

This dashboard provides a centralized view of your repositories, projects, pull requests, issues, and more. It also allows you to manage your code, collaborate with others, and track the progress of your development projects.

To create a repository, click on the create button on the navigation menu and select Repository from the drop-down menu. This will initialize the process of creating a Bitbucket repository in your current workspace:

Fig 5: Initialising creating a Bitbucket repository

The page will then redirect to where you’ll need to provide some information about the repository you are trying to create which is as follows:

  • Workspace: This field will be automatically populated for you if you need to select a different workspace click on the dropdown icon.
  • Project name: Projects are a way to organize and manage repositories within a Bitbucket workspace. Provide a project name – this tutorial uses a project name First-bitbucket-project.
  • Repository name: Give your repository a name, this tutorial sets the repository name to – hello-world.
  • Access level: This field requires you to either make your repository private or public. This tutorial sets this field to – public.
  • Include a README: Just like GitHub, you have the option to create a ReadMe as you create your repository. This tutorial sets this field to Yes.
  • Default branch name: This field requires you to specify the default branch you’d like to push your code to. This tutorial selects the main branch as the default branch.
  • Include .gitignore: This field asks you if you’d like to add a *.gitignore* file to your repository, this tutorial selects Yes.

You have the option to add a description and select the language your project comprised of. These settings are located in the advanced settings option.

Go ahead and create this repository. This should take less than a minute:

Fig 6: Creating a Bitbucket repository

Once your repository has been created successfully, you should see your repository presented to you on your Bitbucket dashboard like the output below:

Fig 7: Viewing Bitbucket repository

Pushing your code to your Bitbucket repository

Since Bitbucket supports the Git version control system, you can upload and transfer the code from your local machine up to your Bitbucket remote repository using Git commands.

Open up your project directory via a terminal or command prompt and execute the following Git commands to commit your changes and push your project up to your Bitbucket repository.

First, execute the command below to initialize a new Git repository in the current directory, This command will create a new directory named ".git" within the current directory, which contains all the necessary metadata and objects to manage version control for the project:

git init

Fig 8: Initialising a new Git repository

Display the current status of the local repository, including information about changed files that have not yet been committed to the repository, untracked files, and the current branch using the following command:

git status

From the output below, you can see that you are on the master branch and haven’t made any commits yet.

Fig 9: Viewing current branch, commits and untracked files

Now execute the following Git command to track the files in your current directory. This prepares them to be committed to the Git repository:

git add .

Record changes to the local repository by specifying commit, which describes the changes being committed using the following Git command:

git commit -m "my first commit"

The commit message provides context and helps to understand the purpose of the changes.

Fig 10: Making a commit message

Since you already have the Main branch as your default branch for your BitBucket remote repository, execute the Git command below to rename the current branch to "main".

The "-M" option specifies that it’s a branch rename operation.

This can be useful if you want to change the name of your branch to better reflect the work you’re doing, or to align with best practices or conventions within your organisation.

git branch -M main

Create a new remote named origin and set its URL to a specified URL using the Git command below. This allows you to push and pull changes from the remote repository located at the specified URL, which in this case is your repository on Bitbucket.

git remote add origin "YOUR_BITBUCKET_REPOSITORY_HERE"

To get the URL of your Bitbucket repository, Click on the clone button from the top right side, and copy the URL after the `git clone` command highlighted below:

Fig 11: Copying Bitbucket repository URL

Since you allowed Bitbucket to add a ReadME and a .gitignore file while creating your repository, you’ll need to execute the following Git pull command to fetch and download the content from the remote repository and merge it with your local repository:

git pull --rebase origin main

You should have the ReadME and the .gitignore file as shown in the below screenshot:

Fig 12: Viewing pulled files from remote Bitbucket repository

Create an App password on your Bitbucket account that you will use when you want to push your code up to your Bitbucket repository. Click on your avatar from your repository page and select personal settings from the dropdown menu:

Fig 13: Initialising creating an app password

The page will redirect to the personal settings page. On this page, select the App passwords tab from the left panel. A new screen will be shown to you, click on the create app password button to create an app password:

Fig 14: Creating app password

Give your app password a label (this tutorial uses hello-world) as the label, check all the check-boxes under the permissions section and click on the create button to create this password.

Fig 15: Adding app-password label and permissions

A pop-up window will be shown to you containing your app password, copy the app password. Be sure to save this password somewhere you can access it, you will always need it whenever you try to push your code to any repository on your Bitbucket account.

Fig 16: Copying app password

Close the pop-up window once you have successfully copied the app password for your repository. You should be redirected to the below screen:

Fig 17: Viewing app-passwords

Last, execute the following Git command to push the local main branch to a remote repository. This command pushes the local main branch to a remote repository named "origin" with the "u" option set to track the remote branch as the local main branch.

git push -u origin main

This command will prompt you to input your Bitbucket username and password. Make sure you provide the correct username and app password as your password.

Once you have successfully pushed to your remote Bitbucket repository, all you now have to do is refresh your Bitbucket repository page. You should see the latest push:

Fig 18: Pushing commits to remote Bitbucket repository

Hosting repository with Bitbucket pages

Bitbucket has a pages feature that allows you to host static websites directly from your Bitbucket repository. Bitbucket Pages provides a simple, fast, and flexible way for developers, teams, and organizations to create and host websites without the need for dedicated hosting infrastructure.

First, you will need to rename your repository to include the following naming convention – username/workspaceID.bitbucket.io. This is the required naming convention to setup pages for your Bitbucket repository.

On your repository page, select the repository settings tab from the left panel:

Fig 19: Viewing repository settings

Edit the name of your repository to follow the naming convention stated above and scroll down to the bottom of the page to save this setting:

Fig 20: Renaming repository name

Once the change has been saved, navigate to the following web address over your preferred browser to see your static site:

https://workspace_ID.bitbucket.io
https://my-helloworldworkspace.bitbucket.io/

Fig 21: Viewing repository

Using a third-party CI tool with Bitbucket

As I mentioned earlier Bitbucket integrates very well with third-party continuous integration and delivery tools. For this tutorial, you’ll be integrating Bitbucket with Circle CI.

First, execute the Git command below to create an orphan branch – you can name this branch whatever you like. This tutorial uses circle-ci as the branch name. This branch will contain a VueJS project, this is the project we will be using for this demo. The reason you’ll need to create this branch is that we only want to configure continuous integration and delivery for only the circle-ci branch.

git checkout --orphan circle-ci
git rm -rf .

This will result in something like the following.

Fig 22: Checking out to orphan branch (circle-ci)

Create a VueJS project using the following command. This command creates a VueJS project using the Vite build tool.

npm create vue@3

This command outputs some questions, you’ll provide the following answers:

  • Project name: type in (.) so it builds the project in the current directory. (type in enter to continue)
  • Package name: vue (you can name it whatever you like)
  • Add TypeScript? … No / Yes (NO is the default so, type enter)
  • Add JSX Support? … No
  • Add Vue Router for Single Page Application development? … No
  • Add Pinia for state management? … No
  • Add Vitest for Unit Testing? … Yes (Use your left-arrow key to select yes)
  • Add an End-to-End Testing Solution? › No
  • Add ESLint for code quality? … No

Once the VueJS project has been created successfully, you should have the following output:

Fig 23: Creating VueJS project with Vite

Run the below command to install all the dependencies needed for the project:

npm install

Fig 24: Installing all project dependencies

Since you accepted to add Vitest for unit testing, you have an already configured example test in the project src folder, named HelloWorld.spec.js. This is the sample test we will instruct CircleCI to check for before pushing our code up to our Bitbucket repository:

Fig 25: Viewing sample test (HelloWorld.spec.js)

Run the following command below to check if this test passes:

npm run test:unit

If it passes you should have output similar to below:

Fig 26: Viewing successful test

Create a folder in the current directory called .circleci, in there, create a file called config.yml This is the exact naming style for the CircleCI configuration file.

Add the below code snippets:

version: 4.0
jobs:
  build:
    working_directory: ~/repo
    branch: circle-ci
    docker:
      - image: cimg/node:19.4.0
    steps:
      - checkout
      - run:
          name: update-npm
          command: sudo npm install -g npm@latest
      - restore_cache:
          key: dependency-cache-
      - run: 
          name: install-all-packages
          command: npm install
      - save_cache:
          key: dependency-cache-
          paths:
           - ./node_modules
      - run: 
          name: run tests
          command: npm run test:unit
      - run:
          name: generate static files #dist
          command: |
            npm run build
            echo "Pushed to Bitbucket"

Now push your changes up to the circle-ci branch using the below commands:

git add .
git commit -m 'first commit for the circle-ci branch'
# you'll need to do this since your renamed your Bitbucket repository
git remote remove origin
# Be sure to add your own repository url
git remote add origin "git@bitbucket.org:my-helloworldworkspace/my-helloworldworkspace.bitbucket.io.git"
git push origin circle-ci

Once you have successfully pushed your code to the circle-ci branch, when you select the Branches tab from the left panel on your Bitbucket repository, you should see that you now have two branches. The main branch and the circle-ci branch:

Fig 27: Viewing branches on Bitbucket repository

Select the Source tab from the left panel to confirm that you also have the circle-ci branch created:

Fig 28: Viewing branches on Bitbucket repository

Now you can view the code pushed by selecting the circle-ci branch, from the above image:

Fig 29: Viewing source code on circle-ci branch

Since you are using CircleCI as the CI/CD tool, you’ll need to generate an SSH key pair and add the public key in your Bitbucket repository else your build will fail. To achieve this, click on your avatar and select the personal settings from the dropdown menu:

Run the following command to generate a ssh key pair - ssh-keygen -t rsa -b 4096 -C YOUR_BITBUCKET_EMAIL

Fig 30: Selecting personal settings to add ssh key on bitbucket

Select the SSH keys from the left panel and click on the Add key button:

Fig 31: Initialising add ssh key on bitbucket

A pop-up window will be shown to you, input the name of the key as the label, add the public key and then click on the Add key button to add this key.

Fig 32: Adding ssh key to Bitbucket (circle ci)

Head over to CircleCI and sign up with your Bitbucket account and be sure to select the Bitbucket workspace housing the repository you are trying to build with CircleCI:

Fig 33: Selecting Bitbucket workspace

Once you have selected your workspace you should be taken to your dashboard to set up a project. From your dashboard, click on the Add project button highlighted below, to add a project:

Fig 34: Viewing CircleCI dashboard

Since CircleCI has access to your Bitbucket workspace, it will automatically output all the repositories you have on that workspace. In this case, the only repository available in the my-helloworldworkspace is my-helloworldworkspace.bitbucket.io. So, click the Set up project button beside the repository to set up a CircleCI project for that repository:

Fig 35: Setting up a CircleCI project

This will output a pop-up asking you to select the branch you would like to build, it also checks if there is a .circleci/config.yml file available in that branch and if there’s you’ll have a green check mark indicating it has found the .circleci/config.yml file , else it provides you with other options to create a .circleci/config.yml file for it to use.

Now type in circle-ci as the branch and click on the Set up project button to proceed:

Fig 36: Selecting config.yml file for CircleCI

The page will then navigate to your dashboard for you to view your pipeline. The following output shows that the pipeline was successful:

Fig 37: Viewing successful pipeline

If you also head to your Bitbucket branches page for your repository, you will see the below output showing that the build on CircleCI was successful:

Fig 38: viewing build on Bitbucket repository

Conclusion

Bitbucket is as you have seen just like GitHub, you can do the basic things you do on GitHub on Bitbucket too. You have seen how to create a workspace, project, and repository on Bitbucket. You have also seen how to use Bitbucket pages to view your repositories over a browser and ultimately seen how to integrate Bitbucket with CircleCI.

I believe you can agree with me that Bitbucket is easy to use out of the box just like GitHub. You can take a tour to test other Bitbucket features like pull requests, Bitbucket pipelines, and more.

 

The post Introduction to Using Bitbucket and CI/CD for Your App appeared first on Simple Talk.



from Simple Talk https://ift.tt/0XpIeZL
via

Tuesday, April 25, 2023

PostgreSQL Basics: Getting started with psql

PostgreSQL has a separate command-line tool that’s been available for decades and is included with any installation of PostgreSQL. Many long-term PostgreSQL users, developers, and administrators rely on psql to help them quickly connect to databases, examine the schema, and execute SQL queries.

Knowing how to install and use basic psql commands is an essential skill to have for anyone that will connect to PostgreSQL.

A Brief History of psql

To understand why PostgreSQL has its own command line utility and why it is so integrated into how developers work with PostgreSQL, we need to take a quick step into the time-travel machine and remind ourselves how PostgreSQL became PostgreSQL.

1970s-1985 INGRES, the grandfather of PostgreSQL, developed and used a proprietary query language called QUEL. One of the terminal programs that was used to interact with INGRESS was called monitor
1985-1994 POSTGRES (after INGRES) was started and developed. It maintained the QUEL query language now called POSTQUEL, and so the monitor application could continue to be used with POSTGRES
1995 Postgres95 is released with a very liberal PostgreSQL License, based on POSTGRES source code, but QUEL is replaced with SQL! The monitor terminal application will no longer work, and psql was provided as the new terminal tool for interacting with Postgres95
1996-present PostgreSQL 6.0 was released under the guidance of the new PostgreSQL Global Development Group and amazing work hasn’t stopped since. With every release of PostgreSQL, additional features and improvements are made to the psql utility to provide more power to end users.

Why Should You Use psql

If you’re new to the PostgreSQL space, using a command line utility to connect to and query the database might feel outdated. As a former, long-time SQL Server developer I know the lack of a consistent, standardized GUI tool felt really frustrating at times.

After a while, however, I realized that it is often much easier to jump into a database with psql when I just need to connect, look at schemas, and run simple queries. Using the meta-commands becomes second nature for getting details about database objects. It’s like having a tool with hundreds of efficient shortcuts to quickly work with the database.

Even more powerful is that you can configure psql to return the SQL that it runs for each command along with the results. This can be a gateway into learning many of the underlying catalog tables in PostgreSQL that control every aspect of how the database is used.

And last, but certainly not least, is that many (many!) articles, tutorials, books, and videos that show you how to use PostgreSQL features will often demonstrate concepts using psql. Knowing how to connect with the tool and run basic meta-commands will quickly help you follow along.

TL;DR; – psql is a powerful tool to have in your PostgreSQL toolbelt. Knowing how to connect to a database and run basic commands will quickly pay dividends in your PostgreSQL work. In total, I think learning some of the basics is worth the time of investment.

Installing psql

The psql command line tool (CLI) is available on Linux, MacOS, and Windows. It comes pre-bundled with the PostgreSQL server installation package or it can be installed independently as a stand-alone CLI application.

Also, psql is versioned alongside PostgreSQL because the queries that it runs when you use meta-commands need to work with newer catalog schemas. There is a lot of effort taken to keep psql backwards compatible within the supported PostgreSQL versions, so a newer version of psql should work with at least the last five major releases.

Check For psql

Because psql comes bundled with the PostgreSQL server, there’s a possibility you already have it available on your computer if you’ve ever installed PostgreSQL. From a terminal or Windows command prompt, type the following:

$> psql --version
psql (PostgreSQL) 15.0 (Ubuntu 15.0-1.pgdg20.04+1)

If you see a response that lists the psql version, then you already have psqlinstalled. If the version is older, consider updating it.

A good rule of thumb is to try to have a psqlversion that matches the newest version of PostgreSQL you’re using across environments. For the basic commands we cover below there’s a high likelihood that any version you have will work, but keeping psqlupdated is a good practice to follow.

Install on Linux

All major Linux distributions should have a package for the postgresql-client. This can be used to only install the PostgreSQL tools apart from the server, including psql, pg_dump pg_restore, and others.

We’ll use Ubuntu as an example, but the package manager of your distribution should have identical (or very similar) package names to do the same thing. The commands below will install the latest version of the tools.

From a terminal prompt, run the following commands:

$> sudo apt-get update

$> sudo apt-get install postgresql-client

Once completed, verify installation by checking for the psql version as shown previously.

Install on Windows

On Windows, you have two options.

If you want to use psql through a Windows command prompt, then you need install PostgreSQL and all tools using the Windows installation package found on PostreSQL.org. Through the installation process, you can decide which parts of the server and tools to install.

On Windows 10 or greater, it’s possible to install the tools in a Windows Subsystem for Linux 2 (WSL2) environment and use the normal Linux package management to install the components as shown above. Again, depending on the distribution you’re using for the WSL host, the package commands may be slightly different.

Install on MacOS

There is a plethora of ways to install PostgreSQL on MacOS, many of which include the full server and associated tools.

The fastest method for getting PostgreSQL setup on MacOS is to use the Postgres.app. This provides a full installation of the PostgreSQL server that can be started and stopped at will, and the simple instructions on their homepage show you how to make sure the PostgreSQL CLI tools are in the path to use from the Terminal.

Alternatively, you can just install the PostgreSQL using Homebrew. Installing the libpq package only installs the tooling (not the server).

ryan@mba-laptop % brew doctor
ryan@mba-laptop % brew update
ryan@mba-laptop % brew install libpq

Because this isn’t the full PostgreSQL server, you’ll also need to setup the path correctly so that you can use psql from the Terminal. The easiest way to do that is to let Homebrew update the linking as follows.

ryan@mba-laptop % brew link --force libpq

Docker

Finally, I’d be remiss if I didn’t mention Docker as an alternative. Any of the official PostgreSQL containers can be used, through the interactive Docker shell, to connect to and use psql. Whether you’re attempting to connect to PostgreSQL on the Docker instance itself or remotely, the installed psqlapplication can be used (assuming networking is setup correctly).

As an example, the following commands could be used to download and start a PostgreSQL Docker container, connect to the running shell, and use psqlinside of the container.

ryan@redgate-laptop:~$ docker run --name pg15 -p 5432:5432 -e POSTGRES_PASSWORD=password -d postgres

ryan@redgate-laptop:~$ docker exec -it pg15 bash

root@80049acea1c0:/# psql -h localhost -U postgres

Connecting to PostgreSQL

Once you have psql installed there are two ways to specify the basic connection parameters for the target database. You will need the following information to connect to PostgreSQL.

  • Hostname
  • Port (5432 by default)
  • Username
  • Password
  • Database name

Specifying Individual Parameters

With the above information, connect to the database using these parameters. If the PostgreSQL server is running on the default port of 5432, you can omit the -p switch and psql will attempt to connect to that port automatically.

psql -h [hostname] -p [port] -U [username] -d [database name]

If all the information is correct, you will be prompted for a password. When using the individual parameters for connecting to PostgreSQL, there is no method to supply the password on the command line. You will always be prompted, or you could specify it in the .pgpass file.

Using a PostgreSQL Connection URI

Alternatively, you can use the connection parameters to create a PostgreSQL connection URI to connect to the database.

psql postgresql://[username]:[password]@[hostname]:[port]/[database name]

With this form, you can specify the password in the connection string as long as it does not contain a semi-colon (;) or ampersand (@) as those interfere with the connection URI parsing. If the password is omitted, then PostgreSQL will prompt you.

Conclusion

The psql command-line application is the go-to tool for anyone working with PostgreSQL. With decades of development and hundreds of built-in meta-commands to help developers and administrators work with PostgreSQL quickly and efficiently, knowing how to install and use it to connect to databases is an essential skill for PostgreSQL users. As an added bonus, recent psql versions can be used with at least the most recent five major releases of PostgreSQL because of the tireless work by the community to maintain backwards compatibility.

Of course, knowing how to get it installed and connecting is only part of the puzzle. In our next article, we’ll give you a tour of how to use psql and the major meta-commands you should know to accelerate your development and management of PostgreSQL databases.

 

 

The post PostgreSQL Basics: Getting started with psql appeared first on Simple Talk.



from Simple Talk https://ift.tt/gpLnM5T
via