1.5. Подключение к базе данных #

Поскольку Postgres Pro Shardman является распределённой системой, достаточно подключиться к одному узлу кластера, чтобы иметь доступ ко всему кластеру. За подробностями обратитесь к Подразделу 1.5.1. Создав базу данных, вы можете обратиться к ней:

  • Запустив терминальную программу Postgres Pro Shardman под названием psql, в которой можно интерактивно вводить, редактировать и выполнять команды SQL.

  • Написав собственное приложение, используя один из множества доступных языковых интерфейсов. Подробнее это рассматривается в Части IV.

Для работы с примером воспользуйтесь клиентом psql. Подключиться с его помощью к базе данных mydb можно, введя команду:

$ psql mydb

Если имя базы данных не указать, она будет выбрана по имени пользователя. Об этом уже рассказывалось в предыдущем разделе, посвящённом команде createdb.

В psql вы увидите следующее сообщение:

psql (18.6.2)
Type "help" for help.

mydb=>

Последняя строка может выглядеть и так:

mydb=#

Что показывает, что вы являетесь суперпользователем, и так скорее всего будет, если вы устанавливали экземпляр Postgres Pro Shardman сами. В этом случае на вас не будут распространяться никакие ограничения доступа, но для целей данного введения это не важно.

Если вы столкнулись с проблемами при запуске psql, вернитесь к предыдущему разделу. Команды createdb и psql подключаются к серверу одинаково, так что если первая работает, должна работать и вторая.

Последняя строка в выводе psql — это приглашение, которое показывает, что psql ждёт ваших команд и вы можете вводить SQL-запросы в рабочей среде psql. Попробуйте эти команды:

mydb=> SELECT current_setting('pgpro_version');
                                         version
-------------------------------------------------------------------​-----------------------
 Postgres Pro Shardman 18.3.2 on x86_64-pc-linux-gnu, compiled by gcc (Ubuntu 11.4.0-1ubuntu1~22.04) 11.4.0, 64-bit
(1 row)

mydb=> SELECT current_date;
    date
------------
 2016-01-07
(1 row)

mydb=> SELECT 2 + 2;
 ?column?
----------
        4
(1 row)

В программе psql есть множество внутренних команд, которые не являются SQL-операторами. Они начинаются с обратной косой черты, «\». Например, вы можете получить справку по различным SQL-командам Postgres Pro Shardman, введя:

mydb=> \h

Чтобы выйти из psql, введите:

mydb=> \q

и psql завершит свою работу, а вы вернётесь в командную оболочку операционной системы. (Чтобы узнать о внутренних командах, введите \? в приглашении командной строки psql.) Все возможности psql документированы в справке psql. В этом руководстве мы не будем использовать эти возможности явно, но вы можете изучить их и применять при удобном случае.

Обратите внимание, что для подключения к кластеру Postgres Pro Shardman и успешной работы с ним достаточно подключиться к одному узлу кластера.

1.5.1. psql/libpq #

Для подключения к кластеру Postgres Pro Shardman получите строку подключения с использованием библиотеки psql или libpq. За дополнительной информацией о libpq обратитесь к libpq — библиотека для языка C.

Для параметра target_session_attrs должно быть указано значение read-write, то есть приемлемы только подключения, допускающие транзакции чтения/записи. При успешном подключении к узлу кластера будет отправлен запрос «SHOW transaction_read_only;». Если в результате получено значение on, соединение будет закрыто. Если в строке подключения указаны несколько серверов, будут перебираться остальные серверы, как и при неудачной попытке подключения. Использование параметра target_session_attrs даёт возможность указывать в строке подключение как ведущие серверы, так и реплики кластера Postgres Pro Shardman.

Ниже представлены примеры подключения:

psql -d  "dbname=postgres host=node3,node4,node2,node1 port=5432,5432,5432,5432 user=username password=password target_session_attrs=read-write"

psql postgres://username:password@node1:5432,node2:5432,node3:5432,node4:5432/postgres?target_session_attrs=read-write

1.5.2. Python #

Подключение к кластеру Postgres Pro Shardman с использованием библиотеки psycopg2 будет выглядеть следующим образом:

import psycopg2
from psycopg2 import pool

pool = psycopg2.pool.SimpleConnectionPool(
                             min_size=1,
                             max_size=5,
                             user="pguser",
                             password="*****",
                             host="node1,node2,node3,node4",
                             port="5432,5432,5432,5432",
                             database="postgres",
                             target_session_attrs="read-write")

connection = pool.getconn()

Создаётся пул соединений со следующими параметрами: минимальное количество подключений min_size=1, а максимальное — max_size=5. Далее выбирается подключение для соединения с кластером, указывается логин и пароль пользователя, список узлов, TCP-портов, база данных и параметры подключения (за дополнительной информацией обратитесь к Подразделу 1.5.1).

1.5.3. Java #

Подключение к кластеру Postgres Pro Shardman с использованием JDBC будет выглядеть следующим образом:

String url = "jdbc:postgresql://node1:5432,node2:5432,node3:5432,node4:5432/postgres?loadBalanceHosts=true&targetServerType=primary";
Properties props = new Properties();


props.setProperty("user","postgres");
props.setProperty("password","********");

Connection conn = DriverManager.getConnection(url, props);

Здесь в переменной url содержится строка подключения, где перечислены все доступные в кластере ведущие серверы сегментов. Если не указывать дополнительные параметры подключения драйвера JDBC, то подключение к кластеру будет происходить через первый доступный для соединения узел. Данный вариант не всегда может оказаться удобным. Поэтому, в строке подключения добавлены параметры, позволяющие использовать разные сегменты кластера для разных подключений.

Параметр loadBalanceHosts=true позволяет перебирать узлы, подключаясь к какому-то одному из них, а параметр targetServerType=primary указывает, что необходимо выбирать только ведущие сервера, тогда в строку подключения можно добавлять реплики.

1.5.4. Go #

Подключение к кластеру Postgres Pro Shardman для Go не слишком отличается от способов подключения, принятых в Java или Python. Необходимо использовать перечисление узлов, их TCP-портов, параметры подключения и выбрать подходящий драйвер.

Одним из таких драйверов для Go является pgx версий 4 или 5.

Ниже представлен пример строки подключения и создания пула для подключения к кластеру:

dbURL := "postgres://username:password@node1:5432,node2:5432,node3:5432,node4:5432/postgres?target_session_attrs=read-write")
dbPool, err := pgxpool.New(context.Background(), dbURL)

Рекомендуем также ознакомиться с описанием параметра target_session_attrs.

1.5. Accessing a Database #

As Postgres Pro Shardman is a distributed system, it is sufficient to connect to one cluster node to connect to entire cluster. See connection details. Once you have created a database, you can access it by:

  • Running the Postgres Pro Shardman interactive terminal program, called psql, which allows you to interactively enter, edit, and execute SQL commands.

  • Writing a custom application, using one of the several available language bindings. These possibilities are discussed further in Part IV.

You probably want to start up psql to try the examples in this tutorial. It can be activated for the mydb database by typing the command:

$ psql mydb

If you do not supply the database name then it will default to your user account name. You already discovered this scheme in the previous section using createdb.

In psql, you will be greeted with the following message:

psql (18.6.2)
Type "help" for help.

mydb=>

The last line could also be:

mydb=#

That would mean you are a database superuser, which is most likely the case if you installed the Postgres Pro Shardman instance yourself. Being a superuser means that you are not subject to access controls. For the purposes of this tutorial that is not important.

If you encounter problems starting psql then go back to the previous section. The diagnostics of createdb and psql are similar, and if the former worked the latter should work as well.

The last line printed out by psql is the prompt, and it indicates that psql is listening to you and that you can type SQL queries into a work space maintained by psql. Try out these commands:

mydb=> SELECT current_setting('pgpro_version');
                                         version
-------------------------------------------------------------------​-----------------------
 Postgres Pro Shardman 18.3.2 on x86_64-pc-linux-gnu, compiled by gcc (Ubuntu 11.4.0-1ubuntu1~22.04) 11.4.0, 64-bit
(1 row)

mydb=> SELECT current_date;
    date
------------
 2016-01-07
(1 row)

mydb=> SELECT 2 + 2;
 ?column?
----------
        4
(1 row)

The psql program has a number of internal commands that are not SQL commands. They begin with the backslash character, “\”. For example, you can get help on the syntax of various Postgres Pro Shardman SQL commands by typing:

mydb=> \h

To get out of psql, type:

mydb=> \q

and psql will quit and return you to your command shell. (For more internal commands, type \? at the psql prompt.) The full capabilities of psql are documented in psql. In this tutorial we will not use these features explicitly, but you can use them yourself when it is helpful.

Note that to connect to a Postgres Pro Shardman cluster and successfully work with it, it is sufficient to connect to one cluster node.

1.5.1. psql/libpq #

To connect to a Postgres Pro Shardman cluster, first get the connection string with psql or libpq. For more information on libpq, refer to libpq — C Library.

The value of target_session_attrs must be set to read-write. Only connections that allow read/write transactions are acceptable. If the connection to a cluster node is a success, the request “SHOW transaction_read_only;” is sent. If it returns on, the connection is closed. If several servers are specified in the connection string, other servers will be iterated through, the same way as with the failed connection attempt. The target_session_attrs parameter allows you to specify both masters and replicas of the Postgres Pro Shardman cluster.

The following examples illustrate the connection:

psql -d  "dbname=postgres host=node3,node4,node2,node1 port=5432,5432,5432,5432 user=username password=password target_session_attrs=read-write"

psql postgres://username:password@node1:5432,node2:5432,node3:5432,node4:5432/postgres?target_session_attrs=read-write

1.5.2. Python #

Connection to a Postgres Pro Shardman cluster using the psycopg2 library looks like this:

import psycopg2
from psycopg2 import pool

pool = psycopg2.pool.SimpleConnectionPool(
                             min_size=1,
                             max_size=5,
                             user="pguser",
                             password="*****",
                             host="node1,node2,node3,node4",
                             port="5432,5432,5432,5432",
                             database="postgres",
                             target_session_attrs="read-write")

connection = pool.getconn()

A connection pool with the following parameters is created: the minimum and maximum number of connections min_size=1 and max_size=5. Then a specific connection to the cluster is selected, the user login and password are specified, as well as the list of nodes and TCP ports, database and connection parameters (see Section 1.5.1 for more information).

1.5.3. Java #

Connection to a Postgres Pro Shardman cluster using JDBC looks like this:

String url = "jdbc:postgresql://node1:5432,node2:5432,node3:5432,node4:5432/postgres?loadBalanceHosts=true&targetServerType=primary";
Properties props = new Properties();


props.setProperty("user","postgres");
props.setProperty("password","********");

Connection conn = DriverManager.getConnection(url, props);

url contains the connection string, where all the available shard masters are listed. If no additional connection parameters of the JDBC driver are specified, connection to the cluster is performed through the first node available for connection. This is not always convenient. Therefore, connection string settings are added that allow using different cluster shards for different connections.

loadBalanceHosts=true allows iterating through nodes connecting to one of them, and targetServerType=primary indicates a need to only choose masters, then replicas can be added to the connection string.

1.5.4. Go #

Ways to connect to a Postgres Pro Shardman cluster for Go are pretty much the same as those accepted in Java or Python. You need to specify lists of nodes, their TCP ports, as well as connection parameters and choose a suitable driver.

One of these drivers for Go is pgx version 4 or 5.

The following is an example of a connection string and creation of a pool for connecting to a cluster:

dbURL := "postgres://username:password@node1:5432,node2:5432,node3:5432,node4:5432/postgres?target_session_attrs=read-write")
dbPool, err := pgxpool.New(context.Background(), dbURL)

Also pay attention to the description of the target_session_attrs parameter.

FAQ