thư mục dữ liệu

Các đối tượng lưu trữ dữ liệu trên PostgreSQL

Sau khi install PostgreSQL việc đầu tiên bạn phải làm là tạo ra một database cluster để thực hiện tiếp các truy vấn (SQL) khác. Để tạo một database cluster, ta sử dụng command initdb. Sau đó khởi động PostgreSQL là ta có thể bắt đầu sử dụng PostgreSQL. Bạn có băn khoăn tại sao mình lại có thể thực hiện được truy vấn, mình đang access bằng User nào truy cập vào database nào để thực hiện truy vấn, ... Bài viết này sẽ giới thiệu một số Objects chính trên PostgreSQL, cách tạo ra chúng, và cách nhìn tổng quan về các Objects lưu trữ dữ liệu trên PostgreSQL.

Một database cluster được tạo và khởi động (dựa trên thông tin bạn nhập trên wizard của installer) nếu bạn cài đặt PostgreSQL qua installer trên Windows.

Khái quát về các Objects lưu trữ trên PostgreSQL

Giống như các RDBMS khác, bảng dữ liệu là nơi PostgreSQL thực hiện lưu trữ dữ liệu. Bảng dữ liệu được lưu trữ trong đơn vị lớn hơn là database, các database nằm bên dưới đơn vị lớn nhất của PostgreSQL là database cluster. Như hình minh họa bên dưới ta còn thấy bảng dữ liệu nằm dưới schema và tablespace. Schema là đơn vị tập hợp các bảng (và một số objects khác) theo hình thức logic. Và tablespace là đơn vị của một tập hợp các bảng và indexes theo hình thức vật lý. Xin vui lòng chi xem tiết các Objects lưu trữ như bên dưới.

Tổng quan phân cấp đối tượng trong PostgreSQL
Tổng quan phân cấp đối tượng trong PostgreSQL.

Các đối tương lưu trữ trong PostgreSQL
Các đối tương lưu trữ trong PostgreSQL.

Database cluster

Là đơn vị lưu trữ lớn nhất của một PostgreSQL database server. Database cluster được tạo ra bởi câu lệnh initdb, bao gồm các files config (postgresql.conf, pg_hba.conf, ...), và tất cả các đối tượng lưu trữ đều nằm trong database cluster. Xin vui lòng xem chi tiết trong bài viết Cấu trúc thư mục PostgreSQL.

Có thể cài đặt nhiều PostgreSQL database server trên một hệ điều hành, bằng cách chỉ định các port (thiết lập trong $PGDATA/postgresql.conf) khác nhau cho mỗi server.

Database

Là đơn vị lớn sau Database cluster. Để thực hiện được câu truy vấn, bạn phải truy cập vào một database nào đó. Mặc định sau khi tạo database cluster, PostgreSQL tạo ra 3 database như bên dưới.

 
$ psql
Timing is on.
psql (10.3)
Type "help" for help.

10300 postgres@postgres=# \l
                         List of databases
   Name    | Owner | Encoding | Collate | Ctype | Access privileges 
-----------+-------+----------+---------+-------+-------------------
 postgres  | bocap | UTF8     | C       | C     | 
 template0 | bocap | UTF8     | C       | C     | =c/bocap         +
           |       |          |         |       | bocap=CTc/bocap
 template1 | bocap | UTF8     | C       | C     | =c/bocap         +
           |       |          |         |       | bocap=CTc/bocap
(3 rows)

Tên Database Mục Đích sử dụng
template0 Là template database. Không thể truy nhập và chỉnh sửa các đối tượng trong đó. Người dùng có thể tạo database mới dựa trên template0 này bằng cách chỉ định TEMPLATE trong câu lệnh "CREATE DATABASE"
template1 Là một template database. Người dùng có thể truy nhập và chỉnh sửa các đối tượng trong đó. Khi thực hiện câu lệnh "CREATE DATABASE", PostgreSQL sẽ copy template1 này để tạo database mới.
postgres database mặc định của PostgreSQL khi tạo database cluster.

PostgreSQL cũng như các RDBMS khác, để truy nhập một database. Ta cần thông tin: tên database, tên user, password(ở chứng thực trust thì bạn không cần), số port (cho từng database cluster), hostname or IP address.

Để tạo một database ta sử dụng câu lệnh SQL "CREATE DATABASE", hoặc sử dụng createdb từ installer.

Khác với Oracle, PostgreSQL mặc định đối tượng câu lệnh SQL là chữ thường. Nếu muốn chữ in hoa vui lòng viết đối tượng trong dấu "".

  • Tạo database từ câu lệnh SQL
  1. Cú pháp

10300 postgres@postgres=# \h CREATE DATABASE
Command:     CREATE DATABASE
Description: create a new database
Syntax:
CREATE DATABASE name
    [ [ WITH ] [ OWNER [=] user_name ]
           [ TEMPLATE [=] template ]
           [ ENCODING [=] encoding ]
           [ LC_COLLATE [=] lc_collate ]
           [ LC_CTYPE [=] lc_ctype ]
           [ TABLESPACE [=] tablespace_name ]
           [ ALLOW_CONNECTIONS [=] allowconn ]
           [ CONNECTION LIMIT [=] connlimit ]
           [ IS_TEMPLATE [=] istemplate ] ]

  1. Ví dụ

10300 postgres@postgres=# CREATE DATABASE testdb TEMPLATE template0;
CREATE DATABASE
Time: 4941.826 ms (00:04.942)
10300 postgres@postgres=# \l
                           List of databases
   Name    |  Owner   | Encoding | Collate | Ctype | Access privileges 
-----------+----------+----------+---------+-------+-------------------
 postgres  | bocap    | UTF8     | C       | C     | 
 template0 | bocap    | UTF8     | C       | C     | =c/bocap         +
           |          |          |         |       | bocap=CTc/bocap
 template1 | bocap    | UTF8     | C       | C     | =c/bocap         +
           |          |          |         |       | bocap=CTc/bocap
 testdb    | postgres | UTF8     | C       | C     | 
(4 rows)

10300 postgres@postgres=# \c testdb
You are now connected to database "testdb" as user "postgres".
10300 postgres@testdb=# \d
Did not find any relations.
10300 postgres@testdb=# \c postgres 
You are now connected to database "postgres" as user "postgres".
10300 postgres@postgres=# DROP DATABASE testdb ;
DROP DATABASE

Để hiện thị thông tin của database trên psql mode, ta sử dụng meta command \l hay \l+ (chi tiết). Muốn access vào database nào đó ta sử dụng meta command "\c database".

  • Tạo database từ câu lệnh createdb
  1. Cú pháp
 
$ createdb --help
createdb creates a PostgreSQL database.

Usage:
  createdb [OPTION]... [DBNAME] [DESCRIPTION]

Options:
  -D, --tablespace=TABLESPACE  default tablespace for the database
  -e, --echo                   show the commands being sent to the server
  -E, --encoding=ENCODING      encoding for the database
  -l, --locale=LOCALE          locale settings for the database
      --lc-collate=LOCALE      LC_COLLATE setting for the database
      --lc-ctype=LOCALE        LC_CTYPE setting for the database
  -O, --owner=OWNER            database user to own the new database
  -T, --template=TEMPLATE      template database to copy
  -V, --version                output version information, then exit
  -?, --help                   show this help, then exit

Connection options:
  -h, --host=HOSTNAME          database server host or socket directory
  -p, --port=PORT              database server port
  -U, --username=USERNAME      user name to connect as
  -w, --no-password            never prompt for password
  -W, --password               force password prompt
  --maintenance-db=DBNAME      alternate maintenance database

By default, a database with the same name as the current user is created.

  1. Ví dụ
 
[ ~]$ createdb --template=template0 testdb
[ ~]$ psql -l
Timing is on.
                           List of databases
   Name    |  Owner   | Encoding | Collate | Ctype | Access privileges 
-----------+----------+----------+---------+-------+-------------------
 postgres  | bocap    | UTF8     | C       | C     | 
 template0 | bocap    | UTF8     | C       | C     | =c/bocap         +
           |          |          |         |       | bocap=CTc/bocap
 template1 | bocap    | UTF8     | C       | C     | =c/bocap         +
           |          |          |         |       | bocap=CTc/bocap
 testdb    | postgres | UTF8     | C       | C     | 
(4 rows)

[ ~]$ dropdb testdb
[ ~]$


Schema

Là đơn vị lưu trữ bên dưới database, quản lý dữ liệu dưới dạng logic. Mặc định trong mỗi database có một schema cho người sử dụng, đó là schema public. Ta có thể tạo schema bằng câu lệnh "CREATE SCHEMA ". Đặc điểm của 1 schema như bên dưới.

  • Có thể sử dụng tên trùng với schema ở database khác but không trùng tên trên cùng database.
  • Ngoài TABLESPACE và user ra, schema có thể chứa hầu hết các đối tượng còn lại (như table, index, sequence, constraint...)
  • để truy cập schema ta có thể thêm tên schema vào phía trước đối tượng muốn truy cập hoặc sử dụng tham số search_path để thay đổi schema truy cập hiện tại.
  • Schema có thể sử dụng với các mục đích như tăng cường security, quản lý dữ liệu dễ dàng hơn.

Khác với Oracle, Schema của PostgreSQL không có liên quan tới database User.

Để tạo schema, ta phải truy cập vào một database nào đó rồi thực hiện lệnh "CREATE SCHEMA " để tạo.

  1. Cú pháp

10300 postgres@postgres=# \h CREATE SCHEMA
Command:     CREATE SCHEMA
Description: define a new schema
Syntax:
CREATE SCHEMA schema_name [ AUTHORIZATION role_specification ] [ schema_element [ ... ] ]
CREATE SCHEMA AUTHORIZATION role_specification [ schema_element [ ... ] ]
CREATE SCHEMA IF NOT EXISTS schema_name [ AUTHORIZATION role_specification ]
CREATE SCHEMA IF NOT EXISTS AUTHORIZATION role_specification

where role_specification can be:

    user_name
  | CURRENT_USER
  | SESSION_USER


  1. Ví dụ:

10300 postgres@postgres=# \dn
  List of schemas
  Name  |  Owner
--------+----------
 public | postgres
(1 row)

10300 postgres@postgres=# show search_path;
   search_path
-----------------
 "$user", public
(1 row)

10300 postgres@postgres=# create schema testscm;
CREATE SCHEMA
10300 postgres@postgres=# create table testscm.testtbl();
CREATE TABLE
10300 postgres@postgres=# \d
Did not find any relations.
10300 postgres@postgres=# set search_path to testscm ;
SET
10300 postgres@postgres=# \d
          List of relations
 Schema  |  Name   | Type  |  Owner
---------+---------+-------+----------
 testscm | testtbl | table | postgres
(1 row)

10300 postgres@postgres=# \dn
  List of schemas
  Name   |  Owner
---------+----------
 public  | postgres
 testscm | postgres
(2 rows)

10300 postgres@postgres=#

 

TABLESPACE

Là đơn vị lưu trữ dữ liệu về phương diện vật lý bên dưới database. Thông thường dữ liệu vật lý được lưu trữ tại thư mục dữ liệu (nơi ta chỉ định lúc ta tạo database cluster initdb -D). Nhưng có một phương pháp lưu trữ dữ liệu ngoài phân vùng này, nhờ sử dụng chức năng TABLESPACE. Khi tạo một TABLESPACE tức là ta đã tạo ra một vùng lưu trữ dữ liệu mới độc lập với dữ liệu bên dưới thư mục dữ liệu. Điều này giảm thiểu được disk I/O cho phân vùng thư mục dữ liệu (nếu trong các hệ thống cấu hình RAID, hay hệ thống có 1 đĩa cứng thì không có hiệu quả).

  1. Cú pháp

10300 postgres@postgres=# \h create tablespace
Command:     CREATE TABLESPACE
Description: define a new tablespace
Syntax:
CREATE TABLESPACE tablespace_name
    [ OWNER { new_owner | CURRENT_USER | SESSION_USER } ]
    LOCATION 'directory'
    [ WITH ( tablespace_option = value [, ... ] ) ]

10300 postgres@postgres=#
  1. Ví dụ

10300 postgres@postgres=# \! mkdir /tmp/testtablespace
10300 postgres@postgres=# create tablespace testtps location '/tmp/testtablespace';
CREATE TABLESPACE
10300 postgres@postgres=# \! ls -l /tmp/testtablespace/*
total 0
10300 postgres@postgres=# set default_tablespace to testtps;
SET
10300 postgres@postgres=# create table testtbl as select generate_series(1,10) as id;
SELECT 10
10300 postgres@postgres=# checkpoint;
CHECKPOINT
drwx------. 2 postgres postgres 18 Apr 15 13:59 13211
10300 postgres@postgres=# \! ls -l /tmp/testtablespace/*/*
total 8
-rw-------. 1 postgres postgres 8192 Apr 15 13:59 16389
10300 postgres@postgres=# select oid,* from pg_tablespace;
  oid  |  spcname   | spcowner | spcacl | spcoptions
-------+------------+----------+--------+------------
  1663 | pg_default |       10 |        |
  1664 | pg_global  |       10 |        |
 16388 | testtps    |       10 |        |
(3 rows)

10300 postgres@postgres=# \! ls -l $PGDATA/pg_tblspc/16388
lrwxrwxrwx. 1 postgres postgres 19 Apr 15 13:58 /usr/local/pgsql/pg1000/data/pg_tblspc/16388 -> /tmp/testtablespace
10300 postgres@postgres=#

PostgreSQL tạo một symblic link có tên là oid (Object ID) của tablespace vừa được tạo ở bên dưới pg_tblspc của database cluster. Trỏ tới vùng dữ liệu được chỉ định (LOCATION) trong lúc tạo tablespace.

Để chuyển đổi qua các tablespace để lưu trữ dữ liệu, ta chỉ định thông qua parameter default_tablespace trước khi tạo đối tượng (bảng hoặc index). Ngoài ra đối với bảng tạm thời (temporary table) và index của nó, để chuyển đổi vùng lưu trữ ta thiết lập tablespace cho tham số temp_tablespaces trước khi tạo đối tượng. default_tablespace và temp_tablespaces đều có giá trị mặc định là không thiết lập, tức là sử dụng tablespace mặc định bên dưới database cluster.

ví dụ trên sử dụng meta command ! của psql, meta command này thực hiện các lệnh shell bên ngoài.

Bảng(table)

Bảng là đối tượng lưu trữ dữ liệu từ người dùng. Một bảng bao gồm 0 hoặc nhiều cột (column) tương ứng với từng kiểu dữ liệu khác nhau của PostgreSQL.
Tổng quan có 3 kiểu tables mà PostgreSQL support, đó là

  • unlogged table: là kiểu table mà các thao tác đối với bảng dữ liệu này không được lưu trữ vào WAL. Tức là không có khả năng phục hồi nếu bị corrupt.
  • temporary table: là kiểu table chỉ được tạo trong phiên làm việc đó. Khi connection bị ngắt, nó sẽ tự động mất đi.
  • table thông thường: Khác với 2 kiểu table trên, là loại table thông thường để lưu trữ dữ liệu. Có khả năng phục hồi khi bị corrupt và tồn tại vĩnh viễn nếu không có thao tác xóa bỏ nào.

PostgreSQL support nhiều kiểu dữ liệu, bao gồm cả kiểu dữ liệu do người dùng định nghĩa. Để biết thêm chi tiết vui lòng  thao khảo ở đây

  1. Cú pháp tạo

postgres=# \h create table
Command:     CREATE TABLE
Description: define a new table
Syntax:
CREATE [ [ GLOBAL | LOCAL ] { TEMPORARY | TEMP } | UNLOGGED ] TABLE [ IF NOT EXISTS ] table_name ( [
  { column_name data_type [ COLLATE collation ] [ column_constraint [ ... ] ]
    | table_constraint
    | LIKE source_table [ like_option ... ] }
    [, ... ]
] )
[ INHERITS ( parent_table [, ... ] ) ]
[ PARTITION BY { RANGE | LIST } ( { column_name | ( expression ) } [ COLLATE collation ] [ opclass ] [, ... ] ) ]
[ WITH ( storage_parameter [= value] [, ... ] ) | WITH OIDS | WITHOUT OIDS ]
[ ON COMMIT { PRESERVE ROWS | DELETE ROWS | DROP } ]
[ TABLESPACE tablespace_name ]

CREATE [ [ GLOBAL | LOCAL ] { TEMPORARY | TEMP } | UNLOGGED ] TABLE [ IF NOT EXISTS ] table_name
    OF type_name [ (
  { column_name [ WITH OPTIONS ] [ column_constraint [ ... ] ]
    | table_constraint }
    [, ... ]
) ]
[ PARTITION BY { RANGE | LIST } ( { column_name | ( expression ) } [ COLLATE collation ] [ opclass ] [, ... ] ) ]
[ WITH ( storage_parameter [= value] [, ... ] ) | WITH OIDS | WITHOUT OIDS ]
[ ON COMMIT { PRESERVE ROWS | DELETE ROWS | DROP } ]
[ TABLESPACE tablespace_name ]

CREATE [ [ GLOBAL | LOCAL ] { TEMPORARY | TEMP } | UNLOGGED ] TABLE [ IF NOT EXISTS ] table_name
    PARTITION OF parent_table [ (
  { column_name [ WITH OPTIONS ] [ column_constraint [ ... ] ]
    | table_constraint }
    [, ... ]
) ] FOR VALUES partition_bound_spec
[ PARTITION BY { RANGE | LIST } ( { column_name | ( expression ) } [ COLLATE collation ] [ opclass ] [, ... ] ) ]
[ WITH ( storage_parameter [= value] [, ... ] ) | WITH OIDS | WITHOUT OIDS ]
[ ON COMMIT { PRESERVE ROWS | DELETE ROWS | DROP } ]
[ TABLESPACE tablespace_name ]

where column_constraint is:

[ CONSTRAINT constraint_name ]
{ NOT NULL |
  NULL |
  CHECK ( expression ) [ NO INHERIT ] |
  DEFAULT default_expr |
  GENERATED { ALWAYS | BY DEFAULT } AS IDENTITY [ ( sequence_options ) ] |
  UNIQUE index_parameters |
  PRIMARY KEY index_parameters |
  REFERENCES reftable [ ( refcolumn ) ] [ MATCH FULL | MATCH PARTIAL | MATCH SIMPLE ]
    [ ON DELETE action ] [ ON UPDATE action ] }
[ DEFERRABLE | NOT DEFERRABLE ] [ INITIALLY DEFERRED | INITIALLY IMMEDIATE ]

and table_constraint is:

[ CONSTRAINT constraint_name ]
{ CHECK ( expression ) [ NO INHERIT ] |
  UNIQUE ( column_name [, ... ] ) index_parameters |
  PRIMARY KEY ( column_name [, ... ] ) index_parameters |
  EXCLUDE [ USING index_method ] ( exclude_element WITH operator [, ... ] ) index_parameters [ WHERE ( predicate ) ] |
  FOREIGN KEY ( column_name [, ... ] ) REFERENCES reftable [ ( refcolumn [, ... ] ) ]
    [ MATCH FULL | MATCH PARTIAL | MATCH SIMPLE ] [ ON DELETE action ] [ ON UPDATE action ] }
[ DEFERRABLE | NOT DEFERRABLE ] [ INITIALLY DEFERRED | INITIALLY IMMEDIATE ]

and like_option is:

{ INCLUDING | EXCLUDING } { DEFAULTS | CONSTRAINTS | IDENTITY | INDEXES | STORAGE | COMMENTS | ALL }

and partition_bound_spec is:

IN ( { numeric_literal | string_literal | NULL } [, ...] ) |
FROM ( { numeric_literal | string_literal | MINVALUE | MAXVALUE } [, ...] )
  TO ( { numeric_literal | string_literal | MINVALUE | MAXVALUE } [, ...] )

index_parameters in UNIQUE, PRIMARY KEY, and EXCLUDE constraints are:

[ WITH ( storage_parameter [= value] [, ... ] ) ]
[ USING INDEX TABLESPACE tablespace_name ]

exclude_element in an EXCLUDE constraint is:

{ column_name | ( expression ) } [ opclass ] [ ASC | DESC ] [ NULLS { FIRST | LAST } ]

  1. Ví dụ:

postgres=#
postgres=# create unlogged table test_unlog_tbl as select generate_series(1,10) as id;
SELECT 10
postgres=# create temporary table test_temp_tbl as select generate_series(1,10) as id;
SELECT 10
postgres=# create table test_nomarl_tbl as select generate_series(1,10) as id;
SELECT 10
postgres=# \d
               List of relations
  Schema   |      Name       | Type  |  Owner
-----------+-----------------+-------+----------
 pg_temp_3 | test_temp_tbl   | table | postgres
 public    | test_nomarl_tbl | table | postgres
 public    | test_unlog_tbl  | table | postgres
(3 rows)

postgres=# \q
[postgres@localhost ~]$ psql
psql (10.3)
Type "help" for help.

postgres=# \d
              List of relations
 Schema |      Name       | Type  |  Owner
--------+-----------------+-------+----------
 public | test_nomarl_tbl | table | postgres
 public | test_unlog_tbl  | table | postgres
(2 rows)

postgres=#

index

Index là đối tượng chỉ mục của một cột nào đó trong bảng, đối tượng này đã được sắp xếp theo một trình tự nào đó khi được sử dụng có thể làm tăng khả năng tìm kiếm.
PostgreSQL hiện tại(tới phiên bản 10) support 6 loại index btree, hash, gist, spgist, gin, and brin. Thường thì btree và hash là 2 loại index được sử dụng rộng rãi. Các index còn lại được sử dụng cho từng mục đích khác nhau, ví dụ gist và spgist cho kiểu dữ liệu liên quan tới vị trí địa lý, gin cho kiểu dữ liệu text tìm kiếm với dữ liệu lớn, brin được thiết kế để xử lý các bảng lớn, trong đó các cột nhất định có một số tương quan tự nhiên với vị trí thực của chúng trong bảng.

  1. Cú pháp tạo

postgres=# \h create index
Command:     CREATE INDEX
Description: define a new index
Syntax:
CREATE [ UNIQUE ] INDEX [ CONCURRENTLY ] [ [ IF NOT EXISTS ] name ] ON table_name [ USING method ]
    ( { column_name | ( expression ) } [ COLLATE collation ] [ opclass ] [ ASC | DESC ] [ NULLS { FIRST | LAST } ] [, ...] )
    [ WITH ( storage_parameter = value [, ... ] ) ]
    [ TABLESPACE tablespace_name ]
    [ WHERE predicate ]

postgres=#

  1. Ví dụ

postgres=# create index test_nomarl_tbl_idx on test_nomarl_tbl using btree (id);
CREATE INDEX
postgres=# create index test_nomarl_tbl_hash_idx on test_nomarl_tbl using hash (id);
CREATE INDEX
postgres=# \d test_nomarl_tbl
          Table "public.test_nomarl_tbl"
 Column |  Type   | Collation | Nullable | Default
--------+---------+-----------+----------+---------
 id     | integer |           |          |
Indexes:
    "test_nomarl_tbl_hash_idx" hash (id)
    "test_nomarl_tbl_idx" btree (id)
Tablespace: "testtps"

postgres=#

Chi tiết về các loại index xin tìm hiểu ở đây: https://www.postgresql.org/docs/current/static/internals.html

Cấu trúc thư mục dữ liệu PostgreSQL

Thư mục dữ liệu PostgreSQL

Để chạy một câu lệnh SQL, tạo bảng dữ liệu, hay lưu trữ dữ liệu PostgreSQL cũng như các RDBMS khác chúng ta cần một thư mục chứa dữ liệu, PostgreSQL gọi đó là database cluster. Sau khi cài đặt PostgreSQL, database cluster được tạo ra bởi lệnh initdb. Nếu bạn cài đặt qua installer trên Windows, database cluster sẽ tự động được tạo ra trong quá trình cài đặt. Sau khi tạo một database cluster, ta có thể khởi động database cluster này lên và thực hiện các câu truy vấn tuỳ ý.

Các database cluster phân biệt bởi parameter port (postgresql.conf). Ta có thể cài đặt nhiều database cluster trên một hệ điều hành bằng cách đặt port khác nhau cho mỗi database cluster.

Tạo thư mục dữ liệu

Để tạo một thư mục dữ liệu PostgreSQL (database cluster) ta sử dụng câu lệnh initdb.


DangnoMacBook-Pro:postgresql-9.6.5 bocap$ initdb --no-locale -E utf8 -D /usr/local/pgsql/pg9600/data
The files belonging to this database system will be owned by user "bocap".
This user must also own the server process.

The database cluster will be initialized with locale "C".
The default text search configuration will be set to "english".

Data page checksums are disabled.

creating directory /usr/local/pgsql/pg9600/data ... ok
creating subdirectories ... ok
selecting default max_connections ... 100
selecting default shared_buffers ... 128MB
selecting dynamic shared memory implementation ... posix
creating configuration files ... ok
running bootstrap script ... ok
performing post-bootstrap initialization ... ok
syncing data to disk ... ok

WARNING: enabling "trust" authentication for local connections
You can change this by editing pg_hba.conf or using the option -A, or
--auth-local and --auth-host, the next time you run initdb.

Success. You can now start the database server using:

    pg_ctl -D /usr/local/pgsql/pg9600/data -l logfile start

DangnoMacBook-Pro:postgresql-9.6.5 bocap$ 

Lệnh initdb nhiều options bạn có thể kiểm tra bằng option --help. Ví dụ trên mình sử dụng các options thông dụng như bên dưới.

  • --no-locale: Không sử dụng locale, hay locale C. Tạo database cluster với option này, khi sắp xếp dữ liệu (ORDER BY), PostgreSQL sẽ không so sánh qua ký tự alphabet mà so sánh trực tiếp qua character code, tăng performance.
  • -E hay --encoding: Chỉ định encoding cho database cluster.
  • -D: thư mục cơ sở dữ liệu.

Khởi động server từ thư mục dữ liệu đã tạo.Ví dụ dưới mình sử dụng port 9605 cho database cluster này.


DangnoMacBook-Pro:postgresql-9.6.5 bocap$ echo port=9605 >> /usr/local/pgsql/pg9600/data/postgresql.conf
DangnoMacBook-Pro:postgresql-9.6.5 bocap$ pg_ctl start
server starting
DangnoMacBook-Pro:postgresql-9.6.5 bocap$ LOG:  database system was shut down at 2017-09-10 23:19:54 JST
LOG:  MultiXact member wraparound protections are now enabled
LOG:  autovacuum launcher started
LOG:  database system is ready to accept connections

Kiểm tra kết nối. Nếu không chỉ định User khi tạo database cluster (tùy chọn -U cho initdb). Mặc định User được tạo ra cho database cluster  là User của OS chạy câu lệnh initdb, nên ví dụ dưới mình tạo lại user postgres cho database cluster (mình để mặc định biến môi trường PGUSER là 'postgres' nên có lỗi User không tồn tại khi truy nhập).


DangnoMacBook-Pro:postgresql-9.6.5 bocap$ psql
FATAL:  role "postgres" does not exist
psql: FATAL:  role "postgres" does not exist
DangnoMacBook-Pro:postgresql-9.6.5 bocap$ psql -U bocap -c "create user postgres password 'postgres'"
CREATE ROLE
DangnoMacBook-Pro:postgresql-9.6.5 bocap$ psql
psql (9.6.5)
Type "help" for help.

postgres=> \q
DangnoMacBook-Pro:postgresql-9.6.5 bocap$


Cấu trúc thư mục PostgreSQL

Sau khi khởi động PostgreSQL 1 database cluster sẽ có cấu trúc như bên dưới.

Phiên bản PostgreSQL-10 sắp tới sẽ hơi khác ví dụ thư mục log pg_log (khi thiết lập lưu trữ log logging_colector = on) sẽ trở thành log, thư mục transaction log pg_xlog sẽ trở thành pg_wal, etc.


DangnoMacBook-Pro:postgresql-9.6.5 bocap$ ll $PGDATA
total 104
-rw-------   1 bocap  wheel      4 Sep 10 23:19 PG_VERSION
drwx------   5 bocap  wheel    170 Sep 10 23:19 base
drwx------  55 bocap  wheel   1870 Sep 10 23:31 global
drwx------   3 bocap  wheel    102 Sep 10 23:19 pg_clog
drwx------   2 bocap  wheel     68 Sep 10 23:19 pg_commit_ts
drwx------   2 bocap  wheel     68 Sep 10 23:19 pg_dynshmem
-rw-------   1 bocap  wheel   4477 Sep 10 23:19 pg_hba.conf
-rw-------   1 bocap  wheel   1636 Sep 10 23:19 pg_ident.conf
drwx------   4 bocap  wheel    136 Sep 10 23:19 pg_logical
drwx------   4 bocap  wheel    136 Sep 10 23:19 pg_multixact
drwx------   3 bocap  wheel    102 Sep 10 23:31 pg_notify
drwx------   2 bocap  wheel     68 Sep 10 23:19 pg_replslot
drwx------   2 bocap  wheel     68 Sep 10 23:19 pg_serial
drwx------   2 bocap  wheel     68 Sep 10 23:19 pg_snapshots
drwx------   2 bocap  wheel     68 Sep 10 23:31 pg_stat
drwx------   4 bocap  wheel    136 Sep 10 23:31 pg_stat_tmp
drwx------   3 bocap  wheel    102 Sep 10 23:19 pg_subtrans
drwx------   2 bocap  wheel     68 Sep 10 23:19 pg_tblspc
drwx------   2 bocap  wheel     68 Sep 10 23:19 pg_twophase
drwx------   4 bocap  wheel    136 Sep 10 23:19 pg_xlog
-rw-------   1 bocap  wheel     88 Sep 10 23:19 postgresql.auto.conf
-rw-------   1 bocap  wheel  22267 Sep 10 23:20 postgresql.conf
-rw-------   1 bocap  wheel     37 Sep 10 23:31 postmaster.opts
-rw-------   1 bocap  wheel     86 Sep 10 23:31 postmaster.pid
DangnoMacBook-Pro:postgresql-9.6.5 bocap$ 

Nội dung các files trong 1 thư mục dữ liệu PostgreSQL (PGDATA)

Folder/files Nội dung
PG_VERSION

File chứa nội dung phiên bản PostgreSQL hiện tại
ví dụ:


DangnoMacBook-Pro:postgresql-9.6.5 bocap$ cat $PGDATA/PG_VERSION
9.6

base Thư mục con chứa dữ liệu của các database trong database cluster. Trong thư mục này chứa các thư mục con nữa cho mỗi database. Tên thư mục đặt theo oid của database tương ứng.

ví dụ:


DangnoMacBook-Pro:postgresql-9.6.5 bocap$ ll $PGDATA/base
total 0
drwx------  270 bocap  wheel  9180 Sep 10 23:19 1
drwx------  270 bocap  wheel  9180 Sep 10 23:19 12668
drwx------  271 bocap  wheel  9214 Sep 10 23:32 12669
DangnoMacBook-Pro:postgresql-9.6.5 bocap$ psql
psql (9.6.5)
Type "help" for help.

postgres=>; select oid, datname from pg_database;
  oid  |  datname  
-------+-----------
 12669 | postgres
     1 | template1
 12668 | template0
(3 rows)

postgres=>; 

global Thư mục con chứa các bảng sử dụng nội bộ trong PostgreSQL (system catalog). Ví dụ như catalog chứa thông tin về database pg_database.
pg_commit_ts Thư mục con chứa thông tin về trạng thái commit của dữ liệu timestamp.
pg_clog Thư mục con chứa thông tin về trạng thái commit của transaction trên database cluster hiện tại. Mỗi bit dữ liệu chứa thông tin trạng thái cho một transaction. offset của file trong thư mục này tương ứng với transaction ID, vì vậy PostgreSQL có thể xem thông tin trạng thái transaction thông qua offset đó.
pg_dynshmem Thư mục con chứa các file sử dụng dynamic shared memory.
pg_logical Thư mục con chứa trạng thái dữ liệu sử dụng trong chức năng logical decoding (chức năng decoding dữ liệu từ WAL).
pg_multixact Thư mục con chứa dữ liệu trạng thái multitransaction (sử dụng cho locks mức độ dòng dữ liệu).
pg_notify Thư mục con chứa dữ liệu về chức năng LISTEN/NOTIFY.
pg_replslot Thư mục con chứa dữ liệu về replication slot
pg_serial Thư mục con chứa thông tin về các transaction commited ở mức độ phân li serializable.
pg_snapshots Thư mục con chứa thông tin về các snapshots đã xuất.
pg_stat Thư mục con chứa các files thông tin thống kê về PostgreSQL đang được sử dụng hiện tại.
pg_stat_tmp Thư mục con chứa các files thông tin thống kê về PostgreSQL tạm thời, chưa được đưa vào sử dụng.
pg_subtrans Thư mục con chứa dữ liệu về các subtransaction (khi sử dụng SAVEPOINT).
pg_tblspc Thư mục con chứa thông tin symbolic links tới các tablespaces. khi tạo 1 TABLESPACE để chứa dữ liệu bên ngoài database cluster, PostgreSQL sẽ tạo một symbolic links tới thư mục tạo từ TABLESPACE trong thư mục này.
pg_twophase Thư mục con chứa các tập tin trạng thái cho các prepared transactions.
pg_xlog Thư mục con chứa thông tin về WAL files. Phiên bản PostgreSQL 10, thư mục này chuyển thành pg_wal.
postgresql.auto.conf File chứa thông tin về các cấu hình tham số thiết lập bởi lệnh ALTER SYSTEM.
postmaster.opts A file recording the command-line options the server was last started with. File này chứa thông tin về các tuỳ chọn lần cuối của lệnh khởi động PostgreSQL.
ví dụ: 

DangnoMacBook-Pro:postgresql-9.6.5 bocap$ cat /usr/local/pgsql/pg9600/data/postmaster.opts 
/usr/local/pgsql/pg9600/bin/postgres

postmaster.pid File này tạo ra khi khởi động PostgreSQL và mất đi khi shutdown PostgreSQL. File chứa thông tin về PID của postmaster process, đường dẫn thư mục dữ liệu, thời gian khởi động, số hiệu port, đường dẫn Unix-domain socket (là trống trên môi trường Windows), giá trị hiệu lực đầu tiên chỉ định trong tham số listen_address và segment ID shared memory (tạo lúc khởi động PostgreSQL).
Đăng kí nhận RSS - thư mục dữ liệu