SoFunction
Updated on 2025-04-08

PostgreSQL Tutorial (17): Client Commands (1)

Zero, password file:

Before giving other PostgreSQL client commands, we need to introduce the password files in PostgreSQL first. The reason why we explain this file in advance here is that we will apply the file in large quantities in the sample code below to ensure that our script can be completed automatically. In other words, if the file is not provided when the client command is executed, all client commands of PostgreSQL will be interrupted by password input prompts.
In the current user's HOME directory, we need to manually create a password file with the file name .pgpass, so that when we connect to the PostgreSQL server, the client command automatically reads the password information needed for login. The format of this file is as follows:
 

Copy the codeThe code is as follows:

    hostname:port:database:username:password
 

The above data is divided into five fields in total, representing the server host name (IP), the port number that the server listens to, the database name that the login access, the login user name and password. The first four fields can all be used to match any value using an asterisk (*). See the following example:
 
Copy the codeThe code is as follows:

    /> cat > .pgpass
    *:5432:postgres:postgres:123456
    CTRL+D
The permissions of #.pgpass file must be 0600, thereby preventing any global or group users from accessing, otherwise this file will be ignored.
    /> chmod 0600 .pgpass
 

Before learning the subsequent client commands, we need to manually create the file according to our application environment so that all the following sample codes will use the password file, so that they can be automatically completed in batch processing.

1. Createdb:

Create a new PostgreSQL database. This command is used as follows:
 

Copy the codeThe code is as follows:

    createdb [option...] [dbname] [description]
 

1. Command line options list:

Options illustrate
-D(--tablespace=tablespace) Specifies the default tablespace for the database.
-e(--echo) Echo the command generated by createb and send it to the server.
-E(--encoding=encoding) Specifies how the character encoding is used for this database.
-l(--locale=locale) Specifies the localization settings used for this database.
-O(--owner=owner) Specifies the owner of the newly created database, if this option is not specified, the value is the currently logged in user.
-T(--template=template) Specifies the template database to create this database.
-h(--host=host) Specifies the host name of the PostgreSQL server.
-p(--port=port) Specifies the server's listening port, if not specified, the default is 5432.
-U(--username=username) If the -O option is not specified, the Owner of this database will be the logged-in user.
-w(--no-password) If the currently logged in user does not have a password, you can specify this option to log in directly.

2. Application example:

Copy the codeThe code is as follows:

#1. Log in as postgres. (For details, please refer to the content of the password file above)
    /> psql
#2. Create a tablespace.
    postgres=# CREATE TABLESPACE my_tablespace LOCATION '/opt/PostgreSQL/9.1/mydata';
    CREATE TABLESPACE
#3. Create the owner of the new database.
    postgres=# CREATE ROLE myuser LOGIN PASSWORD '123456';
    CREATE ROLE
    postgres=# \q
#4. Create a new database, where the logged-in user for this connection is postgres, the owner of the new database is myuser, the table space is my_tablespace, and the new database is called mydatabase.
    /> createdb -U postgres -O myuser -D my_tablespace -e mydatabase
    CREATE DATABASE mydatabase OWNER myuser TABLESPACE my_tablespace;
#5. Log in again and check the system table to see if the database was created successfully and whether the tablespace and owner are consistent.
    /> psql
    postgres=# SELECT datname,rolname,spcname FROM pg_database db, pg_authid au, pg_tablespace ts WHERE datname = 'mydatabase' AND datdba = AND dattablespace = ;
      datname   | rolname |    spcname
    ------------+---------+---------------
     mydatabase | myuser  | my_tablespace
    (1 row)

2. dropdb:

Delete an existing PostgreSQL database.
 

Copy the codeThe code is as follows:

    dropdb [option...] dbname
 

1. Command line options list:

 

Options illustrate
-e(--echo) Echo the command generated by dropdb and send it to the server.
-i(--interactive) Prompt before doing any destructive action.
-q(--quiet) No response is displayed.
-h(--host=host) Specifies the host name of the PostgreSQL server.
-p(--port=port) Specify the server's listening port, if not specified, it is the default 5432.
-U(--username=username) The login user name for this operation.
-w(--no-password) If the currently logged in user does not have a password, you can specify this option to log in directly.

2. Application example:

Copy the codeThe code is as follows:

#Connect the server as postgres and delete the mydatabase database.
    /> dropdb -U postgres -e mydatabase
    DROP DATABASE mydatabase;
# Verify that the database has been deleted by viewing the system table.
    /> psql
    postgres=# SELECT count(*) FROM pg_database WHERE datname = 'mydatabase';
     count
    -------
         0
    (1 row)

3. reindexdb:

Rebuild the index for a specified PostgreSQL database.
 

Copy the codeThe code is as follows:

    reindexdb [connection-option...] [--table | -t table ] [--index | -i index ] [dbname]
    reindexdb [connection-option...] [--all | -a]
    reindexdb [connection-option...] [--system | -s] [dbname]
 

1. Command line options list:

 

Options illustrate
-a(-all) Reconstruct the index of the entire database.
-e(--echo) Echo the command generated by reindexdb and send it to the server.
-i(--index=index) Rebuild only the specified index.
-q(--quiet) No response is displayed.
-s(--system) Reconstruct the index of the database system table.
-t(--table=table) Rebuild only the index of the specified data table.
-h(--host=host) Specifies the host name of the PostgreSQL server.
-p(--port=port) Specify the server's listening port, if not specified, it is the default 5432.
-U(--username=username) The login user name for this operation.
-w(--no-password) If the currently logged in user does not have a password, you can specify this option to log in directly.

2. Application example:
 

Copy the codeThe code is as follows:

#Reconstruct only all indexes on the data table testtable.
    /> reindexdb -t testtable -e -U postgres postgres
    REINDEX TABLE testtable;
#Rebuild only the specified index testtable_idx
    /> reindexdb -i testtable_idx -e -U postgres postgres
    REINDEX INDEX testtable_idx;   
#Reconstruct all indexes of the specified database mydatabase.
    /> reindexdb mydatabase

4. vacuumdb:

Collect garbage and analyze a PostgreSQL database.
 

Copy the codeThe code is as follows:

    vacuumdb [-options] [--full | -f] [--verbose | -v] [--analyze | -z] [-t table [(column [,...])]] [dbname]
    vacuumdb [-options] [--all | -a] [--full | -f] [--verbose | -v] [--analyze | -z]
 

1. Command line options list:
 
Options illustrate
-a(--all) Clean all databases.
-e(--echo) Echo the command generated by vacuumdb and send it to the server.
-f(--full) Perform a complete cleanup.
-q(--quiet) No response is displayed.
-t table [(column[,...])] Only clean or analyze the specified data table, the field name only needs to be declared when used in conjunction with the --analyze option.
-v(--verbose) Print detailed information during processing.
-z(--analyze) Calculate the statistics used for the planner.
-h(--host=host) Specifies the host name of the PostgreSQL server.
-p(--port=port) Specify the server's listening port, if not specified, it is the default 5432.
-U(--username=username) The login user name for this operation.
-w(--no-password) If the currently logged in user does not have a password, you can specify this option to log in directly.

2. Application example:

Copy the codeThe code is as follows:

#Clean the entire database mydatabase.
    /> vacuumdb -e mydatabase
    VACUUM;
#Clean and analyze the testtable table in the postgres database.
    /> vacuumdb -e --analyze --table 'testtable' postgres
    VACUUM ANALYZE testtable;
#Clean and analyze the i field of the testtable table in the postgres database.
    /> vacuumdb -e --analyze -t 'testtable(i)' postgres
    VACUUM ANALYZE testtable(i);
 

V. createuser:

Define a new PostgreSQL user account. It should be noted that only super users or users with CREATEROLE permissions can execute this command. If you want to create a super user, you can only execute the command as a super user. In other words, a normal user with CREATEROLE permission cannot create a super user. This command is used as follows:
 

Copy the codeThe code is as follows:

    createuser [option...] [username]
 

1. Command line options list:

Options illustrate
-c number Sets the maximum number of connections for newly created users, the default is no limit.
-d(--createdb) Allows the new user to create a database.
-D(--no-createdb) This new user is prohibited from creating a database.
-e(--echo) Echo the command generated by createuser and send it to the server.
-E(--encrypted) Encrypt the user password saved in the database. If not declared, the default value is used.
-i(--inherit) The newly created role will automatically inherit the permissions of its group roles.
-I(--no-inherit) A newly created role does not automatically inherit the permissions of its group roles.
-l(--login) The new role will be granted login permission, which is the default option.
-L(--no-login) The new role is not granted login permission.
-N(--unencrypted) The user password stored in the database is not encrypted. If not declared, the default value is used.
-P(--pwprompt) If this option is given, a password will be prompted to be set when creating a user.
-r(--createrole) The new role is granted permission to create the database.
-R(--no-createrole) The new role is not granted permission to create the database.
-s(--superuser) The new role is a superuser.
-S(--no-superuser) The new role is not a superuser.
-h(--host=host) Specifies the host name of the PostgreSQL server.
-p(--port=port) Specify the server's listening port, if not specified, it is the default 5432.
-U(--username=username) The login user name for this operation.
-w(--no-password) If the currently logged in user does not have a password, you can specify this option to log in directly.

2. Application example:

Copy the codeThe code is as follows:

# For some options that do not have default settings, such as -(d/D), -(s/S) and -(r/R), if not specified directly on the command line, a prompt message will be given when executing the command.
# It should be noted that this prompt will suspend the automation script and the command will not continue to be executed until it is entered.
    /> createuser -U postgres myuser
    Shall the new role be a superuser? (y/n) n
    Shall the new role be allowed to create databases? (y/n) y
    Shall the new role be allowed to create more new roles? (y/n) n
    CREATE ROLE myuser NOSUPERUSER CREATEDB NOCREATEROLE INHERIT LOGIN;
# After logging in through psql, view the system view to verify that the user was successfully created and whether the permissions of the new role are correct.
    /> psql
    postgres=# SELECT rolname,rolsuper,rolinherit,rolcreaterole,rolcreatedb,rolcanlogin FROM pg_roles WHERE rolname = 'myuser';
     rolname | rolsuper | rolinherit | rolcreaterole | rolcreatedb | rolcanlogin
    ---------+----------+------------+---------------+-------------+-------------
     myuser  | f           | t             | f                  | t                 | t
    (1 row)
# In order to ensure that the automation script will not be suspended by the prompt of this command, we need to specify all options without default values ​​when executing the command.
    /> createuser -U postgres -e -S -D -R myuser2
    CREATE ROLE myuser2 NOSUPERUSER NOCREATEDB NOCREATEROLE INHERIT LOGIN;
# We can specify the user's password immediately when creating the user. This operation is completed by the -P option, but this usage will definitely hang the automation script.
# Therefore, we can adopt a compromise method, that is, do not specify a password when creating a user, and then manually use the user's password after the automated script is successfully executed.
    /> createuser -P -s -e myuser3
    Enter password for new role:
    Enter it again:
    CREATE ROLE myuser3 PASSWORD 'md5fe54c4f3129f2a766f53e4f4c9d2a698' SUPERUSER CREATEDB CREATEROLE INHERIT LOGIN;

6. dropuser:

To delete a PostgreSQL user account, it should be noted that only the super user or the user with CREATEROLE permission can execute the command. If you want to delete the super user, you can only execute the command through the super user's identity. This command is used as follows:
 

Copy the codeThe code is as follows:

    dropuser [option...] [username]
 

1. Command line options list:

 

Options illustrate
-e(--echo) Echo the command generated by dropuser and send it to the server.
-i(--interactive) Prompt before doing any destructive action.
-h(--host=host) Specifies the host name of the PostgreSQL server.
-p(--port=port) Specify the server's listening port, if not specified, it is the default 5432.
-U(--username=username) The login user name for this operation.

2. Application example:
 

Copy the codeThe code is as follows:

# Delete the specified user directly.
    /> dropuser -e myuser3
    DROP ROLE myuser3;
# When deleting a specified user, this command will give a prompt message to avoid misoperation.
    /> dropuser -e -i myuser2
    Role "myuser2" will be permanently removed.
    Are you sure? (y/n) y
    DROP ROLE myuser2;