- PostgreSQL
- Contents
- Installation
- Initial configuration
- Create your first database/user
- Familiarize with PostgreSQL
- Access the database shell
- Optional configuration
- Restricts access rights to the database superuser by default
- Require password for login
- Configure PostgreSQL to be accessible exclusively through UNIX Sockets
- Configure PostgreSQL to be accessible from remote hosts
- Configure PostgreSQL authenticate against PAM
- Change default data directory
- Change default encoding of new databases to UTF-8
- Graphical tools
- Upgrading PostgreSQL
- pg_upgrade
- Manual dump and reload
- Troubleshooting
- Improve performance of small transactions
- Prevent disk writes when idle
- PostgreSQL 9.2 Начало!
- Сборка и установка
- Настройка
- Утилиты для работы с базой
- Менеджеры по работе с базой
PostgreSQL
PostgreSQL is an open source, community driven, standard compliant object-relational database system.
Contents
Installation
This article or section needs language, wiki syntax or style improvements. See Help:Style for reference.
Install the postgresql package. It will also create a system user called postgres.
You can switch to the PostgreSQL user by executing the following command:
See sudo(8) or su(1) for their usage.
Initial configuration
Before PostgreSQL can function correctly, the database cluster must be initialized:
Where -D is the default location where the database cluster must be stored (see #Change default data directory if you want to use a different one).
Note that by default, the locale and the encoding for the database cluster are derived from your current environment (using $LANG value). [1] However, depending on your settings and use cases this might not be what you want, and you can override the defaults using:
- —locale=locale , where locale is to be chosen amongst the system’s available locales;
- -E encoding for the encoding (which must match the chosen locale);
Many lines should now appear on the screen with several ending by . ok :
If these are the kind of lines you see, then the process succeeded. Return to the regular user using exit .
Finally, start and enable the postgresql.service .
Create your first database/user
Become the postgres user. Add a new database user using the createuser command:
Create a new database over which the above user has read/write privileges using the createdb command (execute this command from your login shell if the database user has the same name as your Linux user, otherwise add -O database-username to the following command):
Familiarize with PostgreSQL
Access the database shell
Become the postgres user. Start the primary database shell, psql, where you can do all your creation of databases/tables, deletion, set permissions, and run raw SQL commands. Use the -d option to connect to the database you created (without specifying a database, psql will try to access a database that matches your username).
Some helpful commands:
Connect to a particular database:
List all users and their permission levels:
Show summary information about all tables in the current database:
Exit/quit the psql shell:
There are of course many more meta-commands, but these should help you get started. To see all meta-commands run:
Optional configuration
The PostgreSQL database server configuration file is postgresql.conf . This file is located in the data directory of the server, typically /var/lib/postgres/data . This folder also houses the other main configuration files, including the pg_hba.conf which defines authentication settings, for both local users and other hosts ones.
Restricts access rights to the database superuser by default
The defaults pg_hba.conf allow any local user to connect as any database user, including the database superuser. This is likely not what you want, so in order to restrict global access to the postgres user, change the following line:
You might later add additional lines depending on your needs or software ones.
Require password for login
Edit /var/lib/postgres/data/pg_hba.conf and set the authentication method for each user (or «all» to affect all users) to scram-sha-256 (preferred), or md5 (less secure; should be avoided if possible):
If you choose scram-sha-256 , you must also edit /var/lib/postgres/data/postgresql.conf and set:
Restart postgresql.service , and then re-add each user’s password using ALTER USER user WITH ENCRYPTED PASSWORD ‘password‘; .
Configure PostgreSQL to be accessible exclusively through UNIX Sockets
In the connections and authentications section of your configuration, set:
This will disable network listening completely. After this you should restart postgresql.service for the changes to take effect.
Configure PostgreSQL to be accessible from remote hosts
In the connections and authentications section, set the listen_addresses line to your needs:
You can use ‘*’ to listen on all available addresses.
Then add a line like the following to the authentication config:
where ip_address is the IP address of the remote client.
See the documentation for pg_hba.conf.
After this you should restart postgresql.service for the changes to take effect.
For troubleshooting take a look in the server log file:
Configure PostgreSQL authenticate against PAM
PostgreSQL offers a number of authentication methods. If you would like to allow users to authenticate with their system password, additional steps are necessary. First you need to enable PAM for the connection.
For example, the same configuration as above, but with PAM enabled:
The PostgreSQL server is however running without root privileges and will not be able to access /etc/shadow . We can work around that by allowing the postgres group to access this file:
Change default data directory
The default directory where all your newly created databases will be stored is /var/lib/postgres/data . To change this, follow these steps:
Create the new directory and make the postgres user its owner:
Become the postgres user, and initialize the new cluster:
Edit postgresql.service to create a drop-in file and override the Environment and PIDFile settings. For example:
If you want to use /home directory for default directory or for tablespaces, add one more line in this file:
Change default encoding of new databases to UTF-8
When creating a new database (e.g. with createdb blog ) PostgreSQL actually copies a template database. There are two predefined templates: template0 is vanilla, while template1 is meant as an on-site template changeable by the administrator and is used by default. In order to change the encoding of a new database, one of the options is to change on-site template1 . To do this, log into PostgreSQL shell ( psql ) and execute the following:
First, we need to drop template1 . Templates cannot be dropped, so we first modify it so it is an ordinary database:
Now we can drop it:
The next step is to create a new database from template0 , with a new default encoding:
Now modify template1 so it is actually a template:
Optionally, if you do not want anyone connecting to this template, set datallowconn to FALSE :
Now you can create a new database:
If you log back in to psql and check the databases, you should see the proper encoding of your new database:
Graphical tools
- phpPgAdmin — Web-based administration tool for PostgreSQL.
https://github.com/phppgadmin/phppgadmin || phppgadmin
- pgAdmin — Comprehensive design and management GUI for PostgreSQL.
https://www.pgadmin.org/ || pgadmin3AUR or pgadmin4
- pgModeler — Graphical schema designer for PostgreSQL.
https://pgmodeler.io/ || pgmodelerAUR
Upgrading PostgreSQL
This article or section needs language, wiki syntax or style improvements. See Help:Style for reference.
This article or section needs expansion.
Upgrading major PostgreSQL versions requires some extra maintenance.
Get the currently used database version via
To ensure you do not accidentally upgrade the database to an incompatible version, it is recommended to skip updates to the PostgreSQL packages:
Minor version upgrades are safe to perform. However, if you do an accidental upgrade to a different major version, you might not be able to access any of your data. Always check the PostgreSQL home page to be sure of what steps are required for each upgrade. For a bit about why this is the case, see the versioning policy.
There are two main ways to upgrade your PostgreSQL database. Read the official documentation for details.
pg_upgrade
For those wishing to use pg_upgrade , a postgresql-old-upgrade package is available that will always run one major version behind the real PostgreSQL package. This can be installed side-by-side with the new version of PostgreSQL. To upgrade from older versions of PostgreSQL there are AUR packages available: postgresql-96-upgrade AUR , postgresql-95-upgrade AUR , postgresql-94-upgrade AUR , postgresql-93-upgrade AUR , postgresql-92-upgrade AUR . Read the pg_upgrade(1) man page to understand what actions it performs.
Note that the databases cluster directory does not change from version to version, so before running pg_upgrade , it is necessary to rename your existing data directory and migrate into a new directory. The new databases cluster must be initialized, as described in the #Installation section.
This article or section needs language, wiki syntax or style improvements. See Help:Style for reference.
While the database is still accessible, one may take the opportunity to check the locale and encoding used, and whether data checksums are used:
When you are ready, stop the postgresql service, upgrade the following packages: postgresql , postgresql-libs , and postgresql-old-upgrade . Finally upgrade the databases cluster.
Stop and make sure PostgreSQL is stopped:
Make sure that PostgresSQL was stopped correctly. If it failed, pg_upgrade will fail too.
Upgrade the packages:
Rename the databases cluster directory, and create an empty one:
Should you have a conflicting system locale and encoding, add —locale=xy_XY.UTF-8 —encoding=UTF8 options (where xx_YY matches your need). Should you have data-checksums enabled, add —data-checksums option.
Upgrade the cluster, replacing PG_VERSION below, with the old PostgreSQL version number (e.g. 12 ):
Start the cluster:
pg_upgrade will have created the scripts analyze_new_cluster.sh and delete_old_cluster.sh in /var/lib/postgres/tmp/ and will have output some instructions about running these.
- analyze_new_cluster.sh generates optimizer statistics for the new cluster and should be run as user postgres . It requires the postgresql service to have been started.
- delete_old_cluster.sh simply deletes the directory /var/lib/postgres/olddata and should be run as a user with write privileges for /var/lib/postgres (e.g. as root ).
You may delete the /var/lib/postgres/tmp directory once the upgrade is completely over.
Manual dump and reload
You could also do something like this (after the upgrade and install of postgresql-old-upgrade ).
Troubleshooting
Improve performance of small transactions
If you are using PostgresSQL on a local machine for development and it seems slow, you could try turning synchronous_commit off in the configuration. Beware of the caveats, however.
Prevent disk writes when idle
PostgreSQL periodically updates its internal «statistics» file. By default, this file is stored on disk, which prevents disks from spinning down on laptops and causes hard drive seek noise. It is simple and safe to relocate this file to a memory-only file system with the following configuration option:
Источник
PostgreSQL 9.2 Начало!
Мне хотелось создать прекрасный объемлющий мануал Getting Start без всякой воды, но включающий основные плюшки для начинающих по системе PostgreSQL в Linux.
PostgreSQL является объектно-реляционной системой управления базами данных (ОРСУБД) на основе POSTGRES, версия 4.2, разработанной в Университете Калифорнии в Беркли департаменте компьютерных наук.
PostgreSQL является open source потомком оригинального кода Berkeley. Он поддерживает большую часть стандарта SQL и предлагает множество современных функций:
Сборка и установка
Как и все любители мейнстрима PostgreSQL мы будем конечно же собирать, а не скачивать готовые пакеты (в репозитариях Debian, например, нет последней версии). Вот здесь лежит множество версий, скачивать конечно же лучше всего последнюю. На момент написания поста это версия 9.2.2
Теперь у нас есть директория с исходниками сей прекрасной базы данных.
По умолчанию файлы базы будут установлены в директорию /usr/local/pgsql, но эту директорию можно изменить задав
перед командой ./configure
Перед сборкой можно указать компилятор С++
PostgeSQL может использовать readline библиотеку, если у вас её нет и нет желания её ставить просто укажите опцию
Надеюсь у всех есть Autotools? Тогда вперед к сборке:
Все господа! Поздравляю!
Настройка
Нам необходимо указать хранилище данных наших баз данных (кластер) и запустить её.
Есть один нюанс — владельцем директории данных и пользователь, который может запускать базу должен быть не root. Это сделано в целях безопасности системы. Поэтому создадим специального пользователя
И далее все понятно
Важный процесс. Мы должны инициализировать кластер баз дынных. Сделать мы должны это от имени пользователя postgres
Теперь нужно добавить запуск PostgreSQL в автостарт. Для этого существует уже готовый скрипт и лежит он в postgresql-9.2.2/contrib/start-scripts/linux
Этот файл можно открыть и обратить внимание на следующие переменные:
- prefix — это место куда мы ставили PostgreSQL и задавали в ./configure
- PGDATA — это то, где хранится кластер баз данных и куда должен иметь доступ наш пользователь postgres
- PGUSER — это тот самый пользователь, от лица которого будет все работать
Если все стоит верно, то добвляем наш скрипт в init.d
Перезапускам систему, чтобы проверить что наш скрипт работает.
Вводим
И если появится окно работы с базой, то настройка прошла успешно! Поздравляю!
По умолчанию создается база данных с именем postgres
Теперь важно поговорить о методах авторизации.
В /usr/local/pgsql/data/pg_hba.conf как раз есть необходимые для этого настройка
Первая строка отвечает за локальное соединение, вторая — за соединение про протоколу IPv4, а третья по протоколу IPv6.
Самый последний параметр — это как раз таки метод авторизации. Его и рассмотрим (только основные)
- trust — доступ к базе может получить кто угодно под любым именем, имеющий с ней соединение.
- reject — отклонить безоговорочно! Это подходит для фильтрации определенных IP адресов
- password — требует обязательного ввода пароля. Не подходит для локальных пользователей, только пользователи созданные командой CREATE USER
- ident — позволяет только пользователем зарегистрированным в файле /usr/local/pgsql/data/pg_ident.conf устанавливать соединение с базой.
Вкратце расскажу об основных утилитах, которые пригодятся в работе.
Утилиты для работы с базой
pg_config
Возвращает информацию о текущей установленной версии PostgreSQL.
initdb
Инициализирует новое хранилище данных (кластер баз данных). Кластер представляет собой совокупность баз данных управляемых одним экземпляром севера. initdb должен быть запущен от имени будущего владельца сервера (как указано выше от имени postgres).
pg_ctl
Управляет процессом работы сервера PostgreSQL. Позволяет запускать, выполнять перезапуск, останавливать работу сервера, указать лог файл и другое.
psql
Клиент для работы с базой дынных. Позволяет выполнять SQL операции.
createdb
dropdb
Удаляет базу данных. Является оберткой SQL команды DROP DATABASE.
createuser
dropuser
Удаляет пользователя базы данных. Является оберткой SQL команды DROP ROLE.
createlang
droplang
Удаляет язык программирования. Является оберткой SQL команды DROP LANGUAGE.
pg_dump
pg_restore
pg_dumpall
Создает бэкап (дамп) всего кластера в файл.
reindexdb
Производит переиндексацию базы данных. Является оберткой SQL команды REINDEX.
clusterdb
Производит перекластеризацию таблиц в базе данных. Является оберткой SQL команды CLUSTER.
vacuumdb
Сборщик мусора и оптимизатор базы данных. Является оберткой SQL команды VACUUM.
Менеджеры по работе с базой
Что касается менеджера по работа с базой, то есть php менеджер — это phpPgAdmin и GUI менеджер pgAdmin. Должен заметить, что они оба плохо поддерживают последнюю версию PostgreSQL.
Источник