21 de fevereiro de 2012

Backup Full PostgreSQL com "pg_dumpall"

Este post é parte integrante doutro principal "Soluções de Backup e Restore para PostgreSQL". Vamos ver de forma sucinta e objetiva como realizar o backup (cópia de segurança) full e restore (restauração do backup) full do PostgreSQL, utilizando respectivamente o "pg_dumpall" e o "psql", que consistem em ferramentas que compõe o referido SGDB.
A principal vantagem do "pg_dumpall", é o backup de todo o cluster, incluindo schemas, bancos de dados, tabelas, templates, usuários e roles, assim como suas permissões.
A facilidade do restore, também pode ser considerado uma vantagem, uma vez que segue o mesmo princípio do backup, que também é full. Esta característica, também pode ser uma desvantagem, devido a dificuldade de restore's parciais.
Os procedimentos serão realizados a partir de um cluster, onde serão utilizados nos exemplos as configurações default:
porta [5432]
usuário [postgres]
host [localhost]
sem tablespace.

Backup full
Sintaxe:
pg_dumpall -p <porta> -U <usuario> -h <host> -f <path/nome_arquivo_backup>
Onde:
porta: porta do cluster
usuario: usuário com perfil superusuário
host: identificação do servidor
path/nome_arquivo_backup: Caminho e Nome do arquivo de backup

Exemplo (com usuário postgres):
~$ pg_dumpall -p 5432 -U postgres -h localhost -f /backup/backup_completo_postgres-AAMMDDhhmm.sql
Exemplo (com usuário root):
~# su - postgres -c 'pg_dumpall -p 5432 -U postgres -h localhost -f /backup/backup_completo_postgres-AAMMDDhhmm.sql' 


Restore full
Sintaxe:
psql -p <porta> -U <usuario> -h <host> < <path/nome_arquivo_backup>
Exemplo (com usuário postgres):
~$ psql -p 5432 -U postgres -h localhost < /backup/backup_completo_postgres-AAMMDDhhmm.sql

Tablespace
É essencial conhecer o caminho e nome de tablespace's no ambiente, a fim de evitar surpresas em caso de restores, uma vez que as pastas deste recurso, exceto quelas default, devem ser criadas previamente, com as devidas permissões aplicadas. Veja como saber se há tablespace's em seu ambiente.
~$ psql -p 5432 -h localhost
psql (9.1.2)
Type "help" for help.
postgres=# \c postgres
You are now connected to database "postgres" as user "postgres".
postgres=# SELECT * FROM pg_tablespace ;
  spcname   | spcowner |   spclocation   | spcacl | spcoptions
------------+----------+-----------------+--------+------------
 pg_default |       10 |                 |        |
 pg_global  |       10 |                 |        |
 sobdemanda |       10 | /opt/sobdemanda |        |
(3 rows)

No exemplo acima, foram listadas três tablespaces, sendo "pg_default" o padrão para criação dos bancos de dados, o "pg_global" que é utilizado para os catálogos do sistemas compartilhados, e "sobdemanda", que consiste em uma tablespace criada para exemplificar este item.

Veja também:

Vale lembrar, que os exemplos acima são básicos e facilitam nossos trabalhos no dia a dia, uma vez estes utilitários possuem outros recursos adicionais, a saber.
Help "pg_dumpall"
~$ pg_dumpall --help
pg_dumpall extracts a PostgreSQL database cluster into an SQL script file.
Usage:
  pg_dumpall [OPTION]...
General options:
  -f, --file=FILENAME         output file name
  --lock-wait-timeout=TIMEOUT fail after waiting TIMEOUT for a table lock
  --help                      show this help, then exit
  --version                   output version information, then exit
Options controlling the output content:
  -a, --data-only             dump only the data, not the schema
  -c, --clean                 clean (drop) databases before recreating
  -g, --globals-only          dump only global objects, no databases
  -o, --oids                  include OIDs in dump
  -O, --no-owner              skip restoration of object ownership
  -r, --roles-only            dump only roles, no databases or tablespaces
  -s, --schema-only           dump only the schema, no data
  -S, --superuser=NAME        superuser user name to use in the dump
  -t, --tablespaces-only      dump only tablespaces, no databases or roles
  -x, --no-privileges         do not dump privileges (grant/revoke)
  --binary-upgrade            for use by upgrade utilities only
  --column-inserts            dump data as INSERT commands with column names
  --disable-dollar-quoting    disable dollar quoting, use SQL standard quoting
  --disable-triggers          disable triggers during data-only restore
  --inserts                   dump data as INSERT commands, rather than COPY
  --no-security-labels        do not dump security label assignments
  --no-tablespaces            do not dump tablespace assignments
  --no-unlogged-table-data    do not dump unlogged table data
  --quote-all-identifiers     quote all identifiers, even if not key words
  --use-set-session-authorization
                              use SET SESSION AUTHORIZATION commands instead of
                              ALTER OWNER commands to set ownership
Connection options:
  -h, --host=HOSTNAME      database server host or socket directory
  -l, --database=DBNAME    alternative default database
  -p, --port=PORT          database server port number
  -U, --username=NAME      connect as specified database user
  -w, --no-password        never prompt for password
  -W, --password           force password prompt (should happen automatically)
  --role=ROLENAME          do SET ROLE before dump
If -f/--file is not used, then the SQL script will be written to the standard
output.
Report bugs to <pgsql-bugs@postgresql.org>.

Help "psql"
~$ psql --help
psql is the PostgreSQL interactive terminal.
Usage:
  psql [OPTION]... [DBNAME [USERNAME]]
General options:
  -c, --command=COMMAND    run only single command (SQL or internal) and exit
  -d, --dbname=DBNAME      database name to connect to (default: "postgres")
  -f, --file=FILENAME      execute commands from file, then exit
  -l, --list               list available databases, then exit
  -v, --set=, --variable=NAME=VALUE
                           set psql variable NAME to VALUE
  -X, --no-psqlrc          do not read startup file (~/.psqlrc)
  -1 ("one"), --single-transaction
                           execute command file as a single transaction
  --help                   show this help, then exit
  --version                output version information, then exit
Input and output options:
  -a, --echo-all           echo all input from script
  -e, --echo-queries       echo commands sent to server
  -E, --echo-hidden        display queries that internal commands generate
  -L, --log-file=FILENAME  send session log to file
  -n, --no-readline        disable enhanced command line editing (readline)
  -o, --output=FILENAME    send query results to file (or |pipe)
  -q, --quiet              run quietly (no messages, only query output)
  -s, --single-step        single-step mode (confirm each query)
  -S, --single-line        single-line mode (end of line terminates SQL command)
Output format options:
  -A, --no-align           unaligned table output mode
  -F, --field-separator=STRING
                           set field separator (default: "|")
  -H, --html               HTML table output mode
  -P, --pset=VAR[=ARG]     set printing option VAR to ARG (see \pset command)
  -R, --record-separator=STRING
                           set record separator (default: newline)
  -t, --tuples-only        print rows only
  -T, --table-attr=TEXT    set HTML table tag attributes (e.g., width, border)
  -x, --expanded           turn on expanded table output
Connection options:
  -h, --host=HOSTNAME      database server host or socket directory (default: "local socket")
  -p, --port=PORT          database server port (default: "5432")
  -U, --username=USERNAME  database user name (default: "postgres")
  -w, --no-password        never prompt for password
  -W, --password           force password prompt (should happen automatically)
For more information, type "\?" (for internal commands) or "\help" (for SQL
commands) from within psql, or consult the psql section in the PostgreSQL
documentation.
Report bugs to <pgsql-bugs@postgresql.org>.

Sem mais, abraço.

0 comentários:

Postar um comentário