diff options
-rw-r--r-- | docs/postgresql/index.rhtml | 120 |
1 files changed, 73 insertions, 47 deletions
diff --git a/docs/postgresql/index.rhtml b/docs/postgresql/index.rhtml index 45c57ac..54a6933 100644 --- a/docs/postgresql/index.rhtml +++ b/docs/postgresql/index.rhtml @@ -1,68 +1,94 @@ <h1>PostgreSQL</h1> <h2>SQL Dump</h2> -<p>L'idea dietro a questo metodo di dump è quello di generare un file con comandi SQL che, +<p class="hyphens">L'idea dietro a questo metodo di dump è quello di generare un file con comandi SQL che, quando eseguiti dal server, ricrea il database nello stesso stato come quando è stato eseguito il dump. PostgreSQL fornisce uno strumento che si chiama <code>pg_dump</code> che serve proprio a questo scopo. L'uso base di qeusto comando è il seguente:</p> -<pre> +<pre class="bordered"> pg_dump dbname > dumpfile </pre> -<pre style="background: cyan"> -As you see, pg_dump writes its result to the standard output. We will see below how this can be useful. While the above command creates a text file, pg_dump can create files in other formats that allow for parallism and more fine-grained control of object restoration. - -pg_dump is a regular PostgreSQL client application (albeit a particularly clever one). This means that you can perform this backup procedure from any remote host that has access to the database. But remember that pg_dump does not operate with special permissions. In particular, it must have read access to all tables that you want to back up, so in order to back up the entire database you almost always have to run it as a database superuser. (If you do not have sufficient privileges to back up the entire database, you can still back up portions of the database to which you do have access using options such as -n schema or -t table.) - -To specify which database server pg_dump should contact, use the command line options -h host and -p port. The default host is the local host or whatever your PGHOST environment variable specifies. Similarly, the default port is indicated by the PGPORT environment variable or, failing that, by the compiled-in default. (Conveniently, the server will normally have the same compiled-in default.) - -Like any other PostgreSQL client application, pg_dump will by default connect with the database user name that is equal to the current operating system user name. To override this, either specify the -U option or set the environment variable PGUSER. Remember that pg_dump connections are subject to the normal client authentication mechanisms (which are described in Chapter 19). - -An important advantage of pg_dump over the other backup methods described later is that pg_dump's output can generally be re-loaded into newer versions of PostgreSQL, whereas file-level backups and continuous archiving are both extremely server-version-specific. pg_dump is also the only method that will work when transferring a database to a different machine architecture, such as going from a 32-bit to a 64-bit server. - -Dumps created by pg_dump are internally consistent, meaning, the dump represents a snapshot of the database at the time pg_dump began running. pg_dump does not block other operations on the database while it is working. (Exceptions are those operations that need to operate with an exclusive lock, such as most forms of ALTER TABLE.) - - - -24.1.1. Restoring the Dump - -Text files created by pg_dump are intended to be read in by the psql program. The general command form to restore a dump is - +<p class="hyphens">Come è facilmente intuibile, il risultato viene scritto nello standard output (nell'esempio + precedente è reindirizzato verso il file <i>dumpfile</i>). Si vedrà più avanti come questo + può essere utile, infatti <code>pg_dump</code> può creare file in altri formati oltre a quelli + testuali; è un client PostgresSQL classico, ciò significa che può eseguire i backup da + qualsiasi postazione remota che abbia un accesso al database. Bisogna ricordarsi che <code>pg_dump</code> non opera + con alcun permesso speciale. In particolare, deve avere un accesso in lettura a tutte le tabelle delle quali si + vuole fare un backup, mentre per eseguire un backup di tutto il database è necessario avviarlo come + super-utente (se non si hanno abbastanza privilegi per eseguire il backup di un intero database, è comunque + possibile farlo tramite le opzioni <code>-n schema</code> o <code>-t tabella</code>).</p> + +<p class="hyphens">Per specificare quale database <code>pg_dump</code> debba contattare, si usa l'opzione + <code>-h host</code> ed eventualmente, specificandone la porta con <code>-p porta</code>. L'host predefinito + è <i>localhost</i> o se impostata, viene recuperato il valore dalla variabile d'ambiente + <code>PGHOST</code>, analogamente, la porta predefinita è la <i>5432</i>, altrimenti viene recuperata dalla + variabile d'ambiente <code>PGPORT</code>.</p> + +<p class="hyphens">Come qualsiasi altro client di PostgreSQL, <code>pg_dump</code> si connette usando la username + dell'utente che attualmente sta usando il sistema operativo. Per poter specificare un'altra utenza, si usa + l'opzione <code>-U utente</code> o impostare la variabile d'ambiente <code>PGUSER</code>.</p> + +<p class="hyphens">Tipicamente, i dump generati con <code>pg_dump</code> possono essere caricati anche nelle nuove + versioni di PostgreSQL e sono internamente consistenti, ciò significa che rappresentano un'esatta immagine + del database nell'istante in cui l'operazione di backup ` stata avviata. Si consideri inoltre che + <code>pg_dump</code> non blocca le altre operazioni sul database mentre questo sta lavorando (eccezion fatta per + quelle operazioni necessitano di un lock esclusivo, come le più diffuse varianti di + <code>ALTER TABLE</code>.</p> + +<h2>Ripristinare il dump</h2> +<p class="hyphens">Il file creati con <code>pg_dump</code> sono pensati per essere letti dal programma + <code>psql</code>. Il comando generico per ripristinare un dump è il seguente: + +<pre class="bordered"> psql dbname < dumpfile +</pre> -where dumpfile is the file output by the pg_dump command. The database dbname will not be created by this command, so you must create it yourself from template0 before executing psql (e.g., with createdb -T template0 dbname). psql supports options similar to pg_dump for specifying the database server to connect to and the user name to use. See the psql reference page for more information. Non-text file dumps are restored using the pg_restore utility. - -Before restoring an SQL dump, all the users who own objects or were granted permissions on objects in the dumped database must already exist. If they do not, the restore will fail to recreate the objects with the original ownership and/or permissions. (Sometimes this is what you want, but usually it is not.) - -By default, the psql script will continue to execute after an SQL error is encountered. You might wish to run psql with the ON_ERROR_STOP variable set to alter that behavior and have psql exit with an exit status of 3 if an SQL error occurs: - -psql --set ON_ERROR_STOP=on dbname < dumpfile - -Either way, you will only have a partially restored database. Alternatively, you can specify that the whole dump should be restored as a single transaction, so the restore is either fully completed or fully rolled back. This mode can be specified by passing the -1 or --single-transaction command-line options to psql. When using this mode, be aware that even a minor error can rollback a restore that has already run for many hours. However, that might still be preferable to manually cleaning up a complex database after a partially restored dump. - -The ability of pg_dump and psql to write to or read from pipes makes it possible to dump a database directly from one server to another, for example: +<p class="hyphens">Dove <i>dumpfile</i> è il file di output generato tramite il comando <code>pg_dump</code>. Il + database <i>dbname</i> non viene creato con questo comando, quindi bisogna crearlo manualmente da <i>template0</i> + prima di eseguire <code>psql</code> (per esempio con <code>createdb -T template0 dbname</code>). <code>psql</code> + supporta le stesse opzioni di <code>pg_dump</code> per specificare il server al quale connettersi e l'utenza da + usare. I dump che non sono salvati su file devono essere ripristinati tramite lo strumento + <code>pg_restore</code>.</p> -pg_dump -h host1 dbname | psql -h host2 dbname +<p class="hyphens">Prima di ripristinare un dump SQL, tutti gli utenti che sono proprietari o che hanno permessi su + oggetti che sono finiti nel dump devono essere già presenti, se non lo sono, il ripristino fallirà + cercando di ricreare gli oggetti con i permessi originali (qualche volta è quello che si vuole, ma + tipicamente non è così).</p> - Important: The dumps produced by pg_dump are relative to template0. This means that any languages, procedures, etc. added via template1 will also be dumped by pg_dump. As a result, when restoring, if you are using a customized template1, you must create the empty database from template0, as in the example above. +<p class="hyphens"><code>psql</code> in modo predefinito continua l'esecuzione dopo che si verifica un errore SQL, + si potrebbe desiderare di eseguire <code>psql</code> con la variabile <code>ON_ERROR_STOP</code> impostata per + alterarne il comportamento ed avere <code>psql</code> che si interrompe con un exit status pari a 3.</p> -After restoring a backup, it is wise to run ANALYZE on each database so the query optimizer has useful statistics; see Section 23.1.3 and Section 23.1.6 for more information. For more advice on how to load large amounts of data into PostgreSQL efficiently, refer to Section 14.4. -24.1.2. Using pg_dumpall +<pre class="bordered">psql --set ON_ERROR_STOP=on dbname < dumpfile</pre> -pg_dump dumps only a single database at a time, and it does not dump information about roles or tablespaces (because those are cluster-wide rather than per-database). To support convenient dumping of the entire contents of a database cluster, the pg_dumpall program is provided. pg_dumpall backs up each database in a given cluster, and also preserves cluster-wide data such as role and tablespace definitions. The basic usage of this command is: +<p class="hyphens">Altrimenti, si ottiene un database ripristinato parzialmente. Altrimenti è possibile + specificare che un intero dump debba essere ripristinato come una singola transazione, quindi il restore è + completamente ripristinato o viene effettauto un rollback completo. Questa modalità può essere + specificata passando l'opzione <code>-1</code> o <code>--single-transaction</code>. Quando si usa questa + modalità, bisogna essere consapevoli che anche un errore minore può causare un rollback di un + ripristino che è stato eseguito molte ore prima. Comunque, è sempre preferibile piuttosto che + pulire manualmente un database complesso dopo un ripristino parziale.</p> -pg_dumpall > dumpfile +<p class="hyphens">L'abilità di <code>pg_dump</code> e <code>pssql</code> di scrivere e leggere dalle pipe, + rende possibile la creazione di un dump direttamente da un server ad un altro, per esempio:</p> -The resulting dump can be restored with psql: +<pre class="bordered">pg_dump -h host1 dbname | psql -h host2 dbname</pre> -psql -f dumpfile postgres +<p class="hyphens"><b>IMPORTANTE:</b> i dump prodotti da <code>pg_dump</code> sono relativi a <i>template0</i>, questo + significa che qualsiasi lingauggio, procedura, ecc. aggiunti tramite <i>template1</i> saranno messi nel dump + da <code>pg_dump</code>. Come risultato, quando si esegue il ripristino, se si sta usando un <i>template1</i> + personalizzato, si deve creare un database vuoto da <i>template0</i>, come nell'esempio precedente.</p> -(Actually, you can specify any existing database name to start from, but if you are loading into an empty cluster then postgres should usually be used.) It is always necessary to have database superuser access when restoring a pg_dumpall dump, as that is required to restore the role and tablespace information. If you use tablespaces, make sure that the tablespace paths in the dump are appropriate for the new installation. +<h2>Usare <code>pg_dumpall</code></h2> +<p class="hyphens"><code>pg_dump</code> effettua il dump di un singolo database alla volta, non effettua il dump delle + informazioni su ruoli e tablespace. Per effettuare il dump di un intero cluster di database, esiste il programma + <code>pg_dumpall</code>. L'utilizzo base del comando è il seguente:</p> -pg_dumpall works by emitting commands to re-create roles, tablespaces, and empty databases, then invoking pg_dump for each database. This means that while each database will be internally consistent, the snapshots of different databases are not sychronized. +<pre class="bordered">pg_dumpall > dumpfile</pre> -Cluster-wide data can be dumped alone using the pg_dumpall --globals-only option. This is necessary to fully backup the cluster if running the pg_dump command on individual databases. -</pre> +<p class="hyphens">Il dump che ne risulta può essere ripristinato tramite <code>psql</code>:</p> +<pre class="bordered">psql -f dumpfile postgres</pre> <h2>Gestire grandi database</h2> <p>Alcuni sistemi operativi hanno i limiti massimi sulla dimensione dei file che potrebbero causare @@ -72,15 +98,15 @@ Cluster-wide data can be dumped alone using the pg_dumpall --globals-only option <p>Usare dei dump compressi:</p> <p>Si può usare qualsiasi programma di compressione che si preferisce, ad esempio con <code>gzip</code> -<pre> +<pre class="bordered"> pg_dump dbname | gzip > filename.gz </pre> <p>Si ripristina con:</p> -<pre> +<pre class="bordered"> gunzip -c filename.gz | psql dbname </pre> <p>Oppure</p> -<pre> +<pre class="bordered"> cat filename.gz | gunzip | psql dbname </pre> |