Linux postgresql create database

1.3. Creating a Database

The first test to see whether you can access the database server is to try to create a database. A running PostgreSQL server can manage many databases. Typically, a separate database is used for each project or for each user.

Possibly, your site administrator has already created a database for your use. He should have told you what the name of your database is. In that case you can omit this step and skip ahead to the next section.

To create a new database, in this example named mydb, you use the following command:

If this produces no response then this step was successful and you can skip over the remainder of this section.

If you see a message similar to:

then PostgreSQL was not installed properly. Either it was not installed at all or your shell’s search path was not set to include it. Try calling the command with an absolute path instead:

The path at your site might be different. Contact your site administrator or check the installation instructions to correct the situation.

Another response could be this:

This means that the server was not started, or it was not started where createdb expected it. Again, check the installation instructions or consult the administrator.

Another response could be this:

where your own login name is mentioned. This will happen if the administrator has not created a PostgreSQL user account for you. ( PostgreSQL user accounts are distinct from operating system user accounts.) If you are the administrator, see Chapter 20 for help creating accounts. You will need to become the operating system user under which PostgreSQL was installed (usually postgres) to create the first user account. It could also be that you were assigned a PostgreSQL user name that is different from your operating system user name; in that case you need to use the -U switch or set the PGUSER environment variable to specify your PostgreSQL user name.

If you have a user account but it does not have the privileges required to create a database, you will see the following:

Not every user has authorization to create new databases. If PostgreSQL refuses to create databases for you then the site administrator needs to grant you permission to create databases. Consult your site administrator if this occurs. If you installed PostgreSQL yourself then you should log in for the purposes of this tutorial under the user account that you started the server as. [1]

You can also create databases with other names. PostgreSQL allows you to create any number of databases at a given site. Database names must have an alphabetic first character and are limited to 63 bytes in length. A convenient choice is to create a database with the same name as your current user name. Many tools assume that database name as the default, so it can save you some typing. To create that database, simply type:

If you do not want to use your database anymore you can remove it. For example, if you are the owner (creator) of the database mydb, you can destroy it using the following command:

(For this command, the database name does not default to the user account name. You always need to specify it.) This action physically removes all files associated with the database and cannot be undone, so this should only be done with a great deal of forethought.

More about createdb and dropdb can be found in createdb and dropdb respectively.

Notes

As an explanation for why this works: PostgreSQL user names are separate from operating system user accounts. When you connect to a database, you can choose what PostgreSQL user name to connect as; if you don’t, it will default to the same name as your current operating system account. As it happens, there will always be a PostgreSQL user account that has the same name as the operating system user that started the server, and it also happens that that user always has permission to create databases. Instead of logging in as that user you can also specify the -U option everywhere to select a PostgreSQL user name to connect as.

Читайте также:  Npm install windows laravel

Источник

CREATE DATABASE

Synopsis

Description

CREATE DATABASE creates a new PostgreSQL database.

To create a database, you must be a superuser or have the special CREATEDB privilege. See CREATE USER.

By default, the new database will be created by cloning the standard system database template1. A different template can be specified by writing TEMPLATE name. In particular, by writing TEMPLATE template0, you can create a virgin database containing only the standard objects predefined by your version of PostgreSQL . This is useful if you wish to avoid copying any installation-local objects that might have been added to template1.

Parameters

The name of a database to create.

The role name of the user who will own the new database, or DEFAULT to use the default (namely, the user executing the command). To create a database owned by another role, you must be a direct or indirect member of that role, or be a superuser.

The name of the template from which to create the new database, or DEFAULT to use the default template ( template1).

Character set encoding to use in the new database. Specify a string constant (e.g., ‘SQL_ASCII’), or an integer encoding number, or DEFAULT to use the default encoding (namely, the encoding of the template database). The character sets supported by the PostgreSQL server are described in Section 22.2.1. See below for additional restrictions.

Collation order ( LC_COLLATE) to use in the new database. This affects the sort order applied to strings, e.g. in queries with ORDER BY, as well as the order used in indexes on text columns. The default is to use the collation order of the template database. See below for additional restrictions.

Character classification ( LC_CTYPE) to use in the new database. This affects the categorization of characters, e.g. lower, upper and digit. The default is to use the character classification of the template database. See below for additional restrictions.

The name of the tablespace that will be associated with the new database, or DEFAULT to use the template database’s tablespace. This tablespace will be the default tablespace used for objects created in this database. See CREATE TABLESPACE for more information.

How many concurrent connections can be made to this database. -1 (the default) means no limit.

Optional parameters can be written in any order, not only the order illustrated above.

Notes

CREATE DATABASE cannot be executed inside a transaction block.

Errors along the line of «could not initialize database directory» are most likely related to insufficient permissions on the data directory, a full disk, or other file system problems.

Use DROP DATABASE to remove a database.

The program createdb is a wrapper program around this command, provided for convenience.

Although it is possible to copy a database other than template1 by specifying its name as the template, this is not (yet) intended as a general-purpose » COPY DATABASE» facility. The principal limitation is that no other sessions can be connected to the template database while it is being copied. CREATE DATABASE will fail if any other connection exists when it starts; otherwise, new connections to the template database are locked out until CREATE DATABASE completes. See Section 21.3 for more information.

The character set encoding specified for the new database must be compatible with the chosen locale settings ( LC_COLLATE and LC_CTYPE). If the locale is C (or equivalently POSIX), then all encodings are allowed, but for other locale settings there is only one encoding that will work properly. (On Windows, however, UTF-8 encoding can be used with any locale.) CREATE DATABASE will allow superusers to specify SQL_ASCII encoding regardless of the locale settings, but this choice is deprecated and may result in misbehavior of character-string functions if data that is not encoding-compatible with the locale is stored in the database.

The encoding and locale settings must match those of the template database, except when template0 is used as template. This is because other databases might contain data that does not match the specified encoding, or might contain indexes whose sort ordering is affected by LC_COLLATE and LC_CTYPE. Copying such data would result in a database that is corrupt according to the new settings. template0, however, is known to not contain any data or indexes that would be affected.

Читайте также:  Centos или linux mint

The CONNECTION LIMIT option is only enforced approximately; if two new sessions start at about the same time when just one connection «slot» remains for the database, it is possible that both will fail. Also, the limit is not enforced against superusers.

Examples

To create a new database:

To create a database sales owned by user salesapp with a default tablespace of salesspace:

To create a database music which supports the ISO-8859-1 character set:

In this example, the TEMPLATE template0 clause would only be required if template1‘s encoding is not ISO-8859-1. Note that changing encoding might require selecting new LC_COLLATE and LC_CTYPE settings as well.

Compatibility

There is no CREATE DATABASE statement in the SQL standard. Databases are equivalent to catalogs, whose creation is implementation-defined.

Источник

Создать базу данных Postgresql

Прежде всего требуется подключиться к серверу по SSH.

Далее подключиться к базе от имени пользователя postgres (по умолчанию существует только он)

could not change directory to «/root»
psql (9.2.24)
Type «help» for help.

Если возникла ошибка, подобная приведенной выше — нужно перейти в любой каталог, в который postgres имеет доступ.

Оказавшись к консоли можно создать базу данных

CREATE DATABASE

Затем пользователя, которому присвоить пароль.

postgres=# CREATE USER appadmin WITH PASSWORD ‘jkfdk8H0Indgshy6hk’;

CREATE ROLE

Пользователи в PostgreSQL являются ролями. Для определенной базы созданному пользователю задаются нужные привилегии.

Например, полный доступ:

postgres=# GRANT ALL PRIVILEGES ON DATABASE app to appadmin;

GRANT

Также требуется скорректировать значения в одном из конфигурационных файлов

В файле содержится информация о методах аутентификации. Изначально работа с базой возможна только в случае если подключение выполняет системный пользователь с именем идентичным пользователю сервера баз данных.

На практике это обычно неудобно и требуется подключение с реквизитами специально созданного пользователя, по установленному паролю.

В файле потребуется заменить в двух строках, начинающихся с host тип аутентификации с ident на md5. Это последнее значение в каждой строке.

# TYPE DATABASE USER ADDRESS METHOD

# «local» is for Unix domain socket connections only
local all all peer
# IPv4 local connections:
#host all all 127.0.0.1/32 ident
host all all 127.0.0.1/32 md5
# IPv6 local connections:
#host all all ::1/128 ident
host all all ::1/128 md5

Для вступления в силу изменений нужно перезапустить сервис

Установка postgresql на Centos и Debian

Если postgresql на сервере еще нет, его нужно установить.

Centos 7

yum install postgresql-server postgresql-devel postgresql-contrib

Debian 9

После установки на CentOS требуется выполнить начальную настройку. Скрипт подобен mysql_secure_instalation в MySQL.

Initializing database … OK

Для Debian / Ubuntu сервис запускается автоматически, для Centos его нужно стартовать и добавить в автозагрузку

Если сайт, работающий с Postgresql переносится на другой сервер — требуется создать, а потом развернуть на другой машине дамп базы.

Источник

Linux postgresql create database

CREATE DATABASE — создать базу данных

Синтаксис

Описание

Команда CREATE DATABASE создаёт базу данных PostgreSQL .

Чтобы создать базу данных, необходимо быть суперпользователем или иметь специальное право CREATEDB . См. CREATE USER .

По умолчанию новая база данных создаётся копированием стандартной системной базы данных template1 . Задать другой шаблон можно, добавив указание TEMPLATE имя . В частности, написав TEMPLATE template0 , можно создать девственно чистую базу данных, содержащую только стандартные объекты, предопределённые установленной версией PostgreSQL . Это бывает полезно, когда копировать в новую базу любые дополнительные объекты, добавленные локально в template1 , нежелательно.

Параметры

Имя создаваемой базы данных. имя_пользователя

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

Имя шаблона, из которого будет создаваться новая база данных, либо DEFAULT , чтобы выбрать шаблон по умолчанию ( template1 ). кодировка

Кодировка символов в новой базе данных. Укажите строковую константу (например, ‘SQL_ASCII’ ) или целочисленный номер кодировки, либо DEFAULT , чтобы выбрать кодировку по умолчанию (а именно, кодировку шаблона). Наборы символов, которые поддерживает PostgreSQL , перечислены в Подразделе 23.3.1. Дополнительные ограничения описаны ниже. категория_сортировки

Читайте также:  Код windows live mail

Порядок сортировки ( LC_COLLATE ), который будет использоваться в новой базе данных. Этот параметр определяет порядок сортировки строк, например, в запросах с ORDER BY, а также порядок индексов по текстовым столбцам. По умолчанию используется порядок сортировки, установленный в шаблоне. Дополнительные ограничения описаны ниже. категория_типов_символов

Классификация символов ( LC_CTYPE ), которая будет применяться в новой базе данных. Этот параметр определяет принадлежность символов категориям, например: строчные, заглавные, цифры и т. п. По умолчанию используется классификация символов, установленная в шаблоне. Дополнительные ограничения описаны ниже. табл_пространство

Имя табличного пространства, связываемого с новой базой данных, или DEFAULT для использования табличного пространства шаблона. Это табличное пространство будет использоваться по умолчанию для объектов, создаваемых в этой базе. За подробностями обратитесь к CREATE TABLESPACE . разр_подключения

Если false, никто не сможет подключаться к этой базе данных. По умолчанию имеет значение true, то есть подключения принимаются (если не ограничиваются другими механизмами, например, GRANT / REVOKE CONNECT ). предел_подключений

Максимальное количество одновременных подключений к этой базе данных. Значение -1 (по умолчанию) снимает ограничение. это_шаблон

Если true, базу данных сможет клонировать любой пользователь с правами CREATEDB ; в противном случае (по умолчанию), клонировать эту базу смогут только суперпользователи и её владелец.

Дополнительные параметры могут записываться в любом порядке, не обязательно так, как показано выше.

Замечания

CREATE DATABASE нельзя выполнять внутри блока транзакции.

Ошибки, содержащие сообщение « не удалось инициализировать каталог базы данных » , чаще всего связаны с нехваткой прав в каталоге данных, заполнением диска или другими проблемами в файловой системе.

Для удаления базы данных применяется DROP DATABASE .

Программа createdb представляет собой оболочку этой команды, созданную ради удобства.

Конфигурационные параметры уровня базы данных (устанавливаемые командой ALTER DATABASE ) и разрешения уровня базы (устанавливаемые командой GRANT ) из шаблона не копируются.

Хотя с помощью этой команды можно скопировать любую базу данных, а не только template1 , указав её имя в качестве имени шаблона, она не предназначена (пока) для использования в качестве универсального средства вроде « COPY DATABASE » . Принципиальным ограничением является невозможность копирования базы данных шаблона, если установлены другие подключения к ней. CREATE DATABASE выдаёт ошибку, если при запуске команды есть другие подключения к этой базе; в противном случае новые подключения к базе блокируются до завершения команды CREATE DATABASE . За дополнительными сведениями обратитесь к Разделу 22.3.

Кодировка символов, указанная для новой базы данных, должна быть совместима с выбранными параметрами локали ( LC_COLLATE и LC_CTYPE ). Если выбрана локаль C (или равнозначная ей POSIX ), допускаются все кодировки, но для других локалей правильно будет работать только одна кодировка. (В Windows, однако, кодировку UTF-8 можно использовать с любой локалью.) CREATE DATABASE позволяет суперпользователям указать кодировку SQL_ASCII вне зависимости от локали, но этот вариант считается устаревшим и может привести к ошибочному поведению строковых функций, если в базе хранятся данные в кодировке, несовместимой с заданной локалью.

Параметры локали и кодировка должны соответствовать тем, что установлены в шаблоне, если только это не template0 . Это ограничение объясняется тем, что другие базы данных могут содержать данные в кодировке, отличной от заданной, или индексы, порядок сортировки которых определяются параметрами LC_COLLATE и LC_CTYPE . При копировании таких данных получится база, которая будет испорченной согласно новым параметрам локали. Однако template0 определённо не содержит какие-либо данные или индексы, зависящие от кодировки или локали.

Ограничение CONNECTION LIMIT действует только приблизительно; если одновременно запускаются два сеанса, тогда как в базе остаётся только одно « свободное место » , может так случиться, что будут отклонены оба подключения. Кроме того, это ограничение не распространяется на суперпользователей и фоновые рабочие процессы.

Примеры

Создание базы данных:

Создание базы данных sales , принадлежащей пользователю salesapp , с табличным пространством по умолчанию salesspace :

Создание базы данных music с кодировкой ISO-8859-1:

В этом примере предложение TEMPLATE template0 будет необходимым, только если кодировка template1 отличается от ISO-8859-1. Заметьте, что при смене кодировки может потребоваться также выбрать другие параметры LC_COLLATE и LC_CTYPE .

Совместимость

Оператор CREATE DATABASE отсутствует в стандарте SQL. Базы данных равнозначны каталогам, а их создание в стандарте определяется реализацией.

Источник

Оцените статью