diff options
| author | Bruce Momjian <bruce@momjian.us> | 2001-03-22 04:01:46 +0000 |
|---|---|---|
| committer | Bruce Momjian <bruce@momjian.us> | 2001-03-22 04:01:46 +0000 |
| commit | 9e1552607a9dc6bc23e43d46770a9063ade4f3f0 (patch) | |
| tree | 6a230d81917ebc004e40cd46c48f2aa27eec153e /src/bin/pg_dump | |
| parent | 6cf8707b828b14b5c2336076ce358b18b67829d6 (diff) | |
| download | postgresql-9e1552607a9dc6bc23e43d46770a9063ade4f3f0.tar.gz | |
pgindent run. Make it all clean.
Diffstat (limited to 'src/bin/pg_dump')
| -rw-r--r-- | src/bin/pg_dump/common.c | 56 | ||||
| -rw-r--r-- | src/bin/pg_dump/pg_backup.h | 132 | ||||
| -rw-r--r-- | src/bin/pg_dump/pg_backup_archiver.c | 1695 | ||||
| -rw-r--r-- | src/bin/pg_dump/pg_backup_archiver.h | 387 | ||||
| -rw-r--r-- | src/bin/pg_dump/pg_backup_custom.c | 827 | ||||
| -rw-r--r-- | src/bin/pg_dump/pg_backup_db.c | 342 | ||||
| -rw-r--r-- | src/bin/pg_dump/pg_backup_db.h | 21 | ||||
| -rw-r--r-- | src/bin/pg_dump/pg_backup_files.c | 449 | ||||
| -rw-r--r-- | src/bin/pg_dump/pg_backup_null.c | 98 | ||||
| -rw-r--r-- | src/bin/pg_dump/pg_backup_tar.c | 860 | ||||
| -rw-r--r-- | src/bin/pg_dump/pg_backup_tar.h | 58 | ||||
| -rw-r--r-- | src/bin/pg_dump/pg_dump.c | 911 | ||||
| -rw-r--r-- | src/bin/pg_dump/pg_dump.h | 15 | ||||
| -rw-r--r-- | src/bin/pg_dump/pg_restore.c | 292 |
14 files changed, 3289 insertions, 2854 deletions
diff --git a/src/bin/pg_dump/common.c b/src/bin/pg_dump/common.c index 2e7281265f..21d7ca2e2c 100644 --- a/src/bin/pg_dump/common.c +++ b/src/bin/pg_dump/common.c @@ -8,7 +8,7 @@ * * * IDENTIFICATION - * $Header: /cvsroot/pgsql/src/bin/pg_dump/common.c,v 1.53 2001/02/10 02:31:27 tgl Exp $ + * $Header: /cvsroot/pgsql/src/bin/pg_dump/common.c,v 1.54 2001/03/22 04:00:11 momjian Exp $ * * Modifications - 6/12/96 - dave@bensoft.com - version 1.13.dhb.2 * @@ -16,8 +16,8 @@ * - Added single. quote to twin single quote expansion for 'insert' string * mode. * - * Modifications 14-Sep-2000 - pjw@rhyme.com.au - * - Added enum for findTypeByOid to specify how to handle OID and which + * Modifications 14-Sep-2000 - pjw@rhyme.com.au + * - Added enum for findTypeByOid to specify how to handle OID and which * string to return - formatted type, or base type. If the base type * is returned then fmtId is called on the string. * @@ -59,13 +59,17 @@ findTypeByOid(TypeInfo *tinfo, int numTypes, const char *oid, OidOptions opts) { int i; - if (strcmp(oid, "0") == 0) { + if (strcmp(oid, "0") == 0) + { - if ( (opts & zeroAsOpaque) != 0 ) { + if ((opts & zeroAsOpaque) != 0) + { return g_opaque_type; - } else if ( (opts & zeroAsAny) != 0 ) { + } + else if ((opts & zeroAsAny) != 0) + { return "'any'"; @@ -74,17 +78,17 @@ findTypeByOid(TypeInfo *tinfo, int numTypes, const char *oid, OidOptions opts) for (i = 0; i < numTypes; i++) { - if (strcmp(tinfo[i].oid, oid) == 0) { - if ( (opts & useBaseTypeName) != 0 ) { - return (char*) fmtId(tinfo[i].typname, false); - } else { + if (strcmp(tinfo[i].oid, oid) == 0) + { + if ((opts & useBaseTypeName) != 0) + return (char *) fmtId(tinfo[i].typname, false); + else return tinfo[i].typedefn; - } } } /* no suitable type name was found */ - return(NULL); + return (NULL); } /* @@ -111,7 +115,7 @@ findOprByOid(OprInfo *oprinfo, int numOprs, const char *oid) oid); /* no suitable operator name was found */ - return(NULL); + return (NULL); } @@ -253,13 +257,13 @@ strInArray(const char *pattern, char **arr, int arr_size) */ TableInfo * -dumpSchema(Archive *fout, - int *numTablesPtr, - const char *tablename, - const bool aclsSkip, - const bool oids, - const bool schemaOnly, - const bool dataOnly) +dumpSchema(Archive *fout, + int *numTablesPtr, + const char *tablename, + const bool aclsSkip, + const bool oids, + const bool schemaOnly, + const bool dataOnly) { int numTypes; int numFuncs; @@ -342,7 +346,7 @@ dumpSchema(Archive *fout, g_comment_start, g_comment_end); dumpTables(fout, tblinfo, numTables, indinfo, numIndices, inhinfo, numInherits, - tinfo, numTypes, tablename, aclsSkip, oids, schemaOnly, dataOnly); + tinfo, numTypes, tablename, aclsSkip, oids, schemaOnly, dataOnly); if (fout && !dataOnly) { @@ -555,10 +559,12 @@ fmtId(const char *rawid, bool force_quotes) appendPQExpBufferChar(id_return, '\"'); for (cp = rawid; *cp; cp++) { - /* Did we find a double-quote in the string? - * Then make this a double double-quote per SQL99. - * Before, we put in a backslash/double-quote pair. - * - thomas 2000-08-05 */ + + /* + * Did we find a double-quote in the string? Then make this a + * double double-quote per SQL99. Before, we put in a + * backslash/double-quote pair. - thomas 2000-08-05 + */ if (*cp == '\"') { appendPQExpBufferChar(id_return, '\"'); diff --git a/src/bin/pg_dump/pg_backup.h b/src/bin/pg_dump/pg_backup.h index 6593a7e56f..12a6a56c7f 100644 --- a/src/bin/pg_dump/pg_backup.h +++ b/src/bin/pg_dump/pg_backup.h @@ -7,24 +7,24 @@ * See the headers to pg_restore for more details. * * Copyright (c) 2000, Philip Warner - * Rights are granted to use this software in any way so long - * as this notice is not removed. + * Rights are granted to use this software in any way so long + * as this notice is not removed. * * The author is not responsible for loss or damages that may * result from it's use. * * * IDENTIFICATION - * $Header: /cvsroot/pgsql/src/bin/pg_dump/pg_backup.h,v 1.8 2001/03/19 02:35:28 pjw Exp $ + * $Header: /cvsroot/pgsql/src/bin/pg_dump/pg_backup.h,v 1.9 2001/03/22 04:00:11 momjian Exp $ * * Modifications - 28-Jun-2000 - pjw@rhyme.com.au * - * Initial version. + * Initial version. * * * Modifications - 28-Jul-2000 - pjw@rhyme.com.au (1.45) * - * Added --create, --no-owner, --superuser, --no-reconnect (pg_dump & pg_restore) + * Added --create, --no-owner, --superuser, --no-reconnect (pg_dump & pg_restore) * Added code to dump 'Create Schema' statement (pg_dump) * Don't bother to disable/enable triggers if we don't have a superuser (pg_restore) * Cleaned up code for reconnecting to database. @@ -47,62 +47,67 @@ #include "libpq-fe.h" -typedef enum _archiveFormat { - archUnknown = 0, - archCustom = 1, - archFiles = 2, - archTar = 3, - archNull = 4 +typedef enum _archiveFormat +{ + archUnknown = 0, + archCustom = 1, + archFiles = 2, + archTar = 3, + archNull = 4 } ArchiveFormat; /* - * We may want to have so user-readbale data, but in the mean - * time this gives us some abstraction and type checking. + * We may want to have so user-readbale data, but in the mean + * time this gives us some abstraction and type checking. */ -typedef struct _Archive { +typedef struct _Archive +{ int verbose; - /* The rest is private */ + /* The rest is private */ } Archive; -typedef int (*DataDumperPtr)(Archive* AH, char* oid, void* userArg); +typedef int (*DataDumperPtr) (Archive *AH, char *oid, void *userArg); -typedef struct _restoreOptions { +typedef struct _restoreOptions +{ int create; /* Issue commands to create the database */ - int noOwner; /* Don't reconnect to database to match original object owner */ - int noReconnect; /* Don't reconnect to database under any cirsumstances */ - char *superuser; /* Username to use as superuser */ + int noOwner; /* Don't reconnect to database to match + * original object owner */ + int noReconnect; /* Don't reconnect to database under any + * cirsumstances */ + char *superuser; /* Username to use as superuser */ int dataOnly; int dropSchema; - char *filename; + char *filename; int schemaOnly; int verbose; int aclsSkip; int tocSummary; - char *tocFile; + char *tocFile; int oidOrder; int origOrder; int rearrange; int format; - char *formatName; + char *formatName; int selTypes; int selIndex; int selFunction; int selTrigger; int selTable; - char *indexNames; - char *functionNames; - char *tableNames; - char *triggerNames; + char *indexNames; + char *functionNames; + char *tableNames; + char *triggerNames; int useDB; - char *dbname; - char *pgport; - char *pghost; + char *dbname; + char *pgport; + char *pghost; int ignoreVersion; int requirePassword; - int *idWanted; + int *idWanted; int limitToList; int compression; @@ -112,63 +117,60 @@ typedef struct _restoreOptions { * Main archiver interface. */ -extern void exit_horribly(Archive *AH, const char *fmt, ...); +extern void exit_horribly(Archive *AH, const char *fmt,...); /* Lets the archibe know we have a DB connection to shutdown if it dies */ -PGconn* ConnectDatabase(Archive *AH, - const char* dbname, - const char* pghost, - const char* pgport, - const int reqPwd, - const int ignoreVersion); +PGconn *ConnectDatabase(Archive *AH, + const char *dbname, + const char *pghost, + const char *pgport, + const int reqPwd, + const int ignoreVersion); /* Called to add a TOC entry */ -extern void ArchiveEntry(Archive* AH, const char* oid, const char* name, - const char* desc, const char* (deps[]), const char* defn, - const char* dropStmt, const char* copyStmt, const char* owner, - DataDumperPtr dumpFn, void* dumpArg); +extern void ArchiveEntry(Archive *AH, const char *oid, const char *name, + const char *desc, const char *(deps[]), const char *defn, + const char *dropStmt, const char *copyStmt, const char *owner, + DataDumperPtr dumpFn, void *dumpArg); /* Called to write *data* to the archive */ -extern int WriteData(Archive* AH, const void* data, int dLen); +extern int WriteData(Archive *AH, const void *data, int dLen); -/* -extern int StartBlobs(Archive* AH); +/* +extern int StartBlobs(Archive* AH); extern int EndBlobs(Archive* AH); */ -extern int StartBlob(Archive* AH, int oid); -extern int EndBlob(Archive* AH, int oid); +extern int StartBlob(Archive *AH, int oid); +extern int EndBlob(Archive *AH, int oid); -extern void CloseArchive(Archive* AH); +extern void CloseArchive(Archive *AH); -extern void RestoreArchive(Archive* AH, RestoreOptions *ropt); +extern void RestoreArchive(Archive *AH, RestoreOptions *ropt); /* Open an existing archive */ -extern Archive* OpenArchive(const char* FileSpec, const ArchiveFormat fmt); +extern Archive *OpenArchive(const char *FileSpec, const ArchiveFormat fmt); /* Create a new archive */ -extern Archive* CreateArchive(const char* FileSpec, const ArchiveFormat fmt, - const int compression); +extern Archive *CreateArchive(const char *FileSpec, const ArchiveFormat fmt, + const int compression); /* The --list option */ -extern void PrintTOCSummary(Archive* AH, RestoreOptions *ropt); +extern void PrintTOCSummary(Archive *AH, RestoreOptions *ropt); -extern RestoreOptions* NewRestoreOptions(void); +extern RestoreOptions *NewRestoreOptions(void); /* Rearrange TOC entries */ -extern void MoveToStart(Archive* AH, char *oType); -extern void MoveToEnd(Archive* AH, char *oType); -extern void SortTocByOID(Archive* AH); -extern void SortTocByID(Archive* AH); -extern void SortTocFromFile(Archive* AH, RestoreOptions *ropt); +extern void MoveToStart(Archive *AH, char *oType); +extern void MoveToEnd(Archive *AH, char *oType); +extern void SortTocByOID(Archive *AH); +extern void SortTocByID(Archive *AH); +extern void SortTocFromFile(Archive *AH, RestoreOptions *ropt); /* Convenience functions used only when writing DATA */ -extern int archputs(const char *s, Archive* AH); -extern int archputc(const char c, Archive* AH); -extern int archprintf(Archive* AH, const char *fmt, ...); +extern int archputs(const char *s, Archive *AH); +extern int archputc(const char c, Archive *AH); +extern int archprintf(Archive *AH, const char *fmt,...); #endif - - - diff --git a/src/bin/pg_dump/pg_backup_archiver.c b/src/bin/pg_dump/pg_backup_archiver.c index cd0fd9c312..adaf7c46d2 100644 --- a/src/bin/pg_dump/pg_backup_archiver.c +++ b/src/bin/pg_dump/pg_backup_archiver.c @@ -8,18 +8,18 @@ * * Copyright (c) 2000, Philip Warner * Rights are granted to use this software in any way so long - * as this notice is not removed. + * as this notice is not removed. * * The author is not responsible for loss or damages that may * result from it's use. * * * IDENTIFICATION - * $Header: /cvsroot/pgsql/src/bin/pg_dump/pg_backup_archiver.c,v 1.21 2001/03/19 02:35:28 pjw Exp $ + * $Header: /cvsroot/pgsql/src/bin/pg_dump/pg_backup_archiver.c,v 1.22 2001/03/22 04:00:11 momjian Exp $ * * Modifications - 28-Jun-2000 - pjw@rhyme.com.au * - * Initial version. + * Initial version. * * Modifications - 31-Jul-2000 - pjw@rhyme.com.au (1.46, 1.47) * Fixed version number initialization in _allocAH (pg_backup_archiver.c) @@ -29,9 +29,9 @@ * Added {Start,End}RestoreBlobs to allow extended TX during BLOB restore. * * Modifications - 04-Jan-2001 - pjw@rhyme.com.au - * - strdup() the current user just in case it's deallocated from it's TOC - * entry. Should *never* happen, but that's what they said about the - * Titanic... + * - strdup() the current user just in case it's deallocated from it's TOC + * entry. Should *never* happen, but that's what they said about the + * Titanic... * * - Check results of IO routines more carefully. * @@ -49,7 +49,7 @@ #include "pg_backup_db.h" #include <string.h> -#include <unistd.h> /* for dup */ +#include <unistd.h> /* for dup */ #include <stdio.h> #include <stdlib.h> @@ -58,69 +58,75 @@ #include "pqexpbuffer.h" #include "libpq/libpq-fs.h" -static void _SortToc(ArchiveHandle* AH, TocSortCompareFn fn); -static int _tocSortCompareByOIDNum(const void *p1, const void *p2); -static int _tocSortCompareByIDNum(const void *p1, const void *p2); -static ArchiveHandle* _allocAH(const char* FileSpec, const ArchiveFormat fmt, - const int compression, ArchiveMode mode); -static int _printTocEntry(ArchiveHandle* AH, TocEntry* te, RestoreOptions *ropt); +static void _SortToc(ArchiveHandle *AH, TocSortCompareFn fn); +static int _tocSortCompareByOIDNum(const void *p1, const void *p2); +static int _tocSortCompareByIDNum(const void *p1, const void *p2); +static ArchiveHandle *_allocAH(const char *FileSpec, const ArchiveFormat fmt, + const int compression, ArchiveMode mode); +static int _printTocEntry(ArchiveHandle *AH, TocEntry *te, RestoreOptions *ropt); -static void _reconnectAsOwner(ArchiveHandle* AH, const char *dbname, TocEntry* te); -static void _reconnectAsUser(ArchiveHandle* AH, const char *dbname, char *user); +static void _reconnectAsOwner(ArchiveHandle *AH, const char *dbname, TocEntry *te); +static void _reconnectAsUser(ArchiveHandle *AH, const char *dbname, char *user); -static int _tocEntryRequired(TocEntry* te, RestoreOptions *ropt); -static void _disableTriggersIfNecessary(ArchiveHandle *AH, TocEntry *te, RestoreOptions *ropt); -static void _enableTriggersIfNecessary(ArchiveHandle *AH, TocEntry *te, RestoreOptions *ropt); -static TocEntry* _getTocEntry(ArchiveHandle* AH, int id); -static void _moveAfter(ArchiveHandle* AH, TocEntry* pos, TocEntry* te); -static void _moveBefore(ArchiveHandle* AH, TocEntry* pos, TocEntry* te); -static int _discoverArchiveFormat(ArchiveHandle* AH); +static int _tocEntryRequired(TocEntry *te, RestoreOptions *ropt); +static void _disableTriggersIfNecessary(ArchiveHandle *AH, TocEntry *te, RestoreOptions *ropt); +static void _enableTriggersIfNecessary(ArchiveHandle *AH, TocEntry *te, RestoreOptions *ropt); +static TocEntry *_getTocEntry(ArchiveHandle *AH, int id); +static void _moveAfter(ArchiveHandle *AH, TocEntry *pos, TocEntry *te); +static void _moveBefore(ArchiveHandle *AH, TocEntry *pos, TocEntry *te); +static int _discoverArchiveFormat(ArchiveHandle *AH); -static char *progname = "Archiver"; +static char *progname = "Archiver"; -static void _die_horribly(ArchiveHandle *AH, const char *fmt, va_list ap); +static void _die_horribly(ArchiveHandle *AH, const char *fmt, va_list ap); -static int _canRestoreBlobs(ArchiveHandle *AH); -static int _restoringToDB(ArchiveHandle *AH); +static int _canRestoreBlobs(ArchiveHandle *AH); +static int _restoringToDB(ArchiveHandle *AH); /* - * Wrapper functions. - * - * The objective it to make writing new formats and dumpers as simple - * as possible, if necessary at the expense of extra function calls etc. + * Wrapper functions. + * + * The objective it to make writing new formats and dumpers as simple + * as possible, if necessary at the expense of extra function calls etc. * */ /* Create a new archive */ /* Public */ -Archive* CreateArchive(const char* FileSpec, const ArchiveFormat fmt, - const int compression) +Archive * +CreateArchive(const char *FileSpec, const ArchiveFormat fmt, + const int compression) { - ArchiveHandle* AH = _allocAH(FileSpec, fmt, compression, archModeWrite); - return (Archive*)AH; + ArchiveHandle *AH = _allocAH(FileSpec, fmt, compression, archModeWrite); + + return (Archive *) AH; } /* Open an existing archive */ /* Public */ -Archive* OpenArchive(const char* FileSpec, const ArchiveFormat fmt) +Archive * +OpenArchive(const char *FileSpec, const ArchiveFormat fmt) { - ArchiveHandle* AH = _allocAH(FileSpec, fmt, 0, archModeRead); - return (Archive*)AH; + ArchiveHandle *AH = _allocAH(FileSpec, fmt, 0, archModeRead); + + return (Archive *) AH; } /* Public */ -void CloseArchive(Archive* AHX) +void +CloseArchive(Archive *AHX) { - int res = 0; - ArchiveHandle* AH = (ArchiveHandle*)AHX; - (*AH->ClosePtr)(AH); + int res = 0; + ArchiveHandle *AH = (ArchiveHandle *) AHX; + + (*AH->ClosePtr) (AH); - /* Close the output */ - if (AH->gzOut) + /* Close the output */ + if (AH->gzOut) res = GZCLOSE(AH->OF); - else if (AH->OF != stdout) + else if (AH->OF != stdout) res = fclose(AH->OF); if (res != 0) @@ -128,18 +134,19 @@ void CloseArchive(Archive* AHX) } /* Public */ -void RestoreArchive(Archive* AHX, RestoreOptions *ropt) +void +RestoreArchive(Archive *AHX, RestoreOptions *ropt) { - ArchiveHandle* AH = (ArchiveHandle*) AHX; - TocEntry *te = AH->toc->next; - int reqs; - OutputContext sav; - int impliedDataOnly; + ArchiveHandle *AH = (ArchiveHandle *) AHX; + TocEntry *te = AH->toc->next; + int reqs; + OutputContext sav; + int impliedDataOnly; AH->ropt = ropt; if (ropt->create && ropt->noReconnect) - die_horribly(AH, "%s: --create and --no-reconnect are incompatible options\n",progname); + die_horribly(AH, "%s: --create and --no-reconnect are incompatible options\n", progname); /* * If we're using a DB connection, then connect it. @@ -150,11 +157,12 @@ void RestoreArchive(Archive* AHX, RestoreOptions *ropt) if (AH->version < K_VERS_1_3) die_horribly(AH, "Direct database connections are not supported in pre-1.3 archives"); - ConnectDatabase(AHX, ropt->dbname, ropt->pghost, ropt->pgport, - ropt->requirePassword, ropt->ignoreVersion); + ConnectDatabase(AHX, ropt->dbname, ropt->pghost, ropt->pgport, + ropt->requirePassword, ropt->ignoreVersion); /* - * If no superuser was specified then see if the current user will do... + * If no superuser was specified then see if the current user will + * do... */ if (!ropt->superuser) { @@ -165,20 +173,23 @@ void RestoreArchive(Archive* AHX, RestoreOptions *ropt) } /* - * Work out if we have an implied data-only retore. This can happen if - * the dump was data only or if the user has used a toc list to exclude - * all of the schema data. All we do is look for schema entries - if none - * are found then we set the dataOnly flag. + * Work out if we have an implied data-only retore. This can happen if + * the dump was data only or if the user has used a toc list to + * exclude all of the schema data. All we do is look for schema + * entries - if none are found then we set the dataOnly flag. * - * We could scan for wanted TABLE entries, but that is not the same as + * We could scan for wanted TABLE entries, but that is not the same as * dataOnly. At this stage, it seems unnecessary (6-Mar-2001). - */ - if (!ropt->dataOnly) { + */ + if (!ropt->dataOnly) + { te = AH->toc->next; impliedDataOnly = 1; - while (te != AH->toc) { + while (te != AH->toc) + { reqs = _tocEntryRequired(te, ropt); - if ( (reqs & 1) != 0 ) { /* It's schema, and it's wanted */ + if ((reqs & 1) != 0) + { /* It's schema, and it's wanted */ impliedDataOnly = 0; break; } @@ -189,31 +200,34 @@ void RestoreArchive(Archive* AHX, RestoreOptions *ropt) ropt->dataOnly = impliedDataOnly; ahlog(AH, 1, "Implied data-only restore\n"); } - } + } if (!ropt->superuser) fprintf(stderr, "\n%s: ******** WARNING ******** \n" - " Data restoration may fail since any defined triggers\n" - " can not be disabled (no superuser username specified).\n" - " This is only a problem for restoration into a database\n" - " with triggers already defined.\n\n", progname); + " Data restoration may fail since any defined triggers\n" + " can not be disabled (no superuser username specified).\n" + " This is only a problem for restoration into a database\n" + " with triggers already defined.\n\n", progname); /* - * Setup the output file if necessary. + * Setup the output file if necessary. */ - if (ropt->filename || ropt->compression) + if (ropt->filename || ropt->compression) sav = SetOutput(AH, ropt->filename, ropt->compression); - ahprintf(AH, "--\n-- Selected TOC Entries:\n--\n"); + ahprintf(AH, "--\n-- Selected TOC Entries:\n--\n"); - /* - * Drop the items at the start, in reverse order + /* + * Drop the items at the start, in reverse order */ - if (ropt->dropSchema) { + if (ropt->dropSchema) + { te = AH->toc->prev; - while (te != AH->toc) { + while (te != AH->toc) + { reqs = _tocEntryRequired(te, ropt); - if ( ( (reqs & 1) != 0) && te->dropStmt) { /* We want the schema */ + if (((reqs & 1) != 0) && te->dropStmt) + { /* We want the schema */ ahlog(AH, 1, "Dropping %s %s\n", te->desc, te->name); /* Reconnect if necessary */ _reconnectAsOwner(AH, "-", te); @@ -222,18 +236,19 @@ void RestoreArchive(Archive* AHX, RestoreOptions *ropt) } te = te->prev; } - } + } /* * Now process each TOC entry */ - te = AH->toc->next; - while (te != AH->toc) { + te = AH->toc->next; + while (te != AH->toc) + { /* Work out what, if anything, we want from this entry */ reqs = _tocEntryRequired(te, ropt); - if ( (reqs & 1) != 0) /* We want the schema */ + if ((reqs & 1) != 0) /* We want the schema */ { /* Reconnect if necessary */ _reconnectAsOwner(AH, "-", te); @@ -242,67 +257,78 @@ void RestoreArchive(Archive* AHX, RestoreOptions *ropt) _printTocEntry(AH, te, ropt); /* If we created a DB, connect to it... */ - if (strcmp(te->desc,"DATABASE") == 0) + if (strcmp(te->desc, "DATABASE") == 0) { - ahlog(AH, 1, "Connecting to new DB '%s' as %s\n",te->name, te->owner); + ahlog(AH, 1, "Connecting to new DB '%s' as %s\n", te->name, te->owner); _reconnectAsUser(AH, te->name, te->owner); } } - /* - * If we want data, and it has data, then restore that too + /* + * If we want data, and it has data, then restore that too */ - if (AH->PrintTocDataPtr != NULL && (reqs & 2) != 0) { + if (AH->PrintTocDataPtr !=NULL && (reqs & 2) != 0) + { #ifndef HAVE_LIBZ if (AH->compression != 0) die_horribly(AH, "%s: Unable to restore data from a compressed archive\n", progname); #endif ahprintf(AH, "--\n-- Data for TOC Entry ID %d (OID %s) %s %s\n--\n\n", - te->id, te->oid, te->desc, te->name); + te->id, te->oid, te->desc, te->name); /* - * Maybe we can't do BLOBS, so check if this node is for BLOBS + * Maybe we can't do BLOBS, so check if this node is for BLOBS */ - if ((strcmp(te->desc,"BLOBS") == 0) && !_canRestoreBlobs(AH)) + if ((strcmp(te->desc, "BLOBS") == 0) && !_canRestoreBlobs(AH)) { ahprintf(AH, "--\n-- SKIPPED \n--\n\n"); + /* - * This is a bit nasty - we assume, for the moment, that if a custom - * output is used, then we don't want warnings. + * This is a bit nasty - we assume, for the moment, that + * if a custom output is used, then we don't want + * warnings. */ if (!AH->CustomOutPtr) fprintf(stderr, "%s: WARNING - skipping BLOB restoration\n", progname); - } else { + } + else + { _disableTriggersIfNecessary(AH, te, ropt); - /* Reconnect if necessary (_disableTriggers may have reconnected) */ + /* + * Reconnect if necessary (_disableTriggers may have + * reconnected) + */ _reconnectAsOwner(AH, "-", te); ahlog(AH, 1, "Restoring data for %s \n", te->name); - /* If we have a copy statement, use it. As of V1.3, these are separate - * to allow easy import from withing a database connection. Pre 1.3 - * archives can not use DB connections and are sent to output only. + /* + * If we have a copy statement, use it. As of V1.3, these + * are separate to allow easy import from withing a + * database connection. Pre 1.3 archives can not use DB + * connections and are sent to output only. * - * For V1.3+, the table data MUST have a copy statement so that - * we can go into appropriate mode with libpq. + * For V1.3+, the table data MUST have a copy statement so + * that we can go into appropriate mode with libpq. */ if (te->copyStmt && strlen(te->copyStmt) > 0) ahprintf(AH, te->copyStmt); - (*AH->PrintTocDataPtr)(AH, te, ropt); + (*AH->PrintTocDataPtr) (AH, te, ropt); _enableTriggersIfNecessary(AH, te, ropt); } } te = te->next; - } + } /* - * Now use blobs_xref (if used) to fixup any refs for tables that we loaded + * Now use blobs_xref (if used) to fixup any refs for tables that we + * loaded */ if (_canRestoreBlobs(AH) && AH->createdBlobXref) { @@ -310,25 +336,25 @@ void RestoreArchive(Archive* AHX, RestoreOptions *ropt) _disableTriggersIfNecessary(AH, NULL, ropt); te = AH->toc->next; - while (te != AH->toc) { + while (te != AH->toc) + { /* Is it table data? */ - if (strcmp(te->desc, "TABLE DATA") == 0) { + if (strcmp(te->desc, "TABLE DATA") == 0) + { ahlog(AH, 2, "Checking if we loaded %s\n", te->name); reqs = _tocEntryRequired(te, ropt); - if ( (reqs & 2) != 0) /* We loaded the data */ + if ((reqs & 2) != 0) /* We loaded the data */ { ahlog(AH, 1, "Fixing up BLOB ref for %s\n", te->name); FixupBlobRefs(AH, te->name); } } else - { ahlog(AH, 2, "Ignoring BLOB xrefs for %s %s\n", te->desc, te->name); - } te = te->next; } @@ -340,7 +366,7 @@ void RestoreArchive(Archive* AHX, RestoreOptions *ropt) /* * Clean up & we're done. */ - if (ropt->filename) + if (ropt->filename) ResetOutput(AH, sav); if (ropt->useDB) @@ -360,47 +386,53 @@ void RestoreArchive(Archive* AHX, RestoreOptions *ropt) * Allocate a new RestoreOptions block. * This is mainly so we can initialize it, but also for future expansion, */ -RestoreOptions* NewRestoreOptions(void) +RestoreOptions * +NewRestoreOptions(void) { - RestoreOptions* opts; + RestoreOptions *opts; - opts = (RestoreOptions*)calloc(1, sizeof(RestoreOptions)); + opts = (RestoreOptions *) calloc(1, sizeof(RestoreOptions)); opts->format = archUnknown; return opts; } -static int _restoringToDB(ArchiveHandle *AH) +static int +_restoringToDB(ArchiveHandle *AH) { return (AH->ropt->useDB && AH->connection); } -static int _canRestoreBlobs(ArchiveHandle *AH) +static int +_canRestoreBlobs(ArchiveHandle *AH) { return _restoringToDB(AH); } -static void _disableTriggersIfNecessary(ArchiveHandle *AH, TocEntry *te, RestoreOptions *ropt) +static void +_disableTriggersIfNecessary(ArchiveHandle *AH, TocEntry *te, RestoreOptions *ropt) { - char *oldUser = NULL; + char *oldUser = NULL; /* Can't do much if we're connected & don't have a superuser */ - /* Also, don't bother with triggers unless a data-only retore. */ - if ( !ropt->dataOnly || (_restoringToDB(AH) && !ropt->superuser) ) + /* Also, don't bother with triggers unless a data-only retore. */ + if (!ropt->dataOnly || (_restoringToDB(AH) && !ropt->superuser)) return; /* - * Reconnect as superuser if possible, since they are the only ones + * Reconnect as superuser if possible, since they are the only ones * who can update pg_class... */ if (ropt->superuser) { if (!_restoringToDB(AH) || !ConnectedUserIsSuperuser(AH)) { - /* If we're not allowing changes for ownership, then remember the user - * so we can change it back here. Otherwise, let _reconnectAsOwner - * do what it has to do. + + /* + * If we're not allowing changes for ownership, then remember + * the user so we can change it back here. Otherwise, let + * _reconnectAsOwner do what it has to do. */ if (ropt->noOwner) oldUser = strdup(ConnectedUser(AH)); @@ -411,24 +443,24 @@ static void _disableTriggersIfNecessary(ArchiveHandle *AH, TocEntry *te, Restore ahlog(AH, 1, "Disabling triggers\n"); /* - * Disable them. This is a hack. Needs to be done via an appropriate 'SET' - * command when one is available. + * Disable them. This is a hack. Needs to be done via an appropriate + * 'SET' command when one is available. */ - ahprintf(AH, "-- Disable triggers\n"); + ahprintf(AH, "-- Disable triggers\n"); /* * Just update the AFFECTED table, if known. */ if (te && te->name && strlen(te->name) > 0) - ahprintf(AH, "UPDATE \"pg_class\" SET \"reltriggers\" = 0 WHERE \"relname\" = '%s';\n\n", - te->name); + ahprintf(AH, "UPDATE \"pg_class\" SET \"reltriggers\" = 0 WHERE \"relname\" = '%s';\n\n", + te->name); else ahprintf(AH, "UPDATE \"pg_class\" SET \"reltriggers\" = 0 WHERE \"relname\" !~ '^pg_';\n\n"); /* - * Restore the user connection from the start of this procedure - * if _reconnectAsOwner is disabled. + * Restore the user connection from the start of this procedure if + * _reconnectAsOwner is disabled. */ if (ropt->noOwner && oldUser) { @@ -437,13 +469,14 @@ static void _disableTriggersIfNecessary(ArchiveHandle *AH, TocEntry *te, Restore } } -static void _enableTriggersIfNecessary(ArchiveHandle *AH, TocEntry *te, RestoreOptions *ropt) +static void +_enableTriggersIfNecessary(ArchiveHandle *AH, TocEntry *te, RestoreOptions *ropt) { - char *oldUser = NULL; + char *oldUser = NULL; /* Can't do much if we're connected & don't have a superuser */ /* Also, don't bother with triggers unless a data-only retore. */ - if ( !ropt->dataOnly || (_restoringToDB(AH) && !ropt->superuser) ) + if (!ropt->dataOnly || (_restoringToDB(AH) && !ropt->superuser)) return; /* @@ -454,9 +487,11 @@ static void _enableTriggersIfNecessary(ArchiveHandle *AH, TocEntry *te, RestoreO { if (!_restoringToDB(AH) || !ConnectedUserIsSuperuser(AH)) { - /* If we're not allowing changes for ownership, then remember the user - * so we can change it back here. Otherwise, let _reconnectAsOwner - * do what it has to do + + /* + * If we're not allowing changes for ownership, then remember + * the user so we can change it back here. Otherwise, let + * _reconnectAsOwner do what it has to do */ if (ropt->noOwner) oldUser = strdup(ConnectedUser(AH)); @@ -468,25 +503,27 @@ static void _enableTriggersIfNecessary(ArchiveHandle *AH, TocEntry *te, RestoreO ahlog(AH, 1, "Enabling triggers\n"); /* - * Enable them. This is a hack. Needs to be done via an appropriate 'SET' - * command when one is available. + * Enable them. This is a hack. Needs to be done via an appropriate + * 'SET' command when one is available. */ - ahprintf(AH, "-- Enable triggers\n"); + ahprintf(AH, "-- Enable triggers\n"); if (te && te->name && strlen(te->name) > 0) { ahprintf(AH, "UPDATE pg_class SET reltriggers = " - "(SELECT count(*) FROM pg_trigger where pg_class.oid = tgrelid) " + "(SELECT count(*) FROM pg_trigger where pg_class.oid = tgrelid) " "WHERE relname = '%s';\n\n", - te->name); - } else { + te->name); + } + else + { ahprintf(AH, "UPDATE \"pg_class\" SET \"reltriggers\" = " - "(SELECT count(*) FROM pg_trigger where pg_class.oid = tgrelid) " + "(SELECT count(*) FROM pg_trigger where pg_class.oid = tgrelid) " "WHERE \"relname\" !~ '^pg_';\n\n"); } /* - * Restore the user connection from the start of this procedure - * if _reconnectAsOwner is disabled. + * Restore the user connection from the start of this procedure if + * _reconnectAsOwner is disabled. */ if (ropt->noOwner && oldUser) { @@ -500,82 +537,88 @@ static void _enableTriggersIfNecessary(ArchiveHandle *AH, TocEntry *te, RestoreO */ /* Public */ -int WriteData(Archive* AHX, const void* data, int dLen) +int +WriteData(Archive *AHX, const void *data, int dLen) { - ArchiveHandle* AH = (ArchiveHandle*)AHX; + ArchiveHandle *AH = (ArchiveHandle *) AHX; if (!AH->currToc) die_horribly(AH, "%s: WriteData can not be called outside the context of " - "a DataDumper routine\n", progname); + "a DataDumper routine\n", progname); - return (*AH->WriteDataPtr)(AH, data, dLen); + return (*AH->WriteDataPtr) (AH, data, dLen); } /* - * Create a new TOC entry. The TOC was designed as a TOC, but is now the + * Create a new TOC entry. The TOC was designed as a TOC, but is now the * repository for all metadata. But the name has stuck. */ /* Public */ -void ArchiveEntry(Archive* AHX, const char* oid, const char* name, - const char* desc, const char* (deps[]), const char* defn, - const char* dropStmt, const char* copyStmt, const char* owner, - DataDumperPtr dumpFn, void* dumpArg) +void +ArchiveEntry(Archive *AHX, const char *oid, const char *name, + const char *desc, const char *(deps[]), const char *defn, + const char *dropStmt, const char *copyStmt, const char *owner, + DataDumperPtr dumpFn, void *dumpArg) { - ArchiveHandle* AH = (ArchiveHandle*)AHX; - TocEntry* newToc; - - AH->lastID++; - AH->tocCount++; - - newToc = (TocEntry*)calloc(1, sizeof(TocEntry)); - if (!newToc) - die_horribly(AH, "Archiver: unable to allocate memory for TOC entry\n"); - - newToc->prev = AH->toc->prev; - newToc->next = AH->toc; - AH->toc->prev->next = newToc; - AH->toc->prev = newToc; - - newToc->id = AH->lastID; - newToc->oid = strdup(oid); - newToc->oidVal = atoi(oid); - newToc->name = strdup(name); - newToc->desc = strdup(desc); - newToc->defn = strdup(defn); - newToc->dropStmt = strdup(dropStmt); + ArchiveHandle *AH = (ArchiveHandle *) AHX; + TocEntry *newToc; + + AH->lastID++; + AH->tocCount++; + + newToc = (TocEntry *) calloc(1, sizeof(TocEntry)); + if (!newToc) + die_horribly(AH, "Archiver: unable to allocate memory for TOC entry\n"); + + newToc->prev = AH->toc->prev; + newToc->next = AH->toc; + AH->toc->prev->next = newToc; + AH->toc->prev = newToc; + + newToc->id = AH->lastID; + newToc->oid = strdup(oid); + newToc->oidVal = atoi(oid); + newToc->name = strdup(name); + newToc->desc = strdup(desc); + newToc->defn = strdup(defn); + newToc->dropStmt = strdup(dropStmt); newToc->copyStmt = copyStmt ? strdup(copyStmt) : NULL; - newToc->owner = strdup(owner); - newToc->printed = 0; - newToc->formatData = NULL; - newToc->dataDumper = dumpFn, - newToc->dataDumperArg = dumpArg; + newToc->owner = strdup(owner); + newToc->printed = 0; + newToc->formatData = NULL; + newToc->dataDumper = dumpFn, + newToc->dataDumperArg = dumpArg; - newToc->hadDumper = dumpFn ? 1 : 0; + newToc->hadDumper = dumpFn ? 1 : 0; - if (AH->ArchiveEntryPtr != NULL) { - (*AH->ArchiveEntryPtr)(AH, newToc); - } + if (AH->ArchiveEntryPtr !=NULL) + (*AH->ArchiveEntryPtr) (AH, newToc); - /* printf("New toc owned by '%s', oid %d\n", newToc->owner, newToc->oidVal); */ + /* + * printf("New toc owned by '%s', oid %d\n", newToc->owner, + * newToc->oidVal); + */ } /* Public */ -void PrintTOCSummary(Archive* AHX, RestoreOptions *ropt) +void +PrintTOCSummary(Archive *AHX, RestoreOptions *ropt) { - ArchiveHandle* AH = (ArchiveHandle*) AHX; - TocEntry *te = AH->toc->next; - OutputContext sav; - char *fmtName; + ArchiveHandle *AH = (ArchiveHandle *) AHX; + TocEntry *te = AH->toc->next; + OutputContext sav; + char *fmtName; - if (ropt->filename) - sav = SetOutput(AH, ropt->filename, ropt->compression); + if (ropt->filename) + sav = SetOutput(AH, ropt->filename, ropt->compression); ahprintf(AH, ";\n; Archive created at %s", ctime(&AH->createDate)); ahprintf(AH, "; dbname: %s\n; TOC Entries: %d\n; Compression: %d\n", - AH->archdbname, AH->tocCount, AH->compression); + AH->archdbname, AH->tocCount, AH->compression); - switch (AH->format) { + switch (AH->format) + { case archFiles: fmtName = "FILES"; break; @@ -592,16 +635,17 @@ void PrintTOCSummary(Archive* AHX, RestoreOptions *ropt) ahprintf(AH, "; Dump Version: %d.%d-%d\n", AH->vmaj, AH->vmin, AH->vrev); ahprintf(AH, "; Format: %s\n;\n", fmtName); - ahprintf(AH, ";\n; Selected TOC Entries:\n;\n"); + ahprintf(AH, ";\n; Selected TOC Entries:\n;\n"); - while (te != AH->toc) { - if (_tocEntryRequired(te, ropt) != 0) - ahprintf(AH, "%d; %d %s %s %s\n", te->id, te->oidVal, te->desc, te->name, te->owner); + while (te != AH->toc) + { + if (_tocEntryRequired(te, ropt) != 0) + ahprintf(AH, "%d; %d %s %s %s\n", te->id, te->oidVal, te->desc, te->name, te->owner); te = te->next; - } + } - if (ropt->filename) - ResetOutput(AH, sav); + if (ropt->filename) + ResetOutput(AH, sav); } /*********** @@ -609,27 +653,29 @@ void PrintTOCSummary(Archive* AHX, RestoreOptions *ropt) ***********/ /* Called by a dumper to signal start of a BLOB */ -int StartBlob(Archive* AHX, int oid) +int +StartBlob(Archive *AHX, int oid) { - ArchiveHandle* AH = (ArchiveHandle*)AHX; + ArchiveHandle *AH = (ArchiveHandle *) AHX; - if (!AH->StartBlobPtr) + if (!AH->StartBlobPtr) die_horribly(AH, "%s: BLOB output not supported in chosen format\n", progname); - (*AH->StartBlobPtr)(AH, AH->currToc, oid); + (*AH->StartBlobPtr) (AH, AH->currToc, oid); - return 1; + return 1; } /* Called by a dumper to signal end of a BLOB */ -int EndBlob(Archive* AHX, int oid) +int +EndBlob(Archive *AHX, int oid) { - ArchiveHandle* AH = (ArchiveHandle*)AHX; + ArchiveHandle *AH = (ArchiveHandle *) AHX; - if (AH->EndBlobPtr) - (*AH->EndBlobPtr)(AH, AH->currToc, oid); + if (AH->EndBlobPtr) + (*AH->EndBlobPtr) (AH, AH->currToc, oid); - return 1; + return 1; } /********** @@ -637,17 +683,19 @@ int EndBlob(Archive* AHX, int oid) **********/ /* - * Called by a format handler before any blobs are restored + * Called by a format handler before any blobs are restored */ -void StartRestoreBlobs(ArchiveHandle* AH) +void +StartRestoreBlobs(ArchiveHandle *AH) { AH->blobCount = 0; } /* - * Called by a format handler after all blobs are restored + * Called by a format handler after all blobs are restored */ -void EndRestoreBlobs(ArchiveHandle* AH) +void +EndRestoreBlobs(ArchiveHandle *AH) { if (AH->txActive) { @@ -656,9 +704,7 @@ void EndRestoreBlobs(ArchiveHandle* AH) } if (AH->blobTxActive) - { CommitTransactionXref(AH); - } ahlog(AH, 1, "Restored %d BLOBs\n", AH->blobCount); } @@ -667,7 +713,8 @@ void EndRestoreBlobs(ArchiveHandle* AH) /* * Called by a format handler to initiate restoration of a blob */ -void StartRestoreBlob(ArchiveHandle* AH, int oid) +void +StartRestoreBlob(ArchiveHandle *AH, int oid) { int loOid; @@ -691,9 +738,7 @@ void StartRestoreBlob(ArchiveHandle* AH, int oid) StartTransaction(AH); } if (!AH->blobTxActive) - { StartTransactionXref(AH); - } loOid = lo_creat(AH->connection, INV_READ | INV_WRITE); if (loOid == 0) @@ -707,18 +752,19 @@ void StartRestoreBlob(ArchiveHandle* AH, int oid) if (AH->loFd == -1) die_horribly(AH, "%s: unable to open BLOB\n", progname); - AH->writingBlob = 1; + AH->writingBlob = 1; } -void EndRestoreBlob(ArchiveHandle* AH, int oid) +void +EndRestoreBlob(ArchiveHandle *AH, int oid) { - lo_close(AH->connection, AH->loFd); - AH->writingBlob = 0; + lo_close(AH->connection, AH->loFd); + AH->writingBlob = 0; /* * Commit every BLOB_BATCH_SIZE blobs... */ - if ( ((AH->blobCount / BLOB_BATCH_SIZE) * BLOB_BATCH_SIZE) == AH->blobCount) + if (((AH->blobCount / BLOB_BATCH_SIZE) * BLOB_BATCH_SIZE) == AH->blobCount) { ahlog(AH, 2, "Committing BLOB transactions\n"); CommitTransaction(AH); @@ -735,25 +781,27 @@ void EndRestoreBlob(ArchiveHandle* AH, int oid) */ /* Public */ -void MoveToStart(Archive* AHX, char *oType) +void +MoveToStart(Archive *AHX, char *oType) { - ArchiveHandle* AH = (ArchiveHandle*)AHX; - TocEntry *te = AH->toc->next; - TocEntry *newTe; + ArchiveHandle *AH = (ArchiveHandle *) AHX; + TocEntry *te = AH->toc->next; + TocEntry *newTe; - while (te != AH->toc) { + while (te != AH->toc) + { te->_moved = 0; te = te->next; - } - - te = AH->toc->prev; - while (te != AH->toc && !te->_moved) { - newTe = te->prev; - if (strcmp(te->desc, oType) == 0) { - _moveAfter(AH, AH->toc, te); } + + te = AH->toc->prev; + while (te != AH->toc && !te->_moved) + { + newTe = te->prev; + if (strcmp(te->desc, oType) == 0) + _moveAfter(AH, AH->toc, te); te = newTe; - } + } } @@ -761,116 +809,124 @@ void MoveToStart(Archive* AHX, char *oType) * Move TOC entries of the specified type to the end of the TOC. */ /* Public */ -void MoveToEnd(Archive* AHX, char *oType) +void +MoveToEnd(Archive *AHX, char *oType) { - ArchiveHandle* AH = (ArchiveHandle*)AHX; - TocEntry *te = AH->toc->next; - TocEntry *newTe; - - while (te != AH->toc) { - te->_moved = 0; - te = te->next; - } - - te = AH->toc->next; - while (te != AH->toc && !te->_moved) { - newTe = te->next; - if (strcmp(te->desc, oType) == 0) { - _moveBefore(AH, AH->toc, te); + ArchiveHandle *AH = (ArchiveHandle *) AHX; + TocEntry *te = AH->toc->next; + TocEntry *newTe; + + while (te != AH->toc) + { + te->_moved = 0; + te = te->next; } + + te = AH->toc->next; + while (te != AH->toc && !te->_moved) + { + newTe = te->next; + if (strcmp(te->desc, oType) == 0) + _moveBefore(AH, AH->toc, te); te = newTe; - } + } } -/* +/* * Sort TOC by OID */ /* Public */ -void SortTocByOID(Archive* AHX) +void +SortTocByOID(Archive *AHX) { - ArchiveHandle* AH = (ArchiveHandle*)AHX; - _SortToc(AH, _tocSortCompareByOIDNum); + ArchiveHandle *AH = (ArchiveHandle *) AHX; + + _SortToc(AH, _tocSortCompareByOIDNum); } /* * Sort TOC by ID */ /* Public */ -void SortTocByID(Archive* AHX) +void +SortTocByID(Archive *AHX) { - ArchiveHandle* AH = (ArchiveHandle*)AHX; - _SortToc(AH, _tocSortCompareByIDNum); + ArchiveHandle *AH = (ArchiveHandle *) AHX; + + _SortToc(AH, _tocSortCompareByIDNum); } -void SortTocFromFile(Archive* AHX, RestoreOptions *ropt) +void +SortTocFromFile(Archive *AHX, RestoreOptions *ropt) { - ArchiveHandle* AH = (ArchiveHandle*)AHX; - FILE *fh; - char buf[1024]; - char *cmnt; - char *endptr; - int id; - TocEntry *te; - TocEntry *tePrev; - int i; - - /* Allocate space for the 'wanted' array, and init it */ - ropt->idWanted = (int*)malloc(sizeof(int)*AH->tocCount); - for ( i = 0 ; i < AH->tocCount ; i++ ) - ropt->idWanted[i] = 0; - - ropt->limitToList = 1; - - /* Mark all entries as 'not moved' */ - te = AH->toc->next; - while (te != AH->toc) { - te->_moved = 0; - te = te->next; - } - - /* Set prev entry as head of list */ - tePrev = AH->toc; - - /* Setup the file */ - fh = fopen(ropt->tocFile, PG_BINARY_R); - if (!fh) - die_horribly(AH, "%s: could not open TOC file\n", progname); - - while (fgets(buf, 1024, fh) != NULL) - { - /* Find a comment */ - cmnt = strchr(buf, ';'); - if (cmnt == buf) - continue; + ArchiveHandle *AH = (ArchiveHandle *) AHX; + FILE *fh; + char buf[1024]; + char *cmnt; + char *endptr; + int id; + TocEntry *te; + TocEntry *tePrev; + int i; + + /* Allocate space for the 'wanted' array, and init it */ + ropt->idWanted = (int *) malloc(sizeof(int) * AH->tocCount); + for (i = 0; i < AH->tocCount; i++) + ropt->idWanted[i] = 0; + + ropt->limitToList = 1; + + /* Mark all entries as 'not moved' */ + te = AH->toc->next; + while (te != AH->toc) + { + te->_moved = 0; + te = te->next; + } - /* End string at comment */ - if (cmnt != NULL) - cmnt[0] = '\0'; + /* Set prev entry as head of list */ + tePrev = AH->toc; - /* Skip if all spaces */ - if (strspn(buf, " \t") == strlen(buf)) - continue; + /* Setup the file */ + fh = fopen(ropt->tocFile, PG_BINARY_R); + if (!fh) + die_horribly(AH, "%s: could not open TOC file\n", progname); - /* Get an ID */ - id = strtol(buf, &endptr, 10); - if (endptr == buf) + while (fgets(buf, 1024, fh) != NULL) { - fprintf(stderr, "%s: WARNING - line ignored: %s\n", progname, buf); - continue; - } + /* Find a comment */ + cmnt = strchr(buf, ';'); + if (cmnt == buf) + continue; + + /* End string at comment */ + if (cmnt != NULL) + cmnt[0] = '\0'; + + /* Skip if all spaces */ + if (strspn(buf, " \t") == strlen(buf)) + continue; + + /* Get an ID */ + id = strtol(buf, &endptr, 10); + if (endptr == buf) + { + fprintf(stderr, "%s: WARNING - line ignored: %s\n", progname, buf); + continue; + } - /* Find TOC entry */ - te = _getTocEntry(AH, id); - if (!te) - die_horribly(AH, "%s: could not find entry for id %d\n",progname, id); + /* Find TOC entry */ + te = _getTocEntry(AH, id); + if (!te) + die_horribly(AH, "%s: could not find entry for id %d\n", progname, id); - ropt->idWanted[id-1] = 1; + ropt->idWanted[id - 1] = 1; - _moveAfter(AH, tePrev, te); - tePrev = te; - } + _moveAfter(AH, tePrev, te); + tePrev = te; + } - if (fclose(fh) != 0) + if (fclose(fh) != 0) die_horribly(AH, "%s: could not close TOC file\n", progname); } @@ -880,41 +936,52 @@ void SortTocFromFile(Archive* AHX, RestoreOptions *ropt) **********************/ /* Public */ -int archputs(const char *s, Archive* AH) { - return WriteData(AH, s, strlen(s)); +int +archputs(const char *s, Archive *AH) +{ + return WriteData(AH, s, strlen(s)); } /* Public */ -int archputc(const char c, Archive* AH) { - return WriteData(AH, &c, 1); +int +archputc(const char c, Archive *AH) +{ + return WriteData(AH, &c, 1); } /* Public */ -int archprintf(Archive* AH, const char *fmt, ...) +int +archprintf(Archive *AH, const char *fmt,...) { - char *p = NULL; - va_list ap; - int bSize = strlen(fmt) + 256; - int cnt = -1; - - /* This is paranoid: deal with the possibility that vsnprintf is willing to ignore trailing null */ - /* or returns > 0 even if string does not fit. It may be the case that it returns cnt = bufsize */ - while (cnt < 0 || cnt >= (bSize-1) ) + char *p = NULL; + va_list ap; + int bSize = strlen(fmt) + 256; + int cnt = -1; + + /* + * This is paranoid: deal with the possibility that vsnprintf is + * willing to ignore trailing null + */ + + /* + * or returns > 0 even if string does not fit. It may be the case that + * it returns cnt = bufsize + */ + while (cnt < 0 || cnt >= (bSize - 1)) { - if (p != NULL) free(p); + if (p != NULL) + free(p); bSize *= 2; - p = (char*)malloc(bSize); + p = (char *) malloc(bSize); if (p == NULL) - { exit_horribly(AH, "%s: could not allocate buffer for archprintf\n", progname); - } va_start(ap, fmt); cnt = vsnprintf(p, bSize, fmt, ap); va_end(ap); - } - WriteData(AH, p, cnt); - free(p); - return cnt; + } + WriteData(AH, p, cnt); + free(p); + return cnt; } @@ -922,107 +989,123 @@ int archprintf(Archive* AH, const char *fmt, ...) * Stuff below here should be 'private' to the archiver routines *******************************/ -OutputContext SetOutput(ArchiveHandle* AH, char *filename, int compression) +OutputContext +SetOutput(ArchiveHandle *AH, char *filename, int compression) { - OutputContext sav; + OutputContext sav; + #ifdef HAVE_LIBZ - char fmode[10]; + char fmode[10]; + #endif - int fn = 0; - - /* Replace the AH output file handle */ - sav.OF = AH->OF; - sav.gzOut = AH->gzOut; - - if (filename) { - fn = 0; - } else if (AH->FH) { - fn = fileno(AH->FH); - } else if (AH->fSpec) { - fn = 0; - filename = AH->fSpec; - } else { - fn = fileno(stdout); - } - - /* If compression explicitly requested, use gzopen */ + int fn = 0; + + /* Replace the AH output file handle */ + sav.OF = AH->OF; + sav.gzOut = AH->gzOut; + + if (filename) + fn = 0; + else if (AH->FH) + fn = fileno(AH->FH); + else if (AH->fSpec) + { + fn = 0; + filename = AH->fSpec; + } + else + fn = fileno(stdout); + + /* If compression explicitly requested, use gzopen */ #ifdef HAVE_LIBZ - if (compression != 0) - { + if (compression != 0) + { sprintf(fmode, "wb%d", compression); - if (fn) { - AH->OF = gzdopen(dup(fn), fmode); /* Don't use PG_BINARY_x since this is zlib */ - } else { - AH->OF = gzopen(filename, fmode); + if (fn) + { + AH->OF = gzdopen(dup(fn), fmode); /* Don't use PG_BINARY_x + * since this is zlib */ } + else + AH->OF = gzopen(filename, fmode); AH->gzOut = 1; - } else { /* Use fopen */ + } + else + { /* Use fopen */ #endif - if (fn) { + if (fn) AH->OF = fdopen(dup(fn), PG_BINARY_W); - } else { + else AH->OF = fopen(filename, PG_BINARY_W); - } AH->gzOut = 0; #ifdef HAVE_LIBZ - } + } #endif if (!AH->OF) die_horribly(AH, "%s: could not set output\n", progname); - return sav; + return sav; } -void ResetOutput(ArchiveHandle* AH, OutputContext sav) +void +ResetOutput(ArchiveHandle *AH, OutputContext sav) { - int res; + int res; - if (AH->gzOut) + if (AH->gzOut) res = GZCLOSE(AH->OF); - else + else res = fclose(AH->OF); if (res != 0) die_horribly(AH, "%s: could not reset the output file\n", progname); - AH->gzOut = sav.gzOut; - AH->OF = sav.OF; + AH->gzOut = sav.gzOut; + AH->OF = sav.OF; } /* - * Print formatted text to the output file (usually stdout). + * Print formatted text to the output file (usually stdout). */ -int ahprintf(ArchiveHandle* AH, const char *fmt, ...) +int +ahprintf(ArchiveHandle *AH, const char *fmt,...) { - char *p = NULL; - va_list ap; - int bSize = strlen(fmt) + 256; /* Should be enough */ - int cnt = -1; - - /* This is paranoid: deal with the possibility that vsnprintf is willing to ignore trailing null */ - /* or returns > 0 even if string does not fit. It may be the case that it returns cnt = bufsize */ - while (cnt < 0 || cnt >= (bSize - 1) ) + char *p = NULL; + va_list ap; + int bSize = strlen(fmt) + 256; /* Should be enough */ + int cnt = -1; + + /* + * This is paranoid: deal with the possibility that vsnprintf is + * willing to ignore trailing null + */ + + /* + * or returns > 0 even if string does not fit. It may be the case that + * it returns cnt = bufsize + */ + while (cnt < 0 || cnt >= (bSize - 1)) { - if (p != NULL) free(p); + if (p != NULL) + free(p); bSize *= 2; - p = (char*)malloc(bSize); + p = (char *) malloc(bSize); if (p == NULL) - { die_horribly(AH, "%s: could not allocate buffer for ahprintf\n", progname); - } va_start(ap, fmt); cnt = vsnprintf(p, bSize, fmt, ap); va_end(ap); - } - ahwrite(p, 1, cnt, AH); - free(p); - return cnt; + } + ahwrite(p, 1, cnt, AH); + free(p); + return cnt; } -void ahlog(ArchiveHandle* AH, int level, const char *fmt, ...) +void +ahlog(ArchiveHandle *AH, int level, const char *fmt,...) { va_list ap; @@ -1037,244 +1120,265 @@ void ahlog(ArchiveHandle* AH, int level, const char *fmt, ...) /* * Single place for logic which says 'We are restoring to a direct DB connection'. */ -int RestoringToDB(ArchiveHandle* AH) +int +RestoringToDB(ArchiveHandle *AH) { return (AH->ropt && AH->ropt->useDB && AH->connection); } /* - * Write buffer to the output file (usually stdout). This is user for - * outputting 'restore' scripts etc. It is even possible for an archive - * format to create a custom output routine to 'fake' a restore if it + * Write buffer to the output file (usually stdout). This is user for + * outputting 'restore' scripts etc. It is even possible for an archive + * format to create a custom output routine to 'fake' a restore if it * wants to generate a script (see TAR output). */ -int ahwrite(const void *ptr, size_t size, size_t nmemb, ArchiveHandle* AH) +int +ahwrite(const void *ptr, size_t size, size_t nmemb, ArchiveHandle *AH) { - int res; + int res; - if (AH->writingBlob) + if (AH->writingBlob) { - res = lo_write(AH->connection, AH->loFd, (void*)ptr, size * nmemb); + res = lo_write(AH->connection, AH->loFd, (void *) ptr, size * nmemb); ahlog(AH, 5, "Wrote %d bytes of BLOB data (result = %d)\n", size * nmemb, res); if (res < size * nmemb) - die_horribly(AH, "%s: could not write to large object (result = %d, expected %d)\n", - progname, res, size * nmemb); + die_horribly(AH, "%s: could not write to large object (result = %d, expected %d)\n", + progname, res, size * nmemb); return res; } - else if (AH->gzOut) + else if (AH->gzOut) { - res = GZWRITE((void*)ptr, size, nmemb, AH->OF); + res = GZWRITE((void *) ptr, size, nmemb, AH->OF); if (res != (nmemb * size)) die_horribly(AH, "%s: could not write to archive\n", progname); return res; } - else if (AH->CustomOutPtr) + else if (AH->CustomOutPtr) { - res = AH->CustomOutPtr(AH, ptr, size * nmemb); + res = AH->CustomOutPtr (AH, ptr, size * nmemb); + if (res != (nmemb * size)) die_horribly(AH, "%s: could not write to custom output routine\n", progname); return res; } else { + /* - * If we're doing a restore, and it's direct to DB, and we're connected - * then send it to the DB. - */ + * If we're doing a restore, and it's direct to DB, and we're + * connected then send it to the DB. + */ if (RestoringToDB(AH)) - return ExecuteSqlCommandBuf(AH, (void*)ptr, size*nmemb); /* Always 1, currently */ + return ExecuteSqlCommandBuf(AH, (void *) ptr, size * nmemb); /* Always 1, currently */ else { - res = fwrite((void*)ptr, size, nmemb, AH->OF); + res = fwrite((void *) ptr, size, nmemb, AH->OF); if (res != nmemb) die_horribly(AH, "%s: could not write to output file (%d != %d)\n", progname, res, nmemb); return res; } } -} +} /* Common exit code */ -static void _die_horribly(ArchiveHandle *AH, const char *fmt, va_list ap) +static void +_die_horribly(ArchiveHandle *AH, const char *fmt, va_list ap) { - vfprintf(stderr, fmt, ap); + vfprintf(stderr, fmt, ap); - if (AH) - if (AH->connection) - PQfinish(AH->connection); + if (AH) + if (AH->connection) + PQfinish(AH->connection); if (AH->blobConnection) PQfinish(AH->blobConnection); - exit(1); + exit(1); } /* External use */ -void exit_horribly(Archive *AH, const char *fmt, ...) +void +exit_horribly(Archive *AH, const char *fmt,...) { - va_list ap; + va_list ap; - va_start(ap, fmt); - _die_horribly((ArchiveHandle*)AH, fmt, ap); + va_start(ap, fmt); + _die_horribly((ArchiveHandle *) AH, fmt, ap); } /* Archiver use (just different arg declaration) */ -void die_horribly(ArchiveHandle *AH, const char *fmt, ...) +void +die_horribly(ArchiveHandle *AH, const char *fmt,...) { - va_list ap; + va_list ap; - va_start(ap, fmt); - _die_horribly(AH, fmt, ap); + va_start(ap, fmt); + _die_horribly(AH, fmt, ap); } -static void _moveAfter(ArchiveHandle* AH, TocEntry* pos, TocEntry* te) +static void +_moveAfter(ArchiveHandle *AH, TocEntry *pos, TocEntry *te) { - te->prev->next = te->next; - te->next->prev = te->prev; + te->prev->next = te->next; + te->next->prev = te->prev; - te->prev = pos; - te->next = pos->next; + te->prev = pos; + te->next = pos->next; - pos->next->prev = te; - pos->next = te; + pos->next->prev = te; + pos->next = te; - te->_moved = 1; + te->_moved = 1; } -static void _moveBefore(ArchiveHandle* AH, TocEntry* pos, TocEntry* te) +static void +_moveBefore(ArchiveHandle *AH, TocEntry *pos, TocEntry *te) { - te->prev->next = te->next; - te->next->prev = te->prev; + te->prev->next = te->next; + te->next->prev = te->prev; - te->prev = pos->prev; - te->next = pos; - pos->prev->next = te; - pos->prev = te; + te->prev = pos->prev; + te->next = pos; + pos->prev->next = te; + pos->prev = te; - te->_moved = 1; + te->_moved = 1; } -static TocEntry* _getTocEntry(ArchiveHandle* AH, int id) +static TocEntry * +_getTocEntry(ArchiveHandle *AH, int id) { - TocEntry *te; - - te = AH->toc->next; - while (te != AH->toc) { - if (te->id == id) - return te; - te = te->next; - } - return NULL; + TocEntry *te; + + te = AH->toc->next; + while (te != AH->toc) + { + if (te->id == id) + return te; + te = te->next; + } + return NULL; } -int TocIDRequired(ArchiveHandle* AH, int id, RestoreOptions *ropt) +int +TocIDRequired(ArchiveHandle *AH, int id, RestoreOptions *ropt) { - TocEntry *te = _getTocEntry(AH, id); + TocEntry *te = _getTocEntry(AH, id); - if (!te) - return 0; + if (!te) + return 0; - return _tocEntryRequired(te, ropt); + return _tocEntryRequired(te, ropt); } -int WriteInt(ArchiveHandle* AH, int i) +int +WriteInt(ArchiveHandle *AH, int i) { - int b; - - /* This is a bit yucky, but I don't want to make the - * binary format very dependant on representation, - * and not knowing much about it, I write out a - * sign byte. If you change this, don't forget to change the - * file version #, and modify readInt to read the new format - * AS WELL AS the old formats. - */ - - /* SIGN byte */ - if (i < 0) { - (*AH->WriteBytePtr)(AH, 1); + int b; + + /* + * This is a bit yucky, but I don't want to make the binary format + * very dependant on representation, and not knowing much about it, I + * write out a sign byte. If you change this, don't forget to change + * the file version #, and modify readInt to read the new format AS + * WELL AS the old formats. + */ + + /* SIGN byte */ + if (i < 0) + { + (*AH->WriteBytePtr) (AH, 1); i = -i; - } else { - (*AH->WriteBytePtr)(AH, 0); - } - - for(b = 0 ; b < AH->intSize ; b++) { - (*AH->WriteBytePtr)(AH, i & 0xFF); - i = i / 256; - } - - return AH->intSize + 1; + } + else + (*AH->WriteBytePtr) (AH, 0); + + for (b = 0; b < AH->intSize; b++) + { + (*AH->WriteBytePtr) (AH, i & 0xFF); + i = i / 256; + } + + return AH->intSize + 1; } -int ReadInt(ArchiveHandle* AH) +int +ReadInt(ArchiveHandle *AH) { - int res = 0; - int bv, b; - int sign = 0; /* Default positive */ - int bitShift = 0; + int res = 0; + int bv, + b; + int sign = 0; /* Default positive */ + int bitShift = 0; - if (AH->version > K_VERS_1_0) + if (AH->version > K_VERS_1_0) /* Read a sign byte */ - sign = (*AH->ReadBytePtr)(AH); + sign = (*AH->ReadBytePtr) (AH); - for( b = 0 ; b < AH->intSize ; b++) { - bv = (*AH->ReadBytePtr)(AH) & 0xFF; + for (b = 0; b < AH->intSize; b++) + { + bv = (*AH->ReadBytePtr) (AH) & 0xFF; if (bv != 0) res = res + (bv << bitShift); bitShift += 8; - } + } - if (sign) - res = - res; + if (sign) + res = -res; - return res; + return res; } -int WriteStr(ArchiveHandle* AH, char* c) +int +WriteStr(ArchiveHandle *AH, char *c) { - int res; + int res; if (c) { res = WriteInt(AH, strlen(c)); - res += (*AH->WriteBufPtr)(AH, c, strlen(c)); + res += (*AH->WriteBufPtr) (AH, c, strlen(c)); } else res = WriteInt(AH, -1); - return res; + return res; } -char* ReadStr(ArchiveHandle* AH) +char * +ReadStr(ArchiveHandle *AH) { - char* buf; - int l; + char *buf; + int l; - l = ReadInt(AH); + l = ReadInt(AH); if (l == -1) buf = NULL; else { - buf = (char*)malloc(l+1); + buf = (char *) malloc(l + 1); if (!buf) - die_horribly(AH, "%s: Unable to allocate sufficient memory in ReadStr - " "requested %d (0x%x) bytes\n", progname, l, l); + die_horribly(AH, "%s: Unable to allocate sufficient memory in ReadStr - " "requested %d (0x%x) bytes\n", progname, l, l); - (*AH->ReadBufPtr)(AH, (void*)buf, l); + (*AH->ReadBufPtr) (AH, (void *) buf, l); buf[l] = '\0'; } - return buf; + return buf; } static int -_discoverArchiveFormat(ArchiveHandle* AH) +_discoverArchiveFormat(ArchiveHandle *AH) { - FILE *fh; - char sig[6]; /* More than enough */ - int cnt; - int wantClose = 0; + FILE *fh; + char sig[6]; /* More than enough */ + int cnt; + int wantClose = 0; /* - * fprintf(stderr, "%s: Attempting to ascertain archive format\n", progname); + * fprintf(stderr, "%s: Attempting to ascertain archive format\n", + * progname); */ if (AH->lookahead) @@ -1285,26 +1389,27 @@ _discoverArchiveFormat(ArchiveHandle* AH) AH->lookaheadLen = 0; AH->lookaheadPos = 0; - if (AH->fSpec) { + if (AH->fSpec) + { wantClose = 1; fh = fopen(AH->fSpec, PG_BINARY_R); - } else { + } + else fh = stdin; - } - if (!fh) + if (!fh) die_horribly(AH, "Archiver: could not open input file\n"); - cnt = fread(sig, 1, 5, fh); + cnt = fread(sig, 1, 5, fh); - if (cnt != 5) - die_horribly(AH, "%s: input file is too short, or is unreadable\n", progname); + if (cnt != 5) + die_horribly(AH, "%s: input file is too short, or is unreadable\n", progname); - /* Save it, just in case we need it later*/ + /* Save it, just in case we need it later */ strncpy(&AH->lookahead[0], sig, 5); AH->lookaheadLen = 5; - if (strncmp(sig, "PGDMP", 5) == 0) + if (strncmp(sig, "PGDMP", 5) == 0) { AH->vmaj = fgetc(fh); AH->vmin = fgetc(fh); @@ -1314,8 +1419,8 @@ _discoverArchiveFormat(ArchiveHandle* AH) AH->lookahead[AH->lookaheadLen++] = AH->vmin; /* Check header version; varies from V1.0 */ - if (AH->vmaj > 1 || ( (AH->vmaj == 1) && (AH->vmin > 0) ) ) /* Version > 1.0 */ - { + if (AH->vmaj > 1 || ((AH->vmaj == 1) && (AH->vmin > 0))) /* Version > 1.0 */ + { AH->vrev = fgetc(fh); AH->lookahead[AH->lookaheadLen++] = AH->vrev; } @@ -1329,18 +1434,21 @@ _discoverArchiveFormat(ArchiveHandle* AH) AH->lookahead[AH->lookaheadLen++] = AH->format; /* Make a convenient integer <maj><min><rev>00 */ - AH->version = ( (AH->vmaj * 256 + AH->vmin) * 256 + AH->vrev ) * 256 + 0; - } else { + AH->version = ((AH->vmaj * 256 + AH->vmin) * 256 + AH->vrev) * 256 + 0; + } + else + { + /* - * *Maybe* we have a tar archive format file... - * So, read first 512 byte header... + * *Maybe* we have a tar archive format file... So, read first 512 + * byte header... */ cnt = fread(&AH->lookahead[AH->lookaheadLen], 1, 512 - AH->lookaheadLen, fh); AH->lookaheadLen += cnt; if (AH->lookaheadLen != 512) die_horribly(AH, "%s: input file does not appear to be a valid archive (too short?)\n", - progname); + progname); if (!isValidTarHeader(AH->lookahead)) die_horribly(AH, "%s: input file does not appear to be a valid archive\n", progname); @@ -1348,96 +1456,104 @@ _discoverArchiveFormat(ArchiveHandle* AH) AH->format = archTar; } - /* If we can't seek, then mark the header as read */ - if (fseek(fh, 0, SEEK_SET) != 0) + /* If we can't seek, then mark the header as read */ + if (fseek(fh, 0, SEEK_SET) != 0) { + /* - * NOTE: Formats that use the looahead buffer can unset this in their Init routine. + * NOTE: Formats that use the looahead buffer can unset this in + * their Init routine. */ AH->readHeader = 1; } else - AH->lookaheadLen = 0; /* Don't bother since we've reset the file */ + AH->lookaheadLen = 0; /* Don't bother since we've reset the file */ /* - *fprintf(stderr, "%s: read %d bytes into lookahead buffer\n", progname, AH->lookaheadLen); + * fprintf(stderr, "%s: read %d bytes into lookahead buffer\n", + * progname, AH->lookaheadLen); */ - /* Close the file */ - if (wantClose) + /* Close the file */ + if (wantClose) if (fclose(fh) != 0) die_horribly(AH, "%s: could not close the input file after reading header\n", progname); - return AH->format; + return AH->format; } /* * Allocate an archive handle */ -static ArchiveHandle* _allocAH(const char* FileSpec, const ArchiveFormat fmt, - const int compression, ArchiveMode mode) +static ArchiveHandle * +_allocAH(const char *FileSpec, const ArchiveFormat fmt, + const int compression, ArchiveMode mode) { - ArchiveHandle* AH; + ArchiveHandle *AH; /* - *fprintf(stderr, "%s: allocating AH for %s, format %d\n", progname, FileSpec, fmt); + * fprintf(stderr, "%s: allocating AH for %s, format %d\n", progname, + * FileSpec, fmt); */ - AH = (ArchiveHandle*)calloc(1, sizeof(ArchiveHandle)); - if (!AH) + AH = (ArchiveHandle *) calloc(1, sizeof(ArchiveHandle)); + if (!AH) die_horribly(AH, "Archiver: Could not allocate archive handle\n"); - AH->vmaj = K_VERS_MAJOR; - AH->vmin = K_VERS_MINOR; + AH->vmaj = K_VERS_MAJOR; + AH->vmin = K_VERS_MINOR; AH->vrev = K_VERS_REV; AH->createDate = time(NULL); - AH->intSize = sizeof(int); - AH->lastID = 0; - if (FileSpec) { + AH->intSize = sizeof(int); + AH->lastID = 0; + if (FileSpec) + { AH->fSpec = strdup(FileSpec); + /* * Not used; maybe later.... * - * AH->workDir = strdup(FileSpec); - * for(i=strlen(FileSpec) ; i > 0 ; i--) - * if (AH->workDir[i-1] == '/') + * AH->workDir = strdup(FileSpec); for(i=strlen(FileSpec) ; i > 0 ; + * i--) if (AH->workDir[i-1] == '/') */ - } else { + } + else AH->fSpec = NULL; - } - AH->currUser = strdup(""); /* So it's valid, but we can free() it later if necessary */ + AH->currUser = strdup(""); /* So it's valid, but we can free() it + * later if necessary */ - AH->toc = (TocEntry*)calloc(1, sizeof(TocEntry)); - if (!AH->toc) + AH->toc = (TocEntry *) calloc(1, sizeof(TocEntry)); + if (!AH->toc) die_horribly(AH, "Archiver: Could not allocate TOC header\n"); - AH->toc->next = AH->toc; - AH->toc->prev = AH->toc; - - AH->mode = mode; - AH->compression = compression; + AH->toc->next = AH->toc; + AH->toc->prev = AH->toc; + + AH->mode = mode; + AH->compression = compression; AH->pgCopyBuf = createPQExpBuffer(); AH->sqlBuf = createPQExpBuffer(); - /* Open stdout with no compression for AH output handle */ - AH->gzOut = 0; - AH->OF = stdout; + /* Open stdout with no compression for AH output handle */ + AH->gzOut = 0; + AH->OF = stdout; /* - *fprintf(stderr, "%s: archive format is %d\n", progname, fmt); + * fprintf(stderr, "%s: archive format is %d\n", progname, fmt); */ - if (fmt == archUnknown) + if (fmt == archUnknown) AH->format = _discoverArchiveFormat(AH); else AH->format = fmt; - switch (AH->format) { + switch (AH->format) + { case archCustom: InitArchiveFmt_Custom(AH); @@ -1457,86 +1573,97 @@ static ArchiveHandle* _allocAH(const char* FileSpec, const ArchiveFormat fmt, default: die_horribly(AH, "Archiver: Unrecognized file format '%d'\n", fmt); - } + } - return AH; + return AH; } -void WriteDataChunks(ArchiveHandle* AH) +void +WriteDataChunks(ArchiveHandle *AH) { - TocEntry *te = AH->toc->next; - StartDataPtr startPtr; - EndDataPtr endPtr; + TocEntry *te = AH->toc->next; + StartDataPtr startPtr; + EndDataPtr endPtr; - while (te != AH->toc) { - if (te->dataDumper != NULL) { - AH->currToc = te; - /* printf("Writing data for %d (%x)\n", te->id, te); */ - - if (strcmp(te->desc, "BLOBS") == 0) + while (te != AH->toc) + { + if (te->dataDumper != NULL) { - startPtr = AH->StartBlobsPtr; - endPtr = AH->EndBlobsPtr; - } else { - startPtr = AH->StartDataPtr; - endPtr = AH->EndDataPtr; - } + AH->currToc = te; + /* printf("Writing data for %d (%x)\n", te->id, te); */ - if (startPtr != NULL) { - (*startPtr)(AH, te); - } + if (strcmp(te->desc, "BLOBS") == 0) + { + startPtr = AH->StartBlobsPtr; + endPtr = AH->EndBlobsPtr; + } + else + { + startPtr = AH->StartDataPtr; + endPtr = AH->EndDataPtr; + } - /* printf("Dumper arg for %d is %x\n", te->id, te->dataDumperArg); */ - /* - * The user-provided DataDumper routine needs to call AH->WriteData - */ - (*te->dataDumper)((Archive*)AH, te->oid, te->dataDumperArg); + if (startPtr != NULL) + (*startPtr) (AH, te); - if (endPtr != NULL) { - (*endPtr)(AH, te); - } - AH->currToc = NULL; - } + /* + * printf("Dumper arg for %d is %x\n", te->id, + * te->dataDumperArg); + */ + + /* + * The user-provided DataDumper routine needs to call + * AH->WriteData + */ + (*te->dataDumper) ((Archive *) AH, te->oid, te->dataDumperArg); + + if (endPtr != NULL) + (*endPtr) (AH, te); + AH->currToc = NULL; + } te = te->next; - } + } } -void WriteToc(ArchiveHandle* AH) +void +WriteToc(ArchiveHandle *AH) { - TocEntry *te = AH->toc->next; - - /* printf("%d TOC Entries to save\n", AH->tocCount); */ - - WriteInt(AH, AH->tocCount); - while (te != AH->toc) { - WriteInt(AH, te->id); - WriteInt(AH, te->dataDumper ? 1 : 0); - WriteStr(AH, te->oid); - WriteStr(AH, te->name); - WriteStr(AH, te->desc); - WriteStr(AH, te->defn); - WriteStr(AH, te->dropStmt); - WriteStr(AH, te->copyStmt); - WriteStr(AH, te->owner); - if (AH->WriteExtraTocPtr) { - (*AH->WriteExtraTocPtr)(AH, te); - } + TocEntry *te = AH->toc->next; + + /* printf("%d TOC Entries to save\n", AH->tocCount); */ + + WriteInt(AH, AH->tocCount); + while (te != AH->toc) + { + WriteInt(AH, te->id); + WriteInt(AH, te->dataDumper ? 1 : 0); + WriteStr(AH, te->oid); + WriteStr(AH, te->name); + WriteStr(AH, te->desc); + WriteStr(AH, te->defn); + WriteStr(AH, te->dropStmt); + WriteStr(AH, te->copyStmt); + WriteStr(AH, te->owner); + if (AH->WriteExtraTocPtr) + (*AH->WriteExtraTocPtr) (AH, te); te = te->next; - } + } } -void ReadToc(ArchiveHandle* AH) +void +ReadToc(ArchiveHandle *AH) { - int i; + int i; - TocEntry *te = AH->toc->next; + TocEntry *te = AH->toc->next; - AH->tocCount = ReadInt(AH); + AH->tocCount = ReadInt(AH); - for( i = 0 ; i < AH->tocCount ; i++) { + for (i = 0; i < AH->tocCount; i++) + { - te = (TocEntry*)calloc(1, sizeof(TocEntry)); + te = (TocEntry *) calloc(1, sizeof(TocEntry)); te->id = ReadInt(AH); /* Sanity check */ @@ -1556,9 +1683,8 @@ void ReadToc(ArchiveHandle* AH) te->owner = ReadStr(AH); - if (AH->ReadExtraTocPtr) { - (*AH->ReadExtraTocPtr)(AH, te); - } + if (AH->ReadExtraTocPtr) + (*AH->ReadExtraTocPtr) (AH, te); ahlog(AH, 3, "Read TOC entry %d (id %d) for %s %s\n", i, te->id, te->desc, te->name); @@ -1566,102 +1692,105 @@ void ReadToc(ArchiveHandle* AH) AH->toc->prev->next = te; AH->toc->prev = te; te->next = AH->toc; - } + } } -static int _tocEntryRequired(TocEntry* te, RestoreOptions *ropt) +static int +_tocEntryRequired(TocEntry *te, RestoreOptions *ropt) { - int res = 3; /* Schema = 1, Data = 2, Both = 3 */ - - /* If it's an ACL, maybe ignore it */ - if (ropt->aclsSkip && strcmp(te->desc,"ACL") == 0) + int res = 3; /* Schema = 1, Data = 2, Both = 3 */ + + /* If it's an ACL, maybe ignore it */ + if (ropt->aclsSkip && strcmp(te->desc, "ACL") == 0) return 0; - if (!ropt->create && strcmp(te->desc,"DATABASE") == 0) + if (!ropt->create && strcmp(te->desc, "DATABASE") == 0) return 0; - /* Check if tablename only is wanted */ - if (ropt->selTypes) - { - if ( (strcmp(te->desc, "TABLE") == 0) || (strcmp(te->desc, "TABLE DATA") == 0) ) + /* Check if tablename only is wanted */ + if (ropt->selTypes) + { + if ((strcmp(te->desc, "TABLE") == 0) || (strcmp(te->desc, "TABLE DATA") == 0)) { if (!ropt->selTable) return 0; if (ropt->tableNames && strcmp(ropt->tableNames, te->name) != 0) return 0; - } else if (strcmp(te->desc, "INDEX") == 0) { + } + else if (strcmp(te->desc, "INDEX") == 0) + { if (!ropt->selIndex) return 0; if (ropt->indexNames && strcmp(ropt->indexNames, te->name) != 0) return 0; - } else if (strcmp(te->desc, "FUNCTION") == 0) { + } + else if (strcmp(te->desc, "FUNCTION") == 0) + { if (!ropt->selFunction) return 0; if (ropt->functionNames && strcmp(ropt->functionNames, te->name) != 0) return 0; - } else if (strcmp(te->desc, "TRIGGER") == 0) { + } + else if (strcmp(te->desc, "TRIGGER") == 0) + { if (!ropt->selTrigger) return 0; if (ropt->triggerNames && strcmp(ropt->triggerNames, te->name) != 0) return 0; - } else { - return 0; } + else + return 0; } /* Special Case: If 'SEQUENCE SET' and schemaOnly, then not needed */ - if (ropt->schemaOnly && (strcmp(te->desc, "SEQUENCE SET") == 0) ) + if (ropt->schemaOnly && (strcmp(te->desc, "SEQUENCE SET") == 0)) return 0; - /* Mask it if we only want schema */ - if (ropt->schemaOnly) + /* Mask it if we only want schema */ + if (ropt->schemaOnly) res = res & 1; - /* Mask it we only want data */ - if (ropt->dataOnly && (strcmp(te->desc, "SEQUENCE SET") != 0) ) - res = res & 2; + /* Mask it we only want data */ + if (ropt->dataOnly && (strcmp(te->desc, "SEQUENCE SET") != 0)) + res = res & 2; - /* Mask it if we don't have a schema contribition */ - if (!te->defn || strlen(te->defn) == 0) + /* Mask it if we don't have a schema contribition */ + if (!te->defn || strlen(te->defn) == 0) res = res & 2; - /* Mask it if we don't have a possible data contribition */ - if (!te->hadDumper) + /* Mask it if we don't have a possible data contribition */ + if (!te->hadDumper) res = res & 1; - /* Finally, if we used a list, limit based on that as well */ - if (ropt->limitToList && !ropt->idWanted[te->id - 1]) + /* Finally, if we used a list, limit based on that as well */ + if (ropt->limitToList && !ropt->idWanted[te->id - 1]) return 0; - return res; + return res; } -static void _reconnectAsUser(ArchiveHandle* AH, const char *dbname, char *user) +static void +_reconnectAsUser(ArchiveHandle *AH, const char *dbname, char *user) { if (AH->ropt && AH->ropt->noReconnect) return; if (user && strlen(user) != 0 - && ( (strcmp(AH->currUser, user) != 0) || (strcmp(dbname,"-") != 0))) + && ((strcmp(AH->currUser, user) != 0) || (strcmp(dbname, "-") != 0))) { if (RestoringToDB(AH)) - { ReconnectDatabase(AH, dbname, user); - } else - { ahprintf(AH, "\\connect %s %s\n", dbname, user); - } - if (AH->currUser) - { + if (AH->currUser) free(AH->currUser); - } AH->currUser = strdup(user); - } + } } -static void _reconnectAsOwner(ArchiveHandle* AH, const char *dbname, TocEntry* te) +static void +_reconnectAsOwner(ArchiveHandle *AH, const char *dbname, TocEntry *te) { if (AH->ropt && AH->ropt->noOwner) return; @@ -1669,37 +1798,38 @@ static void _reconnectAsOwner(ArchiveHandle* AH, const char *dbname, TocEntry* t _reconnectAsUser(AH, dbname, te->owner); } -static int _printTocEntry(ArchiveHandle* AH, TocEntry* te, RestoreOptions *ropt) +static int +_printTocEntry(ArchiveHandle *AH, TocEntry *te, RestoreOptions *ropt) { - ahprintf(AH, "--\n-- TOC Entry ID %d (OID %s)\n--\n-- Name: %s Type: %s Owner: %s\n", - te->id, te->oid, te->name, te->desc, te->owner); - if (AH->PrintExtraTocPtr != NULL) { - (*AH->PrintExtraTocPtr)(AH, te); - } - ahprintf(AH, "--\n\n"); + ahprintf(AH, "--\n-- TOC Entry ID %d (OID %s)\n--\n-- Name: %s Type: %s Owner: %s\n", + te->id, te->oid, te->name, te->desc, te->owner); + if (AH->PrintExtraTocPtr !=NULL) + (*AH->PrintExtraTocPtr) (AH, te); + ahprintf(AH, "--\n\n"); ahprintf(AH, "%s\n", te->defn); - return 1; + return 1; } -void WriteHead(ArchiveHandle* AH) +void +WriteHead(ArchiveHandle *AH) { - struct tm crtm; + struct tm crtm; - (*AH->WriteBufPtr)(AH, "PGDMP", 5); /* Magic code */ - (*AH->WriteBytePtr)(AH, AH->vmaj); - (*AH->WriteBytePtr)(AH, AH->vmin); - (*AH->WriteBytePtr)(AH, AH->vrev); - (*AH->WriteBytePtr)(AH, AH->intSize); - (*AH->WriteBytePtr)(AH, AH->format); + (*AH->WriteBufPtr) (AH, "PGDMP", 5); /* Magic code */ + (*AH->WriteBytePtr) (AH, AH->vmaj); + (*AH->WriteBytePtr) (AH, AH->vmin); + (*AH->WriteBytePtr) (AH, AH->vrev); + (*AH->WriteBytePtr) (AH, AH->intSize); + (*AH->WriteBytePtr) (AH, AH->format); #ifndef HAVE_LIBZ - if (AH->compression != 0) - fprintf(stderr, "%s: WARNING - requested compression not available in this installation - " - "archive will be uncompressed \n", progname); + if (AH->compression != 0) + fprintf(stderr, "%s: WARNING - requested compression not available in this installation - " + "archive will be uncompressed \n", progname); - AH->compression = 0; + AH->compression = 0; #endif @@ -1713,41 +1843,41 @@ void WriteHead(ArchiveHandle* AH) WriteInt(AH, crtm.tm_mon); WriteInt(AH, crtm.tm_year); WriteInt(AH, crtm.tm_isdst); - WriteStr(AH, AH->dbname); + WriteStr(AH, AH->dbname); } -void ReadHead(ArchiveHandle* AH) +void +ReadHead(ArchiveHandle *AH) { - char tmpMag[7]; - int fmt; + char tmpMag[7]; + int fmt; struct tm crtm; /* If we haven't already read the header... */ - if (!AH->readHeader) { + if (!AH->readHeader) + { - (*AH->ReadBufPtr)(AH, tmpMag, 5); + (*AH->ReadBufPtr) (AH, tmpMag, 5); - if (strncmp(tmpMag,"PGDMP", 5) != 0) + if (strncmp(tmpMag, "PGDMP", 5) != 0) die_horribly(AH, "Archiver: Did not fing magic PGDMP in file header\n"); - AH->vmaj = (*AH->ReadBytePtr)(AH); - AH->vmin = (*AH->ReadBytePtr)(AH); + AH->vmaj = (*AH->ReadBytePtr) (AH); + AH->vmin = (*AH->ReadBytePtr) (AH); - if (AH->vmaj > 1 || ( (AH->vmaj == 1) && (AH->vmin > 0) ) ) /* Version > 1.0 */ - { - AH->vrev = (*AH->ReadBytePtr)(AH); - } else { + if (AH->vmaj > 1 || ((AH->vmaj == 1) && (AH->vmin > 0))) /* Version > 1.0 */ + AH->vrev = (*AH->ReadBytePtr) (AH); + else AH->vrev = 0; - } - AH->version = ( (AH->vmaj * 256 + AH->vmin) * 256 + AH->vrev ) * 256 + 0; + AH->version = ((AH->vmaj * 256 + AH->vmin) * 256 + AH->vrev) * 256 + 0; if (AH->version < K_VERS_1_0 || AH->version > K_VERS_MAX) - die_horribly(AH, "%s: unsupported version (%d.%d) in file header\n", - progname, AH->vmaj, AH->vmin); + die_horribly(AH, "%s: unsupported version (%d.%d) in file header\n", + progname, AH->vmaj, AH->vmin); - AH->intSize = (*AH->ReadBytePtr)(AH); + AH->intSize = (*AH->ReadBytePtr) (AH); if (AH->intSize > 32) die_horribly(AH, "Archiver: sanity check on integer size (%d) failes\n", AH->intSize); @@ -1755,27 +1885,27 @@ void ReadHead(ArchiveHandle* AH) fprintf(stderr, "\n%s: WARNING - archive was made on a machine with larger integers, " "some operations may fail\n", progname); - fmt = (*AH->ReadBytePtr)(AH); + fmt = (*AH->ReadBytePtr) (AH); if (AH->format != fmt) - die_horribly(AH, "%s: expected format (%d) differs from format found in file (%d)\n", - progname, AH->format, fmt); - } + die_horribly(AH, "%s: expected format (%d) differs from format found in file (%d)\n", + progname, AH->format, fmt); + } - if (AH->version >= K_VERS_1_2) - { + if (AH->version >= K_VERS_1_2) + { if (AH->version < K_VERS_1_4) - AH->compression = (*AH->ReadBytePtr)(AH); + AH->compression = (*AH->ReadBytePtr) (AH); else AH->compression = ReadInt(AH); - } else { + } + else AH->compression = Z_DEFAULT_COMPRESSION; - } #ifndef HAVE_LIBZ - if (AH->compression != 0) - fprintf(stderr, "%s: WARNING - archive is compressed - any data will not be available\n", - progname); + if (AH->compression != 0) + fprintf(stderr, "%s: WARNING - archive is compressed - any data will not be available\n", + progname); #endif if (AH->version >= K_VERS_1_4) @@ -1792,85 +1922,97 @@ void ReadHead(ArchiveHandle* AH) AH->createDate = mktime(&crtm); - if (AH->createDate == (time_t)-1) + if (AH->createDate == (time_t) -1) fprintf(stderr, "%s: WARNING - bad creation date in header\n", progname); } } -static void _SortToc(ArchiveHandle* AH, TocSortCompareFn fn) +static void +_SortToc(ArchiveHandle *AH, TocSortCompareFn fn) { - TocEntry** tea; - TocEntry* te; - int i; + TocEntry **tea; + TocEntry *te; + int i; - /* Allocate an array for quicksort (TOC size + head & foot) */ - tea = (TocEntry**)malloc(sizeof(TocEntry*) * (AH->tocCount + 2) ); + /* Allocate an array for quicksort (TOC size + head & foot) */ + tea = (TocEntry **) malloc(sizeof(TocEntry *) * (AH->tocCount + 2)); + + /* Build array of toc entries, including header at start and end */ + te = AH->toc; + for (i = 0; i <= AH->tocCount + 1; i++) + { + + /* + * printf("%d: %x (%x, %x) - %d\n", i, te, te->prev, te->next, + * te->oidVal); + */ + tea[i] = te; + te = te->next; + } - /* Build array of toc entries, including header at start and end */ - te = AH->toc; - for( i = 0 ; i <= AH->tocCount+1 ; i++) { - /* printf("%d: %x (%x, %x) - %d\n", i, te, te->prev, te->next, te->oidVal); */ - tea[i] = te; - te = te->next; - } + /* Sort it, but ignore the header entries */ + qsort(&(tea[1]), AH->tocCount, sizeof(TocEntry *), fn); - /* Sort it, but ignore the header entries */ - qsort(&(tea[1]), AH->tocCount, sizeof(TocEntry*), fn); + /* Rebuild list: this works becuase we have headers at each end */ + for (i = 1; i <= AH->tocCount; i++) + { + tea[i]->next = tea[i + 1]; + tea[i]->prev = tea[i - 1]; + } - /* Rebuild list: this works becuase we have headers at each end */ - for( i = 1 ; i <= AH->tocCount ; i++) { - tea[i]->next = tea[i+1]; - tea[i]->prev = tea[i-1]; - } + te = AH->toc; + for (i = 0; i <= AH->tocCount + 1; i++) + { - te = AH->toc; - for( i = 0 ; i <= AH->tocCount+1 ; i++) { - /* printf("%d: %x (%x, %x) - %d\n", i, te, te->prev, te->next, te->oidVal); */ - te = te->next; - } + /* + * printf("%d: %x (%x, %x) - %d\n", i, te, te->prev, te->next, + * te->oidVal); + */ + te = te->next; + } - AH->toc->next = tea[1]; - AH->toc->prev = tea[AH->tocCount]; + AH->toc->next = tea[1]; + AH->toc->prev = tea[AH->tocCount]; } -static int _tocSortCompareByOIDNum(const void* p1, const void* p2) +static int +_tocSortCompareByOIDNum(const void *p1, const void *p2) { - TocEntry* te1 = *(TocEntry**)p1; - TocEntry* te2 = *(TocEntry**)p2; - int id1 = te1->oidVal; - int id2 = te2->oidVal; + TocEntry *te1 = *(TocEntry **) p1; + TocEntry *te2 = *(TocEntry **) p2; + int id1 = te1->oidVal; + int id2 = te2->oidVal; - /* printf("Comparing %d to %d\n", id1, id2); */ + /* printf("Comparing %d to %d\n", id1, id2); */ - if (id1 < id2) { - return -1; - } else if (id1 > id2) { - return 1; - } else { - return _tocSortCompareByIDNum(te1, te2); - } + if (id1 < id2) + return -1; + else if (id1 > id2) + return 1; + else + return _tocSortCompareByIDNum(te1, te2); } -static int _tocSortCompareByIDNum(const void* p1, const void* p2) +static int +_tocSortCompareByIDNum(const void *p1, const void *p2) { - TocEntry* te1 = *(TocEntry**)p1; - TocEntry* te2 = *(TocEntry**)p2; - int id1 = te1->id; - int id2 = te2->id; + TocEntry *te1 = *(TocEntry **) p1; + TocEntry *te2 = *(TocEntry **) p2; + int id1 = te1->id; + int id2 = te2->id; - /* printf("Comparing %d to %d\n", id1, id2); */ + /* printf("Comparing %d to %d\n", id1, id2); */ - if (id1 < id2) { - return -1; - } else if (id1 > id2) { - return 1; - } else { - return 0; - } + if (id1 < id2) + return -1; + else if (id1 > id2) + return 1; + else + return 0; } /* @@ -1881,4 +2023,3 @@ static int _tocSortCompareByIDNum(const void* p1, const void* p2) * *insert into dump_blob_xref select 12345,lo_import(p || '/q.q') from pgdump_blob_path; */ - diff --git a/src/bin/pg_dump/pg_backup_archiver.h b/src/bin/pg_dump/pg_backup_archiver.h index fdf70f716f..fd9a0cf901 100644 --- a/src/bin/pg_dump/pg_backup_archiver.h +++ b/src/bin/pg_dump/pg_backup_archiver.h @@ -3,25 +3,25 @@ * pg_backup_archiver.h * * Private interface to the pg_dump archiver routines. - * It is NOT intended that these routines be called by any + * It is NOT intended that these routines be called by any * dumper directly. * * See the headers to pg_restore for more details. * * Copyright (c) 2000, Philip Warner - * Rights are granted to use this software in any way so long - * as this notice is not removed. + * Rights are granted to use this software in any way so long + * as this notice is not removed. * * The author is not responsible for loss or damages that may * result from it's use. * * * IDENTIFICATION - * $Header: /cvsroot/pgsql/src/bin/pg_dump/pg_backup_archiver.h,v 1.26 2001/03/19 02:35:28 pjw Exp $ + * $Header: /cvsroot/pgsql/src/bin/pg_dump/pg_backup_archiver.h,v 1.27 2001/03/22 04:00:12 momjian Exp $ * * Modifications - 28-Jun-2000 - pjw@rhyme.com.au * - * Initial version. + * Initial version. * * Modifications - 15-Sep-2000 - pjw@rhyme.com.au * - Added braceDepth to sqlparseInfo to handle braces in rule definitions. @@ -49,21 +49,23 @@ #define GZREAD(p, s, n, fh) fread(p, s, n, fh) #define Z_DEFAULT_COMPRESSION -1 -typedef struct _z_stream { - void *next_in; - void *next_out; - int avail_in; - int avail_out; +typedef struct _z_stream +{ + void *next_in; + void *next_out; + int avail_in; + int avail_out; } z_stream; typedef z_stream *z_streamp; + #endif #include "pg_backup.h" #include "libpq-fe.h" #define K_VERS_MAJOR 1 -#define K_VERS_MINOR 4 -#define K_VERS_REV 30 +#define K_VERS_MINOR 4 +#define K_VERS_REV 30 /* Data block types */ #define BLK_DATA 1 @@ -72,220 +74,239 @@ typedef z_stream *z_streamp; /* Some important version numbers (checked in code) */ #define K_VERS_1_0 (( (1 * 256 + 0) * 256 + 0) * 256 + 0) -#define K_VERS_1_2 (( (1 * 256 + 2) * 256 + 0) * 256 + 0) /* Allow No ZLIB */ -#define K_VERS_1_3 (( (1 * 256 + 3) * 256 + 0) * 256 + 0) /* BLOBs */ -#define K_VERS_1_4 (( (1 * 256 + 4) * 256 + 0) * 256 + 0) /* Date & name in header */ +#define K_VERS_1_2 (( (1 * 256 + 2) * 256 + 0) * 256 + 0) /* Allow No ZLIB */ +#define K_VERS_1_3 (( (1 * 256 + 3) * 256 + 0) * 256 + 0) /* BLOBs */ +#define K_VERS_1_4 (( (1 * 256 + 4) * 256 + 0) * 256 + 0) /* Date & name in header */ #define K_VERS_MAX (( (1 * 256 + 4) * 256 + 255) * 256 + 0) /* No of BLOBs to restore in 1 TX */ -#define BLOB_BATCH_SIZE 100 +#define BLOB_BATCH_SIZE 100 struct _archiveHandle; struct _tocEntry; struct _restoreList; -typedef void (*ClosePtr) (struct _archiveHandle* AH); -typedef void (*ArchiveEntryPtr) (struct _archiveHandle* AH, struct _tocEntry* te); - -typedef void (*StartDataPtr) (struct _archiveHandle* AH, struct _tocEntry* te); -typedef int (*WriteDataPtr) (struct _archiveHandle* AH, const void* data, int dLen); -typedef void (*EndDataPtr) (struct _archiveHandle* AH, struct _tocEntry* te); - -typedef void (*StartBlobsPtr) (struct _archiveHandle* AH, struct _tocEntry* te); -typedef void (*StartBlobPtr) (struct _archiveHandle* AH, struct _tocEntry* te, int oid); -typedef void (*EndBlobPtr) (struct _archiveHandle* AH, struct _tocEntry* te, int oid); -typedef void (*EndBlobsPtr) (struct _archiveHandle* AH, struct _tocEntry* te); - -typedef int (*WriteBytePtr) (struct _archiveHandle* AH, const int i); -typedef int (*ReadBytePtr) (struct _archiveHandle* AH); -typedef int (*WriteBufPtr) (struct _archiveHandle* AH, const void* c, int len); -typedef int (*ReadBufPtr) (struct _archiveHandle* AH, void* buf, int len); -typedef void (*SaveArchivePtr) (struct _archiveHandle* AH); -typedef void (*WriteExtraTocPtr) (struct _archiveHandle* AH, struct _tocEntry* te); -typedef void (*ReadExtraTocPtr) (struct _archiveHandle* AH, struct _tocEntry* te); -typedef void (*PrintExtraTocPtr) (struct _archiveHandle* AH, struct _tocEntry* te); -typedef void (*PrintTocDataPtr) (struct _archiveHandle* AH, struct _tocEntry* te, RestoreOptions *ropt); - -typedef int (*CustomOutPtr) (struct _archiveHandle* AH, const void* buf, int len); - -typedef int (*TocSortCompareFn) (const void* te1, const void *te2); - -typedef enum _archiveMode { - archModeWrite, - archModeRead +typedef void (*ClosePtr) (struct _archiveHandle * AH); +typedef void (*ArchiveEntryPtr) (struct _archiveHandle * AH, struct _tocEntry * te); + +typedef void (*StartDataPtr) (struct _archiveHandle * AH, struct _tocEntry * te); +typedef int (*WriteDataPtr) (struct _archiveHandle * AH, const void *data, int dLen); +typedef void (*EndDataPtr) (struct _archiveHandle * AH, struct _tocEntry * te); + +typedef void (*StartBlobsPtr) (struct _archiveHandle * AH, struct _tocEntry * te); +typedef void (*StartBlobPtr) (struct _archiveHandle * AH, struct _tocEntry * te, int oid); +typedef void (*EndBlobPtr) (struct _archiveHandle * AH, struct _tocEntry * te, int oid); +typedef void (*EndBlobsPtr) (struct _archiveHandle * AH, struct _tocEntry * te); + +typedef int (*WriteBytePtr) (struct _archiveHandle * AH, const int i); +typedef int (*ReadBytePtr) (struct _archiveHandle * AH); +typedef int (*WriteBufPtr) (struct _archiveHandle * AH, const void *c, int len); +typedef int (*ReadBufPtr) (struct _archiveHandle * AH, void *buf, int len); +typedef void (*SaveArchivePtr) (struct _archiveHandle * AH); +typedef void (*WriteExtraTocPtr) (struct _archiveHandle * AH, struct _tocEntry * te); +typedef void (*ReadExtraTocPtr) (struct _archiveHandle * AH, struct _tocEntry * te); +typedef void (*PrintExtraTocPtr) (struct _archiveHandle * AH, struct _tocEntry * te); +typedef void (*PrintTocDataPtr) (struct _archiveHandle * AH, struct _tocEntry * te, RestoreOptions *ropt); + +typedef int (*CustomOutPtr) (struct _archiveHandle * AH, const void *buf, int len); + +typedef int (*TocSortCompareFn) (const void *te1, const void *te2); + +typedef enum _archiveMode +{ + archModeWrite, + archModeRead } ArchiveMode; -typedef struct _outputContext { - void *OF; - int gzOut; +typedef struct _outputContext +{ + void *OF; + int gzOut; } OutputContext; -typedef enum { +typedef enum +{ SQL_SCAN = 0, SQL_IN_SQL_COMMENT, SQL_IN_EXT_COMMENT, - SQL_IN_QUOTE} sqlparseState; - -typedef struct { - int backSlash; - sqlparseState state; - char lastChar; - char quoteChar; - int braceDepth; + SQL_IN_QUOTE +} sqlparseState; + +typedef struct +{ + int backSlash; + sqlparseState state; + char lastChar; + char quoteChar; + int braceDepth; } sqlparseInfo; -typedef struct _archiveHandle { - Archive public; /* Public part of archive */ - char vmaj; /* Version of file */ - char vmin; - char vrev; - int version; /* Conveniently formatted version */ +typedef struct _archiveHandle +{ + Archive public; /* Public part of archive */ + char vmaj; /* Version of file */ + char vmin; + char vrev; + int version; /* Conveniently formatted version */ - int debugLevel; /* Used for logging (currently only by --verbose) */ - int intSize; /* Size of an integer in the archive */ - ArchiveFormat format; /* Archive format */ + int debugLevel; /* Used for logging (currently only by + * --verbose) */ + int intSize; /* Size of an integer in the archive */ + ArchiveFormat format; /* Archive format */ - sqlparseInfo sqlparse; - PQExpBuffer sqlBuf; + sqlparseInfo sqlparse; + PQExpBuffer sqlBuf; - time_t createDate; /* Date archive created */ + time_t createDate; /* Date archive created */ /* - * Fields used when discovering header. - * A format can always get the previous read bytes from here... + * Fields used when discovering header. A format can always get the + * previous read bytes from here... */ - int readHeader; /* Used if file header has been read already */ - char *lookahead; /* Buffer used when reading header to discover format */ - int lookaheadSize; /* Size of allocated buffer */ - int lookaheadLen; /* Length of data in lookahead */ - int lookaheadPos; /* Current read position in lookahead buffer */ - - ArchiveEntryPtr ArchiveEntryPtr; /* Called for each metadata object */ - StartDataPtr StartDataPtr; /* Called when table data is about to be dumped */ - WriteDataPtr WriteDataPtr; /* Called to send some table data to the archive */ - EndDataPtr EndDataPtr; /* Called when table data dump is finished */ - WriteBytePtr WriteBytePtr; /* Write a byte to output */ - ReadBytePtr ReadBytePtr; /* Read a byte from an archive */ - WriteBufPtr WriteBufPtr; /* Write a buffer of output to the archive */ - ReadBufPtr ReadBufPtr; /* Read a buffer of input from the archive */ - ClosePtr ClosePtr; /* Close the archive */ - WriteExtraTocPtr WriteExtraTocPtr; /* Write extra TOC entry data associated with */ - /* the current archive format */ - ReadExtraTocPtr ReadExtraTocPtr; /* Read extr info associated with archie format */ - PrintExtraTocPtr PrintExtraTocPtr; /* Extra TOC info for format */ - PrintTocDataPtr PrintTocDataPtr; - - StartBlobsPtr StartBlobsPtr; - EndBlobsPtr EndBlobsPtr; - StartBlobPtr StartBlobPtr; - EndBlobPtr EndBlobPtr; - - CustomOutPtr CustomOutPtr; /* Alternate script output routine */ + int readHeader; /* Used if file header has been read + * already */ + char *lookahead; /* Buffer used when reading header to + * discover format */ + int lookaheadSize; /* Size of allocated buffer */ + int lookaheadLen; /* Length of data in lookahead */ + int lookaheadPos; /* Current read position in lookahead + * buffer */ + + ArchiveEntryPtr ArchiveEntryPtr; /* Called for each metadata object */ + StartDataPtr StartDataPtr; /* Called when table data is about to be + * dumped */ + WriteDataPtr WriteDataPtr; /* Called to send some table data to the + * archive */ + EndDataPtr EndDataPtr; /* Called when table data dump is finished */ + WriteBytePtr WriteBytePtr; /* Write a byte to output */ + ReadBytePtr ReadBytePtr; /* Read a byte from an archive */ + WriteBufPtr WriteBufPtr; /* Write a buffer of output to the archive */ + ReadBufPtr ReadBufPtr; /* Read a buffer of input from the archive */ + ClosePtr ClosePtr; /* Close the archive */ + WriteExtraTocPtr WriteExtraTocPtr; /* Write extra TOC entry data + * associated with */ + /* the current archive format */ + ReadExtraTocPtr ReadExtraTocPtr; /* Read extr info associated with + * archie format */ + PrintExtraTocPtr PrintExtraTocPtr; /* Extra TOC info for format */ + PrintTocDataPtr PrintTocDataPtr; + + StartBlobsPtr StartBlobsPtr; + EndBlobsPtr EndBlobsPtr; + StartBlobPtr StartBlobPtr; + EndBlobPtr EndBlobPtr; + + CustomOutPtr CustomOutPtr; /* Alternate script output routine */ /* Stuff for direct DB connection */ - char username[100]; - char *dbname; /* Name of db for connection */ - char *archdbname; /* DB name *read* from archive */ - char *pghost; - char *pgport; - PGconn *connection; - PGconn *blobConnection; /* Connection for BLOB xref */ - int txActive; /* Flag set if TX active on connection */ - int blobTxActive; /* Flag set if TX active on blobConnection */ - int connectToDB; /* Flag to indicate if direct DB connection is required */ - int pgCopyIn; /* Currently in libpq 'COPY IN' mode. */ - PQExpBuffer pgCopyBuf; /* Left-over data from incomplete lines in COPY IN */ - - int loFd; /* BLOB fd */ - int writingBlob; /* Flag */ - int createdBlobXref; /* Flag */ - int blobCount; /* # of blobs restored */ - - int lastID; /* Last internal ID for a TOC entry */ - char* fSpec; /* Archive File Spec */ - FILE *FH; /* General purpose file handle */ - void *OF; - int gzOut; /* Output file */ - - struct _tocEntry* toc; /* List of TOC entries */ - int tocCount; /* Number of TOC entries */ - struct _tocEntry* currToc; /* Used when dumping data */ - char *currUser; /* Restore: current username in script */ - int compression; /* Compression requested on open */ - ArchiveMode mode; /* File mode - r or w */ - void* formatData; /* Header data specific to file format */ - - RestoreOptions *ropt; /* Used to check restore options in ahwrite etc */ + char username[100]; + char *dbname; /* Name of db for connection */ + char *archdbname; /* DB name *read* from archive */ + char *pghost; + char *pgport; + PGconn *connection; + PGconn *blobConnection; /* Connection for BLOB xref */ + int txActive; /* Flag set if TX active on connection */ + int blobTxActive; /* Flag set if TX active on blobConnection */ + int connectToDB; /* Flag to indicate if direct DB + * connection is required */ + int pgCopyIn; /* Currently in libpq 'COPY IN' mode. */ + PQExpBuffer pgCopyBuf; /* Left-over data from incomplete lines in + * COPY IN */ + + int loFd; /* BLOB fd */ + int writingBlob; /* Flag */ + int createdBlobXref;/* Flag */ + int blobCount; /* # of blobs restored */ + + int lastID; /* Last internal ID for a TOC entry */ + char *fSpec; /* Archive File Spec */ + FILE *FH; /* General purpose file handle */ + void *OF; + int gzOut; /* Output file */ + + struct _tocEntry *toc; /* List of TOC entries */ + int tocCount; /* Number of TOC entries */ + struct _tocEntry *currToc; /* Used when dumping data */ + char *currUser; /* Restore: current username in script */ + int compression; /* Compression requested on open */ + ArchiveMode mode; /* File mode - r or w */ + void *formatData; /* Header data specific to file format */ + + RestoreOptions *ropt; /* Used to check restore options in + * ahwrite etc */ } ArchiveHandle; -typedef struct _tocEntry { - struct _tocEntry* prev; - struct _tocEntry* next; - int id; - int hadDumper; /* Archiver was passed a dumper routine (used in restore) */ - char* oid; - int oidVal; - char* name; - char* desc; - char* defn; - char* dropStmt; - char* copyStmt; - char* owner; - char** depOid; - int printed; /* Indicates if entry defn has been dumped */ - DataDumperPtr dataDumper; /* Routine to dump data for object */ - void* dataDumperArg; /* Arg for above routine */ - void* formatData; /* TOC Entry data specific to file format */ - - int _moved; /* Marker used when rearranging TOC */ +typedef struct _tocEntry +{ + struct _tocEntry *prev; + struct _tocEntry *next; + int id; + int hadDumper; /* Archiver was passed a dumper routine + * (used in restore) */ + char *oid; + int oidVal; + char *name; + char *desc; + char *defn; + char *dropStmt; + char *copyStmt; + char *owner; + char **depOid; + int printed; /* Indicates if entry defn has been dumped */ + DataDumperPtr dataDumper; /* Routine to dump data for object */ + void *dataDumperArg; /* Arg for above routine */ + void *formatData; /* TOC Entry data specific to file format */ + + int _moved; /* Marker used when rearranging TOC */ } TocEntry; /* Used everywhere */ -extern void die_horribly(ArchiveHandle *AH, const char *fmt, ...); +extern void die_horribly(ArchiveHandle *AH, const char *fmt,...); -extern void WriteTOC(ArchiveHandle* AH); -extern void ReadTOC(ArchiveHandle* AH); -extern void WriteHead(ArchiveHandle* AH); -extern void ReadHead(ArchiveHandle* AH); -extern void WriteToc(ArchiveHandle* AH); -extern void ReadToc(ArchiveHandle* AH); -extern void WriteDataChunks(ArchiveHandle* AH); +extern void WriteTOC(ArchiveHandle *AH); +extern void ReadTOC(ArchiveHandle *AH); +extern void WriteHead(ArchiveHandle *AH); +extern void ReadHead(ArchiveHandle *AH); +extern void WriteToc(ArchiveHandle *AH); +extern void ReadToc(ArchiveHandle *AH); +extern void WriteDataChunks(ArchiveHandle *AH); -extern int TocIDRequired(ArchiveHandle* AH, int id, RestoreOptions *ropt); +extern int TocIDRequired(ArchiveHandle *AH, int id, RestoreOptions *ropt); /* * Mandatory routines for each supported format */ -extern int WriteInt(ArchiveHandle* AH, int i); -extern int ReadInt(ArchiveHandle* AH); -extern char* ReadStr(ArchiveHandle* AH); -extern int WriteStr(ArchiveHandle* AH, char* s); +extern int WriteInt(ArchiveHandle *AH, int i); +extern int ReadInt(ArchiveHandle *AH); +extern char *ReadStr(ArchiveHandle *AH); +extern int WriteStr(ArchiveHandle *AH, char *s); -extern void StartRestoreBlobs(ArchiveHandle* AH); -extern void StartRestoreBlob(ArchiveHandle* AH, int oid); -extern void EndRestoreBlob(ArchiveHandle* AH, int oid); -extern void EndRestoreBlobs(ArchiveHandle* AH); +extern void StartRestoreBlobs(ArchiveHandle *AH); +extern void StartRestoreBlob(ArchiveHandle *AH, int oid); +extern void EndRestoreBlob(ArchiveHandle *AH, int oid); +extern void EndRestoreBlobs(ArchiveHandle *AH); -extern void InitArchiveFmt_Custom(ArchiveHandle* AH); -extern void InitArchiveFmt_Files(ArchiveHandle* AH); -extern void InitArchiveFmt_Null(ArchiveHandle* AH); -extern void InitArchiveFmt_Tar(ArchiveHandle* AH); +extern void InitArchiveFmt_Custom(ArchiveHandle *AH); +extern void InitArchiveFmt_Files(ArchiveHandle *AH); +extern void InitArchiveFmt_Null(ArchiveHandle *AH); +extern void InitArchiveFmt_Tar(ArchiveHandle *AH); -extern int isValidTarHeader(char *header); +extern int isValidTarHeader(char *header); -extern OutputContext SetOutput(ArchiveHandle* AH, char *filename, int compression); -extern void ResetOutput(ArchiveHandle* AH, OutputContext savedContext); -extern int RestoringToDB(ArchiveHandle* AH); -extern int ReconnectDatabase(ArchiveHandle *AH, const char* dbname, char *newUser); -extern int UserIsSuperuser(ArchiveHandle *AH, char* user); -extern char* ConnectedUser(ArchiveHandle *AH); -extern int ConnectedUserIsSuperuser(ArchiveHandle *AH); +extern OutputContext SetOutput(ArchiveHandle *AH, char *filename, int compression); +extern void ResetOutput(ArchiveHandle *AH, OutputContext savedContext); +extern int RestoringToDB(ArchiveHandle *AH); +extern int ReconnectDatabase(ArchiveHandle *AH, const char *dbname, char *newUser); +extern int UserIsSuperuser(ArchiveHandle *AH, char *user); +extern char *ConnectedUser(ArchiveHandle *AH); +extern int ConnectedUserIsSuperuser(ArchiveHandle *AH); -int ahwrite(const void *ptr, size_t size, size_t nmemb, ArchiveHandle* AH); -int ahprintf(ArchiveHandle* AH, const char *fmt, ...); +int ahwrite(const void *ptr, size_t size, size_t nmemb, ArchiveHandle *AH); +int ahprintf(ArchiveHandle *AH, const char *fmt,...); -void ahlog(ArchiveHandle* AH, int level, const char *fmt, ...); +void ahlog(ArchiveHandle *AH, int level, const char *fmt,...); #endif diff --git a/src/bin/pg_dump/pg_backup_custom.c b/src/bin/pg_dump/pg_backup_custom.c index e9117b8320..e58a9f15c3 100644 --- a/src/bin/pg_dump/pg_backup_custom.c +++ b/src/bin/pg_dump/pg_backup_custom.c @@ -4,30 +4,30 @@ * * Implements the custom output format. * - * The comments with the routined in this code are a good place to - * understand how to write a new format. + * The comments with the routined in this code are a good place to + * understand how to write a new format. * * See the headers to pg_restore for more details. * * Copyright (c) 2000, Philip Warner - * Rights are granted to use this software in any way so long - * as this notice is not removed. + * Rights are granted to use this software in any way so long + * as this notice is not removed. * * The author is not responsible for loss or damages that may * and any liability will be limited to the time taken to fix any - * related bug. + * related bug. * * * IDENTIFICATION - * $Header: /cvsroot/pgsql/src/bin/pg_dump/pg_backup_custom.c,v 1.8 2001/03/19 02:35:28 pjw Exp $ + * $Header: /cvsroot/pgsql/src/bin/pg_dump/pg_backup_custom.c,v 1.9 2001/03/22 04:00:12 momjian Exp $ * * Modifications - 28-Jun-2000 - pjw@rhyme.com.au * - * Initial version. + * Initial version. * * Modifications - 04-Jan-2001 - pjw@rhyme.com.au * - * - Check results of IO routines more carefully. + * - Check results of IO routines more carefully. * *------------------------------------------------------------------------- */ @@ -43,161 +43,165 @@ *-------- */ -static void _ArchiveEntry(ArchiveHandle* AH, TocEntry* te); -static void _StartData(ArchiveHandle* AH, TocEntry* te); -static int _WriteData(ArchiveHandle* AH, const void* data, int dLen); -static void _EndData(ArchiveHandle* AH, TocEntry* te); -static int _WriteByte(ArchiveHandle* AH, const int i); -static int _ReadByte(ArchiveHandle* ); -static int _WriteBuf(ArchiveHandle* AH, const void* buf, int len); -static int _ReadBuf(ArchiveHandle* AH, void* buf, int len); -static void _CloseArchive(ArchiveHandle* AH); -static void _PrintTocData(ArchiveHandle* AH, TocEntry* te, RestoreOptions *ropt); -static void _WriteExtraToc(ArchiveHandle* AH, TocEntry* te); -static void _ReadExtraToc(ArchiveHandle* AH, TocEntry* te); -static void _PrintExtraToc(ArchiveHandle* AH, TocEntry* te); - -static void _PrintData(ArchiveHandle* AH); -static void _skipData(ArchiveHandle* AH); -static void _skipBlobs(ArchiveHandle* AH); - -static void _StartBlobs(ArchiveHandle* AH, TocEntry* te); -static void _StartBlob(ArchiveHandle* AH, TocEntry* te, int oid); -static void _EndBlob(ArchiveHandle* AH, TocEntry* te, int oid); -static void _EndBlobs(ArchiveHandle* AH, TocEntry* te); -static void _LoadBlobs(ArchiveHandle* AH); +static void _ArchiveEntry(ArchiveHandle *AH, TocEntry *te); +static void _StartData(ArchiveHandle *AH, TocEntry *te); +static int _WriteData(ArchiveHandle *AH, const void *data, int dLen); +static void _EndData(ArchiveHandle *AH, TocEntry *te); +static int _WriteByte(ArchiveHandle *AH, const int i); +static int _ReadByte(ArchiveHandle *); +static int _WriteBuf(ArchiveHandle *AH, const void *buf, int len); +static int _ReadBuf(ArchiveHandle *AH, void *buf, int len); +static void _CloseArchive(ArchiveHandle *AH); +static void _PrintTocData(ArchiveHandle *AH, TocEntry *te, RestoreOptions *ropt); +static void _WriteExtraToc(ArchiveHandle *AH, TocEntry *te); +static void _ReadExtraToc(ArchiveHandle *AH, TocEntry *te); +static void _PrintExtraToc(ArchiveHandle *AH, TocEntry *te); + +static void _PrintData(ArchiveHandle *AH); +static void _skipData(ArchiveHandle *AH); +static void _skipBlobs(ArchiveHandle *AH); + +static void _StartBlobs(ArchiveHandle *AH, TocEntry *te); +static void _StartBlob(ArchiveHandle *AH, TocEntry *te, int oid); +static void _EndBlob(ArchiveHandle *AH, TocEntry *te, int oid); +static void _EndBlobs(ArchiveHandle *AH, TocEntry *te); +static void _LoadBlobs(ArchiveHandle *AH); /*------------ * Buffers used in zlib compression and extra data stored in archive and * in TOC entries. *------------ */ -#define zlibOutSize 4096 +#define zlibOutSize 4096 #define zlibInSize 4096 -typedef struct { - z_streamp zp; - char* zlibOut; - char* zlibIn; - int inSize; - int hasSeek; - int filePos; - int dataStart; +typedef struct +{ + z_streamp zp; + char *zlibOut; + char *zlibIn; + int inSize; + int hasSeek; + int filePos; + int dataStart; } lclContext; -typedef struct { - int dataPos; - int dataLen; +typedef struct +{ + int dataPos; + int dataLen; } lclTocEntry; /*------ - * Static declarations + * Static declarations *------ */ -static void _readBlockHeader(ArchiveHandle *AH, int *type, int *id); -static void _StartDataCompressor(ArchiveHandle* AH, TocEntry* te); -static void _EndDataCompressor(ArchiveHandle* AH, TocEntry* te); -static int _getFilePos(ArchiveHandle* AH, lclContext* ctx); -static int _DoDeflate(ArchiveHandle* AH, lclContext* ctx, int flush); +static void _readBlockHeader(ArchiveHandle *AH, int *type, int *id); +static void _StartDataCompressor(ArchiveHandle *AH, TocEntry *te); +static void _EndDataCompressor(ArchiveHandle *AH, TocEntry *te); +static int _getFilePos(ArchiveHandle *AH, lclContext *ctx); +static int _DoDeflate(ArchiveHandle *AH, lclContext *ctx, int flush); -static char* progname = "Archiver(custom)"; +static char *progname = "Archiver(custom)"; /* - * Init routine required by ALL formats. This is a global routine + * Init routine required by ALL formats. This is a global routine * and should be declared in pg_backup_archiver.h * * It's task is to create any extra archive context (using AH->formatData), * and to initialize the supported function pointers. * * It should also prepare whatever it's input source is for reading/writing, - * and in the case of a read mode connection, it should load the Header & TOC. + * and in the case of a read mode connection, it should load the Header & TOC. */ -void InitArchiveFmt_Custom(ArchiveHandle* AH) +void +InitArchiveFmt_Custom(ArchiveHandle *AH) { - lclContext* ctx; - - /* Assuming static functions, this can be copied for each format. */ - AH->ArchiveEntryPtr = _ArchiveEntry; - AH->StartDataPtr = _StartData; - AH->WriteDataPtr = _WriteData; - AH->EndDataPtr = _EndData; - AH->WriteBytePtr = _WriteByte; - AH->ReadBytePtr = _ReadByte; - AH->WriteBufPtr = _WriteBuf; - AH->ReadBufPtr = _ReadBuf; - AH->ClosePtr = _CloseArchive; - AH->PrintTocDataPtr = _PrintTocData; - AH->ReadExtraTocPtr = _ReadExtraToc; - AH->WriteExtraTocPtr = _WriteExtraToc; - AH->PrintExtraTocPtr = _PrintExtraToc; - - AH->StartBlobsPtr = _StartBlobs; - AH->StartBlobPtr = _StartBlob; - AH->EndBlobPtr = _EndBlob; - AH->EndBlobsPtr = _EndBlobs; - - /* - * Set up some special context used in compressing data. - */ - ctx = (lclContext*)malloc(sizeof(lclContext)); - if (ctx == NULL) - die_horribly(AH, "%s: Unable to allocate archive context",progname); - AH->formatData = (void*)ctx; - - ctx->zp = (z_streamp)malloc(sizeof(z_stream)); - if (ctx->zp == NULL) - die_horribly(AH, "%s: unable to allocate zlib stream archive context",progname); + lclContext *ctx; + + /* Assuming static functions, this can be copied for each format. */ + AH->ArchiveEntryPtr = _ArchiveEntry; + AH->StartDataPtr = _StartData; + AH->WriteDataPtr = _WriteData; + AH->EndDataPtr = _EndData; + AH->WriteBytePtr = _WriteByte; + AH->ReadBytePtr = _ReadByte; + AH->WriteBufPtr = _WriteBuf; + AH->ReadBufPtr = _ReadBuf; + AH->ClosePtr = _CloseArchive; + AH->PrintTocDataPtr = _PrintTocData; + AH->ReadExtraTocPtr = _ReadExtraToc; + AH->WriteExtraTocPtr = _WriteExtraToc; + AH->PrintExtraTocPtr = _PrintExtraToc; + + AH->StartBlobsPtr = _StartBlobs; + AH->StartBlobPtr = _StartBlob; + AH->EndBlobPtr = _EndBlob; + AH->EndBlobsPtr = _EndBlobs; + + /* + * Set up some special context used in compressing data. + */ + ctx = (lclContext *) malloc(sizeof(lclContext)); + if (ctx == NULL) + die_horribly(AH, "%s: Unable to allocate archive context", progname); + AH->formatData = (void *) ctx; + + ctx->zp = (z_streamp) malloc(sizeof(z_stream)); + if (ctx->zp == NULL) + die_horribly(AH, "%s: unable to allocate zlib stream archive context", progname); /* * zlibOutSize is the buffer size we tell zlib it can output to. We - * actually allocate one extra byte because some routines want to append - * a trailing zero byte to the zlib output. The input buffer is expansible - * and is always of size ctx->inSize; zlibInSize is just the initial - * default size for it. + * actually allocate one extra byte because some routines want to + * append a trailing zero byte to the zlib output. The input buffer + * is expansible and is always of size ctx->inSize; zlibInSize is just + * the initial default size for it. */ - ctx->zlibOut = (char*)malloc(zlibOutSize+1); - ctx->zlibIn = (char*)malloc(zlibInSize); - ctx->inSize = zlibInSize; - ctx->filePos = 0; + ctx->zlibOut = (char *) malloc(zlibOutSize + 1); + ctx->zlibIn = (char *) malloc(zlibInSize); + ctx->inSize = zlibInSize; + ctx->filePos = 0; - if (ctx->zlibOut == NULL || ctx->zlibIn == NULL) - die_horribly(AH, "%s: unable to allocate buffers in archive context",progname); + if (ctx->zlibOut == NULL || ctx->zlibIn == NULL) + die_horribly(AH, "%s: unable to allocate buffers in archive context", progname); - /* - * Now open the file - */ - if (AH->mode == archModeWrite) { + /* + * Now open the file + */ + if (AH->mode == archModeWrite) + { - if (AH->fSpec && strcmp(AH->fSpec,"") != 0) { + if (AH->fSpec && strcmp(AH->fSpec, "") != 0) AH->FH = fopen(AH->fSpec, PG_BINARY_W); - } else { + else AH->FH = stdout; - } if (!AH->FH) - die_horribly(AH, "%s: unable to open archive file %s",progname, AH->fSpec); + die_horribly(AH, "%s: unable to open archive file %s", progname, AH->fSpec); ctx->hasSeek = (fseek(AH->FH, 0, SEEK_CUR) == 0); - } else { + } + else + { - if (AH->fSpec && strcmp(AH->fSpec,"") != 0) { + if (AH->fSpec && strcmp(AH->fSpec, "") != 0) AH->FH = fopen(AH->fSpec, PG_BINARY_R); - } else { + else AH->FH = stdin; - } if (!AH->FH) - die_horribly(AH, "%s: unable to open archive file %s",progname, AH->fSpec); + die_horribly(AH, "%s: unable to open archive file %s", progname, AH->fSpec); ctx->hasSeek = (fseek(AH->FH, 0, SEEK_CUR) == 0); ReadHead(AH); ReadToc(AH); ctx->dataStart = _getFilePos(AH, ctx); - } + } } @@ -206,20 +210,20 @@ void InitArchiveFmt_Custom(ArchiveHandle* AH) * * Optional. * - * Set up extrac format-related TOC data. + * Set up extrac format-related TOC data. */ -static void _ArchiveEntry(ArchiveHandle* AH, TocEntry* te) +static void +_ArchiveEntry(ArchiveHandle *AH, TocEntry *te) { - lclTocEntry* ctx; + lclTocEntry *ctx; - ctx = (lclTocEntry*)calloc(1, sizeof(lclTocEntry)); - if (te->dataDumper) { + ctx = (lclTocEntry *) calloc(1, sizeof(lclTocEntry)); + if (te->dataDumper) ctx->dataPos = -1; - } else { + else ctx->dataPos = 0; - } - ctx->dataLen = 0; - te->formatData = (void*)ctx; + ctx->dataLen = 0; + te->formatData = (void *) ctx; } @@ -232,12 +236,13 @@ static void _ArchiveEntry(ArchiveHandle* AH, TocEntry* te) * Use the Archiver routines to write data - they are non-endian, and * maintain other important file information. */ -static void _WriteExtraToc(ArchiveHandle* AH, TocEntry* te) +static void +_WriteExtraToc(ArchiveHandle *AH, TocEntry *te) { - lclTocEntry* ctx = (lclTocEntry*)te->formatData; + lclTocEntry *ctx = (lclTocEntry *) te->formatData; - WriteInt(AH, ctx->dataPos); - WriteInt(AH, ctx->dataLen); + WriteInt(AH, ctx->dataPos); + WriteInt(AH, ctx->dataLen); } /* @@ -248,17 +253,19 @@ static void _WriteExtraToc(ArchiveHandle* AH, TocEntry* te) * Needs to match the order defined in _WriteExtraToc, and sould also * use the Archiver input routines. */ -static void _ReadExtraToc(ArchiveHandle* AH, TocEntry* te) +static void +_ReadExtraToc(ArchiveHandle *AH, TocEntry *te) { - lclTocEntry* ctx = (lclTocEntry*)te->formatData; + lclTocEntry *ctx = (lclTocEntry *) te->formatData; - if (ctx == NULL) { - ctx = (lclTocEntry*)malloc(sizeof(lclTocEntry)); - te->formatData = (void*)ctx; - } + if (ctx == NULL) + { + ctx = (lclTocEntry *) malloc(sizeof(lclTocEntry)); + te->formatData = (void *) ctx; + } - ctx->dataPos = ReadInt( AH ); - ctx->dataLen = ReadInt( AH ); + ctx->dataPos = ReadInt(AH); + ctx->dataLen = ReadInt(AH); } /* @@ -268,11 +275,12 @@ static void _ReadExtraToc(ArchiveHandle* AH, TocEntry* te) * Optional. * */ -static void _PrintExtraToc(ArchiveHandle* AH, TocEntry* te) +static void +_PrintExtraToc(ArchiveHandle *AH, TocEntry *te) { - lclTocEntry* ctx = (lclTocEntry*)te->formatData; + lclTocEntry *ctx = (lclTocEntry *) te->formatData; - ahprintf(AH, "-- Data Pos: %d (Length %d)\n", ctx->dataPos, ctx->dataLen); + ahprintf(AH, "-- Data Pos: %d (Length %d)\n", ctx->dataPos, ctx->dataLen); } /* @@ -285,22 +293,23 @@ static void _PrintExtraToc(ArchiveHandle* AH, TocEntry* te) * Optional, but strongly recommended. * */ -static void _StartData(ArchiveHandle* AH, TocEntry* te) +static void +_StartData(ArchiveHandle *AH, TocEntry *te) { - lclContext* ctx = (lclContext*)AH->formatData; - lclTocEntry* tctx = (lclTocEntry*)te->formatData; + lclContext *ctx = (lclContext *) AH->formatData; + lclTocEntry *tctx = (lclTocEntry *) te->formatData; - tctx->dataPos = _getFilePos(AH, ctx); + tctx->dataPos = _getFilePos(AH, ctx); - _WriteByte(AH, BLK_DATA); /* Block type */ - WriteInt(AH, te->id); /* For sanity check */ + _WriteByte(AH, BLK_DATA); /* Block type */ + WriteInt(AH, te->id); /* For sanity check */ - _StartDataCompressor(AH, te); + _StartDataCompressor(AH, te); } /* - * Called by archiver when dumper calls WriteData. This routine is + * Called by archiver when dumper calls WriteData. This routine is * called for both BLOB and TABLE data; it is the responsibility of * the format to manage each kind of data using StartBlob/StartData. * @@ -309,19 +318,21 @@ static void _StartData(ArchiveHandle* AH, TocEntry* te) * Mandatory. * */ -static int _WriteData(ArchiveHandle* AH, const void* data, int dLen) +static int +_WriteData(ArchiveHandle *AH, const void *data, int dLen) { - lclContext* ctx = (lclContext*)AH->formatData; - z_streamp zp = ctx->zp; + lclContext *ctx = (lclContext *) AH->formatData; + z_streamp zp = ctx->zp; - zp->next_in = (void*)data; - zp->avail_in = dLen; + zp->next_in = (void *) data; + zp->avail_in = dLen; - while (zp->avail_in != 0) { - /* printf("Deflating %d bytes\n", dLen); */ + while (zp->avail_in != 0) + { + /* printf("Deflating %d bytes\n", dLen); */ _DoDeflate(AH, ctx, 0); - } - return dLen; + } + return dLen; } /* @@ -331,35 +342,37 @@ static int _WriteData(ArchiveHandle* AH, const void* data, int dLen) * Optional. * */ -static void _EndData(ArchiveHandle* AH, TocEntry* te) +static void +_EndData(ArchiveHandle *AH, TocEntry *te) { - lclContext* ctx = (lclContext*)AH->formatData; - lclTocEntry* tctx = (lclTocEntry*) te->formatData; + lclContext *ctx = (lclContext *) AH->formatData; + lclTocEntry *tctx = (lclTocEntry *) te->formatData; - _EndDataCompressor(AH, te); + _EndDataCompressor(AH, te); - tctx->dataLen = _getFilePos(AH, ctx) - tctx->dataPos; + tctx->dataLen = _getFilePos(AH, ctx) - tctx->dataPos; } /* - * Called by the archiver when starting to save all BLOB DATA (not schema). + * Called by the archiver when starting to save all BLOB DATA (not schema). * This routine should save whatever format-specific information is needed - * to read the BLOBs back into memory. + * to read the BLOBs back into memory. * * It is called just prior to the dumper's DataDumper routine. * * Optional, but strongly recommended. * */ -static void _StartBlobs(ArchiveHandle* AH, TocEntry* te) +static void +_StartBlobs(ArchiveHandle *AH, TocEntry *te) { - lclContext* ctx = (lclContext*)AH->formatData; - lclTocEntry* tctx = (lclTocEntry*)te->formatData; + lclContext *ctx = (lclContext *) AH->formatData; + lclTocEntry *tctx = (lclTocEntry *) te->formatData; - tctx->dataPos = _getFilePos(AH, ctx); + tctx->dataPos = _getFilePos(AH, ctx); - _WriteByte(AH, BLK_BLOBS); /* Block type */ - WriteInt(AH, te->id); /* For sanity check */ + _WriteByte(AH, BLK_BLOBS); /* Block type */ + WriteInt(AH, te->id); /* For sanity check */ } @@ -370,13 +383,14 @@ static void _StartBlobs(ArchiveHandle* AH, TocEntry* te) * * Must save the passed OID for retrieval at restore-time. */ -static void _StartBlob(ArchiveHandle* AH, TocEntry* te, int oid) +static void +_StartBlob(ArchiveHandle *AH, TocEntry *te, int oid) { - if (oid == 0) - die_horribly(AH, "%s: illegal OID for BLOB (%d)\n", progname, oid); + if (oid == 0) + die_horribly(AH, "%s: illegal OID for BLOB (%d)\n", progname, oid); - WriteInt(AH, oid); - _StartDataCompressor(AH, te); + WriteInt(AH, oid); + _StartDataCompressor(AH, te); } /* @@ -385,91 +399,100 @@ static void _StartBlob(ArchiveHandle* AH, TocEntry* te, int oid) * Optional. * */ -static void _EndBlob(ArchiveHandle* AH, TocEntry* te, int oid) +static void +_EndBlob(ArchiveHandle *AH, TocEntry *te, int oid) { - _EndDataCompressor(AH, te); + _EndDataCompressor(AH, te); } /* - * Called by the archiver when finishing saving all BLOB DATA. + * Called by the archiver when finishing saving all BLOB DATA. * * Optional. * */ -static void _EndBlobs(ArchiveHandle* AH, TocEntry* te) +static void +_EndBlobs(ArchiveHandle *AH, TocEntry *te) { /* Write out a fake zero OID to mark end-of-blobs. */ - WriteInt(AH, 0); + WriteInt(AH, 0); } /* * Print data for a gievn TOC entry */ -static void _PrintTocData(ArchiveHandle* AH, TocEntry* te, RestoreOptions *ropt) +static void +_PrintTocData(ArchiveHandle *AH, TocEntry *te, RestoreOptions *ropt) { - lclContext* ctx = (lclContext*)AH->formatData; - int id; - lclTocEntry* tctx = (lclTocEntry*) te->formatData; - int blkType; - int found = 0; + lclContext *ctx = (lclContext *) AH->formatData; + int id; + lclTocEntry *tctx = (lclTocEntry *) te->formatData; + int blkType; + int found = 0; - if (tctx->dataPos == 0) + if (tctx->dataPos == 0) return; - if (!ctx->hasSeek || tctx->dataPos < 0) { + if (!ctx->hasSeek || tctx->dataPos < 0) + { - /* Skip over unnecessary blocks until we get the one we want. */ + /* Skip over unnecessary blocks until we get the one we want. */ - found = 0; + found = 0; - _readBlockHeader(AH, &blkType, &id); + _readBlockHeader(AH, &blkType, &id); - while (id != te->id) { + while (id != te->id) + { - if ( (TocIDRequired(AH, id, ropt) & 2) != 0) - die_horribly(AH, "%s: Dumping a specific TOC data block out of order is not supported" - " without on this input stream (fseek required)\n", progname); + if ((TocIDRequired(AH, id, ropt) & 2) != 0) + die_horribly(AH, "%s: Dumping a specific TOC data block out of order is not supported" + " without on this input stream (fseek required)\n", progname); - switch (blkType) { + switch (blkType) + { - case BLK_DATA: + case BLK_DATA: - _skipData(AH); - break; + _skipData(AH); + break; - case BLK_BLOBS: + case BLK_BLOBS: - _skipBlobs(AH); - break; + _skipBlobs(AH); + break; - default: /* Always have a default */ + default: /* Always have a default */ - die_horribly(AH, "%s: unrecognized data block type while searching archive %d\n", - progname, blkType); - break; - } + die_horribly(AH, "%s: unrecognized data block type while searching archive %d\n", + progname, blkType); + break; + } - _readBlockHeader(AH, &blkType, &id); + _readBlockHeader(AH, &blkType, &id); - } + } - } else { + } + else + { - /* Grab it */ + /* Grab it */ if (fseek(AH->FH, tctx->dataPos, SEEK_SET) != 0) - die_horribly(AH, "%s: error %d in file seek\n",progname, errno); + die_horribly(AH, "%s: error %d in file seek\n", progname, errno); _readBlockHeader(AH, &blkType, &id); - } + } - /* Are we sane? */ - if (id != te->id) + /* Are we sane? */ + if (id != te->id) die_horribly(AH, "%s: Found unexpected block ID (%d) when reading data - expected %d\n", - progname, id, te->id); + progname, id, te->id); - switch (blkType) { + switch (blkType) + { case BLK_DATA: @@ -484,61 +507,67 @@ static void _PrintTocData(ArchiveHandle* AH, TocEntry* te, RestoreOptions *ropt) _LoadBlobs(AH); break; - default: /* Always have a default */ + default: /* Always have a default */ - die_horribly(AH, "%s: unrecognized data block type %d while restoring archive\n", - progname, blkType); + die_horribly(AH, "%s: unrecognized data block type %d while restoring archive\n", + progname, blkType); break; - } + } - ahprintf(AH, "\n\n"); + ahprintf(AH, "\n\n"); } /* * Print data from current file position. */ -static void _PrintData(ArchiveHandle* AH) +static void +_PrintData(ArchiveHandle *AH) { - lclContext* ctx = (lclContext*)AH->formatData; - z_streamp zp = ctx->zp; - int blkLen; - char* in = ctx->zlibIn; - int cnt; + lclContext *ctx = (lclContext *) AH->formatData; + z_streamp zp = ctx->zp; + int blkLen; + char *in = ctx->zlibIn; + int cnt; + #ifdef HAVE_LIBZ - int res; - char* out = ctx->zlibOut; + int res; + char *out = ctx->zlibOut; + #endif #ifdef HAVE_LIBZ - res = Z_OK; + res = Z_OK; - if (AH->compression != 0) { + if (AH->compression != 0) + { zp->zalloc = Z_NULL; zp->zfree = Z_NULL; zp->opaque = Z_NULL; if (inflateInit(zp) != Z_OK) die_horribly(AH, "%s: could not initialize compression library - %s\n", progname, zp->msg); - } + } #endif - blkLen = ReadInt(AH); - while (blkLen != 0) { - if (blkLen+1 > ctx->inSize) { + blkLen = ReadInt(AH); + while (blkLen != 0) + { + if (blkLen + 1 > ctx->inSize) + { free(ctx->zlibIn); ctx->zlibIn = NULL; - ctx->zlibIn = (char*)malloc(blkLen+1); + ctx->zlibIn = (char *) malloc(blkLen + 1); if (!ctx->zlibIn) die_horribly(AH, "%s: failed to allocate decompression buffer\n", progname); - ctx->inSize = blkLen+1; + ctx->inSize = blkLen + 1; in = ctx->zlibIn; } cnt = fread(in, 1, blkLen, AH->FH); - if (cnt != blkLen) + if (cnt != blkLen) die_horribly(AH, "%s: could not read data block - expected %d, got %d\n", progname, blkLen, cnt); ctx->filePos += blkLen; @@ -548,9 +577,11 @@ static void _PrintData(ArchiveHandle* AH) #ifdef HAVE_LIBZ - if (AH->compression != 0) { + if (AH->compression != 0) + { - while (zp->avail_in != 0) { + while (zp->avail_in != 0) + { zp->next_out = out; zp->avail_out = zlibOutSize; res = inflate(zp, 0); @@ -560,7 +591,9 @@ static void _PrintData(ArchiveHandle* AH) out[zlibOutSize - zp->avail_out] = '\0'; ahwrite(out, 1, zlibOutSize - zp->avail_out, AH); } - } else { + } + else + { #endif in[zp->avail_in] = '\0'; ahwrite(in, 1, zp->avail_in, AH); @@ -572,14 +605,15 @@ static void _PrintData(ArchiveHandle* AH) blkLen = ReadInt(AH); - } + } #ifdef HAVE_LIBZ - if (AH->compression != 0) - { + if (AH->compression != 0) + { zp->next_in = NULL; zp->avail_in = 0; - while (res != Z_STREAM_END) { + while (res != Z_STREAM_END) + { zp->next_out = out; zp->avail_out = zlibOutSize; res = inflate(zp, 0); @@ -589,25 +623,26 @@ static void _PrintData(ArchiveHandle* AH) out[zlibOutSize - zp->avail_out] = '\0'; ahwrite(out, 1, zlibOutSize - zp->avail_out, AH); } - } + } #endif } -static void _LoadBlobs(ArchiveHandle* AH) +static void +_LoadBlobs(ArchiveHandle *AH) { - int oid; + int oid; StartRestoreBlobs(AH); - oid = ReadInt(AH); - while(oid != 0) - { + oid = ReadInt(AH); + while (oid != 0) + { StartRestoreBlob(AH, oid); _PrintData(AH); EndRestoreBlob(AH, oid); oid = ReadInt(AH); - } + } EndRestoreBlobs(AH); @@ -616,49 +651,53 @@ static void _LoadBlobs(ArchiveHandle* AH) /* * Skip the BLOBs from the current file position. * BLOBS are written sequentially as data blocks (see below). - * Each BLOB is preceded by it's original OID. + * Each BLOB is preceded by it's original OID. * A zero OID indicated the end of the BLOBS */ -static void _skipBlobs(ArchiveHandle* AH) +static void +_skipBlobs(ArchiveHandle *AH) { - int oid; + int oid; - oid = ReadInt(AH); - while(oid != 0) - { + oid = ReadInt(AH); + while (oid != 0) + { _skipData(AH); oid = ReadInt(AH); - } + } } /* * Skip data from current file position. - * Data blocks are formatted as an integer length, followed by data. + * Data blocks are formatted as an integer length, followed by data. * A zero length denoted the end of the block. */ -static void _skipData(ArchiveHandle* AH) +static void +_skipData(ArchiveHandle *AH) { - lclContext* ctx = (lclContext*)AH->formatData; - int blkLen; - char* in = ctx->zlibIn; - int cnt; - - blkLen = ReadInt(AH); - while (blkLen != 0) { - if (blkLen > ctx->inSize) { - free(ctx->zlibIn); - ctx->zlibIn = (char*)malloc(blkLen); - ctx->inSize = blkLen; - in = ctx->zlibIn; - } - cnt = fread(in, 1, blkLen, AH->FH); - if (cnt != blkLen) - die_horribly(AH, "%s: could not read data block - expected %d, got %d\n", progname, blkLen, cnt); - - ctx->filePos += blkLen; + lclContext *ctx = (lclContext *) AH->formatData; + int blkLen; + char *in = ctx->zlibIn; + int cnt; blkLen = ReadInt(AH); - } + while (blkLen != 0) + { + if (blkLen > ctx->inSize) + { + free(ctx->zlibIn); + ctx->zlibIn = (char *) malloc(blkLen); + ctx->inSize = blkLen; + in = ctx->zlibIn; + } + cnt = fread(in, 1, blkLen, AH->FH); + if (cnt != blkLen) + die_horribly(AH, "%s: could not read data block - expected %d, got %d\n", progname, blkLen, cnt); + + ctx->filePos += blkLen; + + blkLen = ReadInt(AH); + } } @@ -671,18 +710,18 @@ static void _skipData(ArchiveHandle* AH) * These routines are only used to read & write headers & TOC. * */ -static int _WriteByte(ArchiveHandle* AH, const int i) +static int +_WriteByte(ArchiveHandle *AH, const int i) { - lclContext* ctx = (lclContext*)AH->formatData; - int res; + lclContext *ctx = (lclContext *) AH->formatData; + int res; - res = fputc(i, AH->FH); - if (res != EOF) { + res = fputc(i, AH->FH); + if (res != EOF) ctx->filePos += 1; - } else { - die_horribly(AH, "%s: could not write byte./n",progname); - } - return res; + else + die_horribly(AH, "%s: could not write byte./n", progname); + return res; } /* @@ -694,16 +733,16 @@ static int _WriteByte(ArchiveHandle* AH, const int i) * These routines are only used to read & write headers & TOC. * */ -static int _ReadByte(ArchiveHandle* AH) +static int +_ReadByte(ArchiveHandle *AH) { - lclContext* ctx = (lclContext*)AH->formatData; - int res; + lclContext *ctx = (lclContext *) AH->formatData; + int res; - res = fgetc(AH->FH); - if (res != EOF) { + res = fgetc(AH->FH); + if (res != EOF) ctx->filePos += 1; - } - return res; + return res; } /* @@ -715,35 +754,39 @@ static int _ReadByte(ArchiveHandle* AH) * These routines are only used to read & write headers & TOC. * */ -static int _WriteBuf(ArchiveHandle* AH, const void* buf, int len) +static int +_WriteBuf(ArchiveHandle *AH, const void *buf, int len) { - lclContext* ctx = (lclContext*)AH->formatData; - int res; - res = fwrite(buf, 1, len, AH->FH); + lclContext *ctx = (lclContext *) AH->formatData; + int res; + + res = fwrite(buf, 1, len, AH->FH); if (res != len) die_horribly(AH, "%s: write error in _WriteBuf (%d != %d)\n", progname, res, len); - ctx->filePos += res; - return res; + ctx->filePos += res; + return res; } /* * Read a block of bytes from the archive. - * + * * Mandatory. - * + * * Called by the archiver to read a block of bytes from the archive * These routines are only used to read & write headers & TOC. * */ -static int _ReadBuf(ArchiveHandle* AH, void* buf, int len) +static int +_ReadBuf(ArchiveHandle *AH, void *buf, int len) { - lclContext* ctx = (lclContext*)AH->formatData; - int res; - res = fread(buf, 1, len, AH->FH); - ctx->filePos += res; - return res; + lclContext *ctx = (lclContext *) AH->formatData; + int res; + + res = fread(buf, 1, len, AH->FH); + ctx->filePos += res; + return res; } /* @@ -751,42 +794,47 @@ static int _ReadBuf(ArchiveHandle* AH, void* buf, int len) * * Mandatory. * - * When writing the archive, this is the routine that actually starts - * the process of saving it to files. No data should be written prior + * When writing the archive, this is the routine that actually starts + * the process of saving it to files. No data should be written prior * to this point, since the user could sort the TOC after creating it. - * + * * If an archive is to be written, this toutine must call: * WriteHead to save the archive header - * WriteToc to save the TOC entries + * WriteToc to save the TOC entries * WriteDataChunks to save all DATA & BLOBs. * */ -static void _CloseArchive(ArchiveHandle* AH) +static void +_CloseArchive(ArchiveHandle *AH) { - lclContext* ctx = (lclContext*)AH->formatData; - int tpos; + lclContext *ctx = (lclContext *) AH->formatData; + int tpos; - if (AH->mode == archModeWrite) { + if (AH->mode == archModeWrite) + { WriteHead(AH); tpos = ftell(AH->FH); WriteToc(AH); ctx->dataStart = _getFilePos(AH, ctx); WriteDataChunks(AH); - /* This is not an essential operation - it is really only - * needed if we expect to be doing seeks to read the data back - * - it may be ok to just use the existing self-consistent block + + /* + * This is not an essential operation - it is really only needed + * if we expect to be doing seeks to read the data back - it may + * be ok to just use the existing self-consistent block * formatting. - */ - if (ctx->hasSeek) { + */ + if (ctx->hasSeek) + { fseek(AH->FH, tpos, SEEK_SET); WriteToc(AH); } - } + } - if (fclose(AH->FH) != 0) - die_horribly(AH, "%s: could not close archive file\n",progname); + if (fclose(AH->FH) != 0) + die_horribly(AH, "%s: could not close archive file\n", progname); - AH->FH = NULL; + AH->FH = NULL; } /*-------------------------------------------------- @@ -797,32 +845,35 @@ static void _CloseArchive(ArchiveHandle* AH) /* * Get the current position in the archive file. */ -static int _getFilePos(ArchiveHandle* AH, lclContext* ctx) +static int +_getFilePos(ArchiveHandle *AH, lclContext *ctx) { - int pos; - if (ctx->hasSeek) { + int pos; + + if (ctx->hasSeek) + { pos = ftell(AH->FH); - if (pos != ctx->filePos) { + if (pos != ctx->filePos) fprintf(stderr, "Warning: ftell mismatch with filePos\n"); - } - } else { + } + else pos = ctx->filePos; - } - return pos; + return pos; } /* - * Read a data block header. The format changed in V1.3, so we + * Read a data block header. The format changed in V1.3, so we * put the code here for simplicity. */ -static void _readBlockHeader(ArchiveHandle *AH, int *type, int *id) +static void +_readBlockHeader(ArchiveHandle *AH, int *type, int *id) { - if (AH->version < K_VERS_1_3) + if (AH->version < K_VERS_1_3) *type = BLK_DATA; - else + else *type = _ReadByte(AH);; - *id = ReadInt(AH); + *id = ReadInt(AH); } /* @@ -830,35 +881,36 @@ static void _readBlockHeader(ArchiveHandle *AH, int *type, int *id) * StartData & StartBlob. The buffers are setup in the Init routine. * */ -static void _StartDataCompressor(ArchiveHandle* AH, TocEntry* te) +static void +_StartDataCompressor(ArchiveHandle *AH, TocEntry *te) { - lclContext* ctx = (lclContext*)AH->formatData; - z_streamp zp = ctx->zp; + lclContext *ctx = (lclContext *) AH->formatData; + z_streamp zp = ctx->zp; #ifdef HAVE_LIBZ - if (AH->compression < 0 || AH->compression > 9) { + if (AH->compression < 0 || AH->compression > 9) AH->compression = Z_DEFAULT_COMPRESSION; - } - if (AH->compression != 0) { - zp->zalloc = Z_NULL; - zp->zfree = Z_NULL; - zp->opaque = Z_NULL; + if (AH->compression != 0) + { + zp->zalloc = Z_NULL; + zp->zfree = Z_NULL; + zp->opaque = Z_NULL; - if (deflateInit(zp, AH->compression) != Z_OK) - die_horribly(AH, "%s: could not initialize compression library - %s\n",progname, zp->msg); - } + if (deflateInit(zp, AH->compression) != Z_OK) + die_horribly(AH, "%s: could not initialize compression library - %s\n", progname, zp->msg); + } #else - AH->compression = 0; + AH->compression = 0; #endif - /* Just be paranoid - maybe End is called after Start, with no Write */ - zp->next_out = ctx->zlibOut; - zp->avail_out = zlibOutSize; + /* Just be paranoid - maybe End is called after Start, with no Write */ + zp->next_out = ctx->zlibOut; + zp->avail_out = zlibOutSize; } /* @@ -867,42 +919,51 @@ static void _StartDataCompressor(ArchiveHandle* AH, TocEntry* te) * In the case of Z0, or no zlib, just write the raw data. * */ -static int _DoDeflate(ArchiveHandle* AH, lclContext* ctx, int flush) +static int +_DoDeflate(ArchiveHandle *AH, lclContext *ctx, int flush) { - z_streamp zp = ctx->zp; + z_streamp zp = ctx->zp; #ifdef HAVE_LIBZ - char* out = ctx->zlibOut; - int res = Z_OK; + char *out = ctx->zlibOut; + int res = Z_OK; - if (AH->compression != 0) - { + if (AH->compression != 0) + { res = deflate(zp, flush); if (res == Z_STREAM_ERROR) - die_horribly(AH, "%s: could not compress data - %s\n",progname, zp->msg); + die_horribly(AH, "%s: could not compress data - %s\n", progname, zp->msg); - if ( ( (flush == Z_FINISH) && (zp->avail_out < zlibOutSize) ) - || (zp->avail_out == 0) + if (((flush == Z_FINISH) && (zp->avail_out < zlibOutSize)) + || (zp->avail_out == 0) || (zp->avail_in != 0) - ) + ) { + /* - * Extra paranoia: avoid zero-length chunks since a zero + * Extra paranoia: avoid zero-length chunks since a zero * length chunk is the EOF marker. This should never happen - * but... + * but... */ - if (zp->avail_out < zlibOutSize) { - /* printf("Wrote %d byte deflated chunk\n", zlibOutSize - zp->avail_out); */ + if (zp->avail_out < zlibOutSize) + { + + /* + * printf("Wrote %d byte deflated chunk\n", zlibOutSize - + * zp->avail_out); + */ WriteInt(AH, zlibOutSize - zp->avail_out); if (fwrite(out, 1, zlibOutSize - zp->avail_out, AH->FH) != (zlibOutSize - zp->avail_out)) - die_horribly(AH, "%s: could not write compressed chunk\n",progname); + die_horribly(AH, "%s: could not write compressed chunk\n", progname); ctx->filePos += zlibOutSize - zp->avail_out; } zp->next_out = out; zp->avail_out = zlibOutSize; } - } else { + } + else #endif + { if (zp->avail_in > 0) { WriteInt(AH, zp->avail_in); @@ -910,7 +971,9 @@ static int _DoDeflate(ArchiveHandle* AH, lclContext* ctx, int flush) die_horribly(AH, "%s: could not write uncompressed chunk\n", progname); ctx->filePos += zp->avail_in; zp->avail_in = 0; - } else { + } + else + { #ifdef HAVE_LIBZ if (flush == Z_FINISH) res = Z_STREAM_END; @@ -918,35 +981,37 @@ static int _DoDeflate(ArchiveHandle* AH, lclContext* ctx, int flush) } -#ifdef HAVE_LIBZ - } + } - return res; +#ifdef HAVE_LIBZ + return res; #else - return 1; + return 1; #endif } /* - * Terminate zlib context and flush it's buffers. If no zlib + * Terminate zlib context and flush it's buffers. If no zlib * then just return. * */ -static void _EndDataCompressor(ArchiveHandle* AH, TocEntry* te) +static void +_EndDataCompressor(ArchiveHandle *AH, TocEntry *te) { #ifdef HAVE_LIBZ - lclContext* ctx = (lclContext*)AH->formatData; - z_streamp zp = ctx->zp; - int res; + lclContext *ctx = (lclContext *) AH->formatData; + z_streamp zp = ctx->zp; + int res; - if (AH->compression != 0) - { + if (AH->compression != 0) + { zp->next_in = NULL; zp->avail_in = 0; - do { + do + { /* printf("Ending data output\n"); */ res = _DoDeflate(AH, ctx, Z_FINISH); } while (res != Z_STREAM_END); @@ -959,5 +1024,3 @@ static void _EndDataCompressor(ArchiveHandle* AH, TocEntry* te) /* Send the end marker */ WriteInt(AH, 0); } - - diff --git a/src/bin/pg_dump/pg_backup_db.c b/src/bin/pg_dump/pg_backup_db.c index 3e3976bc74..9b747a2572 100644 --- a/src/bin/pg_dump/pg_backup_db.c +++ b/src/bin/pg_dump/pg_backup_db.c @@ -2,16 +2,16 @@ * * pg_backup_db.c * - * Implements the basic DB functions used by the archiver. + * Implements the basic DB functions used by the archiver. * * IDENTIFICATION - * $Header: /cvsroot/pgsql/src/bin/pg_dump/pg_backup_db.c,v 1.15 2001/03/19 02:35:28 pjw Exp $ + * $Header: /cvsroot/pgsql/src/bin/pg_dump/pg_backup_db.c,v 1.16 2001/03/22 04:00:12 momjian Exp $ * * NOTES * * Modifications - 04-Jan-2001 - pjw@rhyme.com.au * - * - Check results of PQ routines more carefully. + * - Check results of PQ routines more carefully. * * Modifications - 19-Mar-2001 - pjw@rhyme.com.au * @@ -38,12 +38,12 @@ #include "strdup.h" #endif -static const char *progname = "Archiver(db)"; +static const char *progname = "Archiver(db)"; -static void _prompt_for_password(char *username, char *password); -static void _check_database_version(ArchiveHandle *AH, bool ignoreVersion); -static PGconn* _connectDB(ArchiveHandle *AH, const char* newdbname, char *newUser); -static int _executeSqlCommand(ArchiveHandle* AH, PGconn *conn, PQExpBuffer qry, char *desc); +static void _prompt_for_password(char *username, char *password); +static void _check_database_version(ArchiveHandle *AH, bool ignoreVersion); +static PGconn *_connectDB(ArchiveHandle *AH, const char *newdbname, char *newUser); +static int _executeSqlCommand(ArchiveHandle *AH, PGconn *conn, PQExpBuffer qry, char *desc); static void @@ -55,7 +55,8 @@ _prompt_for_password(char *username, char *password) #ifdef HAVE_TERMIOS_H struct termios t_orig, - t; + t; + #endif /* @@ -118,10 +119,10 @@ static void _check_database_version(ArchiveHandle *AH, bool ignoreVersion) { PGresult *res; - double myversion; + double myversion; const char *remoteversion_str; - double remoteversion; - PGconn *conn = AH->connection; + double remoteversion; + PGconn *conn = AH->connection; myversion = strtod(PG_VERSION, NULL); res = PQexec(conn, "SELECT version()"); @@ -130,7 +131,7 @@ _check_database_version(ArchiveHandle *AH, bool ignoreVersion) PQntuples(res) != 1) die_horribly(AH, "check_database_version(): command failed. " - "Explanation from backend: '%s'.\n", PQerrorMessage(conn)); + "Explanation from backend: '%s'.\n", PQerrorMessage(conn)); remoteversion_str = PQgetvalue(res, 0, 0); remoteversion = strtod(remoteversion_str + 11, NULL); @@ -142,21 +143,22 @@ _check_database_version(ArchiveHandle *AH, bool ignoreVersion) fprintf(stderr, "Proceeding despite version mismatch.\n"); else die_horribly(AH, "Aborting because of version mismatch.\n" - "Use --ignore-version if you think it's safe to proceed anyway.\n"); + "Use --ignore-version if you think it's safe to proceed anyway.\n"); } PQclear(res); } -/* +/* * Check if a given user is a superuser. */ -int UserIsSuperuser(ArchiveHandle *AH, char* user) +int +UserIsSuperuser(ArchiveHandle *AH, char *user) { - PQExpBuffer qry = createPQExpBuffer(); - PGresult *res; - int i_usesuper; - int ntups; - int isSuper; + PQExpBuffer qry = createPQExpBuffer(); + PGresult *res; + int i_usesuper; + int ntups; + int isSuper; /* Get the superuser setting */ appendPQExpBuffer(qry, "select usesuper from pg_user where usename = '%s'", user); @@ -164,11 +166,11 @@ int UserIsSuperuser(ArchiveHandle *AH, char* user) if (!res) die_horribly(AH, "%s: null result checking superuser status of %s.\n", - progname, user); + progname, user); if (PQresultStatus(res) != PGRES_TUPLES_OK) die_horribly(AH, "%s: Could not check superuser status of %s. Explanation from backend: %s\n", - progname, user, PQerrorMessage(AH->connection)); + progname, user, PQerrorMessage(AH->connection)); ntups = PQntuples(res); @@ -184,28 +186,31 @@ int UserIsSuperuser(ArchiveHandle *AH, char* user) return isSuper; } -int ConnectedUserIsSuperuser(ArchiveHandle *AH) +int +ConnectedUserIsSuperuser(ArchiveHandle *AH) { return UserIsSuperuser(AH, PQuser(AH->connection)); } -char* ConnectedUser(ArchiveHandle *AH) +char * +ConnectedUser(ArchiveHandle *AH) { return PQuser(AH->connection); } /* - * Reconnect the DB associated with the archive handle + * Reconnect the DB associated with the archive handle */ -int ReconnectDatabase(ArchiveHandle *AH, const char* newdbname, char *newUser) +int +ReconnectDatabase(ArchiveHandle *AH, const char *newdbname, char *newUser) { - PGconn *newConn; - char *dbname; + PGconn *newConn; + char *dbname; - if (!newdbname || (strcmp(newdbname, "-") == 0) ) + if (!newdbname || (strcmp(newdbname, "-") == 0)) dbname = PQdb(AH->connection); else - dbname = (char*)newdbname; + dbname = (char *) newdbname; /* Let's see if the request is already satisfied */ if (strcmp(PQuser(AH->connection), newUser) == 0 && strcmp(newdbname, PQdb(AH->connection)) == 0) @@ -223,26 +228,27 @@ int ReconnectDatabase(ArchiveHandle *AH, const char* newdbname, char *newUser) /* * Connect to the db again. */ -static PGconn* _connectDB(ArchiveHandle *AH, const char* reqdb, char *requser) +static PGconn * +_connectDB(ArchiveHandle *AH, const char *reqdb, char *requser) { int need_pass; - PGconn *newConn; + PGconn *newConn; char password[100]; - char *pwparam = NULL; + char *pwparam = NULL; int badPwd = 0; int noPwd = 0; - char *newdb; - char *newuser; + char *newdb; + char *newuser; - if (!reqdb || (strcmp(reqdb, "-") == 0) ) + if (!reqdb || (strcmp(reqdb, "-") == 0)) newdb = PQdb(AH->connection); else - newdb = (char*)reqdb; + newdb = (char *) reqdb; if (!requser || (strlen(requser) == 0)) newuser = PQuser(AH->connection); else - newuser = (char*)requser; + newuser = (char *) requser; ahlog(AH, 1, "Connecting to %s as %s\n", newdb, newuser); @@ -250,8 +256,8 @@ static PGconn* _connectDB(ArchiveHandle *AH, const char* reqdb, char *requser) { need_pass = false; newConn = PQsetdbLogin(PQhost(AH->connection), PQport(AH->connection), - NULL, NULL, newdb, - newuser, pwparam); + NULL, NULL, newdb, + newuser, pwparam); if (!newConn) die_horribly(AH, "%s: Failed to reconnect (PQsetdbLogin failed).\n", progname); @@ -259,9 +265,9 @@ static PGconn* _connectDB(ArchiveHandle *AH, const char* reqdb, char *requser) { noPwd = (strcmp(PQerrorMessage(newConn), "fe_sendauth: no password supplied\n") == 0); badPwd = (strncmp(PQerrorMessage(newConn), "Password authentication failed for user", 39) - == 0); + == 0); - if (noPwd || badPwd) + if (noPwd || badPwd) { if (badPwd) @@ -271,7 +277,7 @@ static PGconn* _connectDB(ArchiveHandle *AH, const char* reqdb, char *requser) need_pass = true; _prompt_for_password(newuser, password); - pwparam = password; + pwparam = password; } else die_horribly(AH, "%s: Could not reconnect. %s\n", progname, PQerrorMessage(newConn)); @@ -283,22 +289,23 @@ static PGconn* _connectDB(ArchiveHandle *AH, const char* reqdb, char *requser) } -PGconn* ConnectDatabase(Archive *AHX, - const char* dbname, - const char* pghost, - const char* pgport, - const int reqPwd, - const int ignoreVersion) +PGconn * +ConnectDatabase(Archive *AHX, + const char *dbname, + const char *pghost, + const char *pgport, + const int reqPwd, + const int ignoreVersion) { - ArchiveHandle *AH = (ArchiveHandle*)AHX; - char connect_string[512] = ""; - char tmp_string[128]; - char password[100]; + ArchiveHandle *AH = (ArchiveHandle *) AHX; + char connect_string[512] = ""; + char tmp_string[128]; + char password[100]; if (AH->connection) die_horribly(AH, "%s: already connected to database\n", progname); - if (!dbname && !(dbname = getenv("PGDATABASE")) ) + if (!dbname && !(dbname = getenv("PGDATABASE"))) die_horribly(AH, "%s: no database name specified\n", progname); AH->dbname = strdup(dbname); @@ -310,7 +317,7 @@ PGconn* ConnectDatabase(Archive *AHX, strcat(connect_string, tmp_string); } else - AH->pghost = NULL; + AH->pghost = NULL; if (pgport != NULL) { @@ -319,7 +326,7 @@ PGconn* ConnectDatabase(Archive *AHX, strcat(connect_string, tmp_string); } else - AH->pgport = NULL; + AH->pgport = NULL; sprintf(tmp_string, "dbname=%s ", AH->dbname); strcat(connect_string, tmp_string); @@ -342,16 +349,16 @@ PGconn* ConnectDatabase(Archive *AHX, /* check to see that the backend connection was successfully made */ if (PQstatus(AH->connection) == CONNECTION_BAD) die_horribly(AH, "Connection to database '%s' failed.\n%s\n", - AH->dbname, PQerrorMessage(AH->connection)); + AH->dbname, PQerrorMessage(AH->connection)); /* check for version mismatch */ _check_database_version(AH, ignoreVersion); /* - * AH->currUser = PQuser(AH->connection); - * - * Removed because it prevented an initial \connect - * when dumping to SQL in pg_dump. + * AH->currUser = PQuser(AH->connection); + * + * Removed because it prevented an initial \connect when dumping to SQL + * in pg_dump. */ return AH->connection; @@ -359,26 +366,28 @@ PGconn* ConnectDatabase(Archive *AHX, /* Public interface */ /* Convenience function to send a query. Monitors result to handle COPY statements */ -int ExecuteSqlCommand(ArchiveHandle* AH, PQExpBuffer qry, char *desc) +int +ExecuteSqlCommand(ArchiveHandle *AH, PQExpBuffer qry, char *desc) { return _executeSqlCommand(AH, AH->connection, qry, desc); } -/* +/* * Handle command execution. This is used to execute a command on more than one connection, * but the 'pgCopyIn' setting assumes the COPY commands are ONLY executed on the primary * setting...an error will be raised otherwise. */ -static int _executeSqlCommand(ArchiveHandle* AH, PGconn *conn, PQExpBuffer qry, char *desc) +static int +_executeSqlCommand(ArchiveHandle *AH, PGconn *conn, PQExpBuffer qry, char *desc) { - PGresult *res; + PGresult *res; /* fprintf(stderr, "Executing: '%s'\n\n", qry->data); */ res = PQexec(conn, qry->data); if (!res) die_horribly(AH, "%s: %s. No result from backend.\n", progname, desc); - if (PQresultStatus(res) != PGRES_COMMAND_OK && PQresultStatus(res) != PGRES_TUPLES_OK) + if (PQresultStatus(res) != PGRES_COMMAND_OK && PQresultStatus(res) != PGRES_TUPLES_OK) { if (PQresultStatus(res) == PGRES_COPY_IN) { @@ -387,9 +396,9 @@ static int _executeSqlCommand(ArchiveHandle* AH, PGconn *conn, PQExpBuffer qry, AH->pgCopyIn = 1; } - else + else die_horribly(AH, "%s: %s. Code = %d. Explanation from backend: '%s'.\n", - progname, desc, PQresultStatus(res), PQerrorMessage(AH->connection)); + progname, desc, PQresultStatus(res), PQerrorMessage(AH->connection)); } PQclear(res); @@ -398,42 +407,52 @@ static int _executeSqlCommand(ArchiveHandle* AH, PGconn *conn, PQExpBuffer qry, } /* Convenience function to send one or more queries. Monitors result to handle COPY statements */ -int ExecuteSqlCommandBuf(ArchiveHandle* AH, void *qryv, int bufLen) +int +ExecuteSqlCommandBuf(ArchiveHandle *AH, void *qryv, int bufLen) { - int loc; - int pos = 0; - int sPos = 0; - char *qry = (char*)qryv; - int isEnd = 0; - char *eos = qry + bufLen; + int loc; + int pos = 0; + int sPos = 0; + char *qry = (char *) qryv; + int isEnd = 0; + char *eos = qry + bufLen; - /* fprintf(stderr, "\n\n*****\n Buffer:\n\n%s\n*******************\n\n", qry); */ + /* + * fprintf(stderr, "\n\n*****\n + * Buffer:\n\n%s\n*******************\n\n", qry); + */ /* If we're in COPY IN mode, then just break it into lines and send... */ - if (AH->pgCopyIn) { - for(;;) { + if (AH->pgCopyIn) + { + for (;;) + { /* Find a lf */ loc = strcspn(&qry[pos], "\n") + pos; pos = 0; /* If no match, then wait */ - if (loc >= (eos - qry)) /* None found */ + if (loc >= (eos - qry)) /* None found */ { appendBinaryPQExpBuffer(AH->pgCopyBuf, qry, (eos - qry)); break; }; - /* fprintf(stderr, "Found cr at %d, prev char was %c, next was %c\n", loc, qry[loc-1], qry[loc+1]); */ - + /* + * fprintf(stderr, "Found cr at %d, prev char was %c, next was + * %c\n", loc, qry[loc-1], qry[loc+1]); + */ + /* Count the number of preceding slashes */ sPos = loc; - while (sPos > 0 && qry[sPos-1] == '\\') + while (sPos > 0 && qry[sPos - 1] == '\\') sPos--; sPos = loc - sPos; - /* If an odd number of preceding slashes, then \n was escaped + /* + * If an odd number of preceding slashes, then \n was escaped * so set the next search pos, and restart (if any left). */ if ((sPos & 1) == 1) @@ -451,19 +470,26 @@ int ExecuteSqlCommandBuf(ArchiveHandle* AH, void *qryv, int bufLen) /* We got a good cr */ qry[loc] = '\0'; appendPQExpBuffer(AH->pgCopyBuf, "%s\n", qry); - qry += loc + 1; + qry += loc + 1; isEnd = (strcmp(AH->pgCopyBuf->data, "\\.\n") == 0); - /* fprintf(stderr, "Sending '%s' via COPY (at end = %d)\n\n", AH->pgCopyBuf->data, isEnd); */ - + /* + * fprintf(stderr, "Sending '%s' via COPY (at end = + * %d)\n\n", AH->pgCopyBuf->data, isEnd); + */ + if (PQputline(AH->connection, AH->pgCopyBuf->data) != 0) die_horribly(AH, "%s: error returned by PQputline\n", progname); resetPQExpBuffer(AH->pgCopyBuf); - /* fprintf(stderr, "Buffer is '%s'\n", AH->pgCopyBuf->data); */ + /* + * fprintf(stderr, "Buffer is '%s'\n", + * AH->pgCopyBuf->data); + */ - if(isEnd) { + if (isEnd) + { if (PQendcopy(AH->connection) != 0) die_horribly(AH, "%s: error returned by PQendcopy\n", progname); @@ -481,58 +507,60 @@ int ExecuteSqlCommandBuf(ArchiveHandle* AH, void *qryv, int bufLen) } /* We may have finished Copy In, and have a non-empty buffer */ - if (!AH->pgCopyIn) { + if (!AH->pgCopyIn) + { - /* - * The following is a mini state machine to assess then of of an SQL statement. - * It really only needs to parse good SQL, or at least that's the theory... - * End-of-statement is assumed to be an unquoted, un commented semi-colon. + /* + * The following is a mini state machine to assess then of of an + * SQL statement. It really only needs to parse good SQL, or at + * least that's the theory... End-of-statement is assumed to be an + * unquoted, un commented semi-colon. */ - /* fprintf(stderr, "Buffer at start is: '%s'\n\n", AH->sqlBuf->data); */ + /* + * fprintf(stderr, "Buffer at start is: '%s'\n\n", + * AH->sqlBuf->data); + */ - for(pos=0; pos < (eos - qry); pos++) + for (pos = 0; pos < (eos - qry); pos++) { appendPQExpBufferChar(AH->sqlBuf, qry[pos]); /* fprintf(stderr, " %c",qry[pos]); */ - switch (AH->sqlparse.state) { + switch (AH->sqlparse.state) + { - case SQL_SCAN: /* Default state == 0, set in _allocAH */ + case SQL_SCAN: /* Default state == 0, set in _allocAH */ if (qry[pos] == ';' && AH->sqlparse.braceDepth == 0) { /* Send It & reset the buffer */ - /* fprintf(stderr, " sending: '%s'\n\n", AH->sqlBuf->data); */ + + /* + * fprintf(stderr, " sending: '%s'\n\n", + * AH->sqlBuf->data); + */ ExecuteSqlCommand(AH, AH->sqlBuf, "Could not execute query"); resetPQExpBuffer(AH->sqlBuf); AH->sqlparse.lastChar = '\0'; - } - else + } + else { if (qry[pos] == '"' || qry[pos] == '\'') - { + { /* fprintf(stderr,"[startquote]\n"); */ AH->sqlparse.state = SQL_IN_QUOTE; AH->sqlparse.quoteChar = qry[pos]; AH->sqlparse.backSlash = 0; - } + } else if (qry[pos] == '-' && AH->sqlparse.lastChar == '-') - { AH->sqlparse.state = SQL_IN_SQL_COMMENT; - } else if (qry[pos] == '*' && AH->sqlparse.lastChar == '/') - { AH->sqlparse.state = SQL_IN_EXT_COMMENT; - } - else if ( qry[pos] == '(' ) - { + else if (qry[pos] == '(') AH->sqlparse.braceDepth++; - } else if (qry[pos] == ')') - { AH->sqlparse.braceDepth--; - } AH->sqlparse.lastChar = qry[pos]; } @@ -557,8 +585,8 @@ int ExecuteSqlCommandBuf(ArchiveHandle* AH, void *qryv, int bufLen) { /* fprintf(stderr,"[endquote]\n"); */ AH->sqlparse.state = SQL_SCAN; - } - else + } + else { if (qry[pos] == '\\') @@ -567,9 +595,9 @@ int ExecuteSqlCommandBuf(ArchiveHandle* AH, void *qryv, int bufLen) AH->sqlparse.backSlash = !AH->sqlparse.backSlash; else AH->sqlparse.backSlash = 1; - } else { - AH->sqlparse.backSlash = 0; } + else + AH->sqlparse.backSlash = 0; } break; @@ -583,33 +611,37 @@ int ExecuteSqlCommandBuf(ArchiveHandle* AH, void *qryv, int bufLen) return 1; } -void FixupBlobRefs(ArchiveHandle *AH, char *tablename) +void +FixupBlobRefs(ArchiveHandle *AH, char *tablename) { - PQExpBuffer tblQry = createPQExpBuffer(); - PGresult *res, *uRes; - int i, n; - char *attr; + PQExpBuffer tblQry = createPQExpBuffer(); + PGresult *res, + *uRes; + int i, + n; + char *attr; if (strcmp(tablename, BLOB_XREF_TABLE) == 0) return; appendPQExpBuffer(tblQry, "SELECT a.attname FROM pg_class c, pg_attribute a, pg_type t " - " WHERE a.attnum > 0 AND a.attrelid = c.oid AND a.atttypid = t.oid " - " AND t.typname = 'oid' AND c.relname = '%s';", tablename); + " WHERE a.attnum > 0 AND a.attrelid = c.oid AND a.atttypid = t.oid " + " AND t.typname = 'oid' AND c.relname = '%s';", tablename); res = PQexec(AH->blobConnection, tblQry->data); if (!res) die_horribly(AH, "%s: could not find OID attrs of %s. Explanation from backend '%s'\n", - progname, tablename, PQerrorMessage(AH->connection)); + progname, tablename, PQerrorMessage(AH->connection)); - if ((n = PQntuples(res)) == 0) { + if ((n = PQntuples(res)) == 0) + { /* We're done */ ahlog(AH, 1, "No OID attributes in table %s\n", tablename); PQclear(res); return; } - for (i = 0 ; i < n ; i++) + for (i = 0; i < n; i++) { attr = PQgetvalue(res, i, 0); @@ -618,28 +650,28 @@ void FixupBlobRefs(ArchiveHandle *AH, char *tablename) resetPQExpBuffer(tblQry); /* - * We should use coalesce here (rather than 'exists'), but it seems to - * be broken in 7.0.2 (weird optimizer strategy) + * We should use coalesce here (rather than 'exists'), but it + * seems to be broken in 7.0.2 (weird optimizer strategy) */ - appendPQExpBuffer(tblQry, "UPDATE \"%s\" SET \"%s\" = ",tablename, attr); + appendPQExpBuffer(tblQry, "UPDATE \"%s\" SET \"%s\" = ", tablename, attr); appendPQExpBuffer(tblQry, " (SELECT x.newOid FROM \"%s\" x WHERE x.oldOid = \"%s\".\"%s\")", - BLOB_XREF_TABLE, tablename, attr); + BLOB_XREF_TABLE, tablename, attr); appendPQExpBuffer(tblQry, " where exists" - "(select * from %s x where x.oldOid = \"%s\".\"%s\");", - BLOB_XREF_TABLE, tablename, attr); + "(select * from %s x where x.oldOid = \"%s\".\"%s\");", + BLOB_XREF_TABLE, tablename, attr); ahlog(AH, 10, " - sql:\n%s\n", tblQry->data); uRes = PQexec(AH->blobConnection, tblQry->data); if (!uRes) die_horribly(AH, "%s: could not update attr %s of table %s. Explanation from backend '%s'\n", - progname, attr, tablename, PQerrorMessage(AH->blobConnection)); + progname, attr, tablename, PQerrorMessage(AH->blobConnection)); - if ( PQresultStatus(uRes) != PGRES_COMMAND_OK ) + if (PQresultStatus(uRes) != PGRES_COMMAND_OK) die_horribly(AH, "%s: error while updating attr %s of table %s (result = %d)." - " Explanation from backend '%s'\n", - progname, attr, tablename, PQresultStatus(uRes), - PQerrorMessage(AH->blobConnection)); + " Explanation from backend '%s'\n", + progname, attr, tablename, PQresultStatus(uRes), + PQerrorMessage(AH->blobConnection)); PQclear(uRes); } @@ -651,15 +683,14 @@ void FixupBlobRefs(ArchiveHandle *AH, char *tablename) /********** * Convenient SQL calls **********/ -void CreateBlobXrefTable(ArchiveHandle* AH) +void +CreateBlobXrefTable(ArchiveHandle *AH) { - PQExpBuffer qry = createPQExpBuffer(); + PQExpBuffer qry = createPQExpBuffer(); /* IF we don't have a BLOB connection, then create one */ if (!AH->blobConnection) - { AH->blobConnection = _connectDB(AH, NULL, NULL); - } ahlog(AH, 1, "Creating table for BLOBS xrefs\n"); @@ -673,18 +704,20 @@ void CreateBlobXrefTable(ArchiveHandle* AH) _executeSqlCommand(AH, AH->blobConnection, qry, "can not create index on BLOB xref table '" BLOB_XREF_TABLE "'"); } -void InsertBlobXref(ArchiveHandle* AH, int old, int new) +void +InsertBlobXref(ArchiveHandle *AH, int old, int new) { - PQExpBuffer qry = createPQExpBuffer(); + PQExpBuffer qry = createPQExpBuffer(); appendPQExpBuffer(qry, "Insert Into %s(oldOid, newOid) Values (%d, %d);", BLOB_XREF_TABLE, old, new); _executeSqlCommand(AH, AH->blobConnection, qry, "can not create BLOB xref entry"); } -void StartTransaction(ArchiveHandle* AH) +void +StartTransaction(ArchiveHandle *AH) { - PQExpBuffer qry = createPQExpBuffer(); + PQExpBuffer qry = createPQExpBuffer(); appendPQExpBuffer(qry, "Begin;"); @@ -692,9 +725,10 @@ void StartTransaction(ArchiveHandle* AH) AH->txActive = true; } -void StartTransactionXref(ArchiveHandle* AH) +void +StartTransactionXref(ArchiveHandle *AH) { - PQExpBuffer qry = createPQExpBuffer(); + PQExpBuffer qry = createPQExpBuffer(); appendPQExpBuffer(qry, "Begin;"); @@ -702,19 +736,21 @@ void StartTransactionXref(ArchiveHandle* AH) AH->blobTxActive = true; } -void CommitTransaction(ArchiveHandle* AH) +void +CommitTransaction(ArchiveHandle *AH) { - PQExpBuffer qry = createPQExpBuffer(); + PQExpBuffer qry = createPQExpBuffer(); - appendPQExpBuffer(qry, "Commit;"); + appendPQExpBuffer(qry, "Commit;"); - ExecuteSqlCommand(AH, qry, "can not commit database transaction"); + ExecuteSqlCommand(AH, qry, "can not commit database transaction"); AH->txActive = false; } -void CommitTransactionXref(ArchiveHandle* AH) +void +CommitTransactionXref(ArchiveHandle *AH) { - PQExpBuffer qry = createPQExpBuffer(); + PQExpBuffer qry = createPQExpBuffer(); appendPQExpBuffer(qry, "Commit;"); diff --git a/src/bin/pg_dump/pg_backup_db.h b/src/bin/pg_dump/pg_backup_db.h index d7903d2bcd..44500e72c1 100644 --- a/src/bin/pg_dump/pg_backup_db.h +++ b/src/bin/pg_dump/pg_backup_db.h @@ -2,19 +2,18 @@ * Definitions for pg_backup_db.c * * IDENTIFICATION - * $Header: /cvsroot/pgsql/src/bin/pg_dump/pg_backup_db.h,v 1.3 2001/03/19 02:35:28 pjw Exp $ + * $Header: /cvsroot/pgsql/src/bin/pg_dump/pg_backup_db.h,v 1.4 2001/03/22 04:00:13 momjian Exp $ */ -#define BLOB_XREF_TABLE "dump_blob_xref" /* MUST be lower case */ +#define BLOB_XREF_TABLE "dump_blob_xref" /* MUST be lower case */ extern void FixupBlobRefs(ArchiveHandle *AH, char *tablename); -extern int ExecuteSqlCommand(ArchiveHandle* AH, PQExpBuffer qry, char *desc); -extern int ExecuteSqlCommandBuf(ArchiveHandle* AH, void *qry, int bufLen); - -extern void CreateBlobXrefTable(ArchiveHandle* AH); -extern void InsertBlobXref(ArchiveHandle* AH, int old, int new); -extern void StartTransaction(ArchiveHandle* AH); -extern void StartTransactionXref(ArchiveHandle* AH); -extern void CommitTransaction(ArchiveHandle* AH); -extern void CommitTransactionXref(ArchiveHandle* AH); +extern int ExecuteSqlCommand(ArchiveHandle *AH, PQExpBuffer qry, char *desc); +extern int ExecuteSqlCommandBuf(ArchiveHandle *AH, void *qry, int bufLen); +extern void CreateBlobXrefTable(ArchiveHandle *AH); +extern void InsertBlobXref(ArchiveHandle *AH, int old, int new); +extern void StartTransaction(ArchiveHandle *AH); +extern void StartTransactionXref(ArchiveHandle *AH); +extern void CommitTransaction(ArchiveHandle *AH); +extern void CommitTransactionXref(ArchiveHandle *AH); diff --git a/src/bin/pg_dump/pg_backup_files.c b/src/bin/pg_dump/pg_backup_files.c index d4746a966a..9a5a7797a1 100644 --- a/src/bin/pg_dump/pg_backup_files.c +++ b/src/bin/pg_dump/pg_backup_files.c @@ -12,23 +12,23 @@ * See the headers to pg_restore for more details. * * Copyright (c) 2000, Philip Warner - * Rights are granted to use this software in any way so long - * as this notice is not removed. + * Rights are granted to use this software in any way so long + * as this notice is not removed. * * The author is not responsible for loss or damages that may * result from it's use. * * * IDENTIFICATION - * $Header: /cvsroot/pgsql/src/bin/pg_dump/pg_backup_files.c,v 1.7 2001/03/19 02:35:28 pjw Exp $ + * $Header: /cvsroot/pgsql/src/bin/pg_dump/pg_backup_files.c,v 1.8 2001/03/22 04:00:13 momjian Exp $ * * Modifications - 28-Jun-2000 - pjw@rhyme.com.au * - * Initial version. + * Initial version. * * Modifications - 04-Jan-2001 - pjw@rhyme.com.au * - * - Check results of IO routines more carefully. + * - Check results of IO routines more carefully. * *------------------------------------------------------------------------- */ @@ -39,114 +39,117 @@ #include <stdlib.h> #include <string.h> -static void _ArchiveEntry(ArchiveHandle* AH, TocEntry* te); -static void _StartData(ArchiveHandle* AH, TocEntry* te); -static int _WriteData(ArchiveHandle* AH, const void* data, int dLen); -static void _EndData(ArchiveHandle* AH, TocEntry* te); -static int _WriteByte(ArchiveHandle* AH, const int i); -static int _ReadByte(ArchiveHandle* ); -static int _WriteBuf(ArchiveHandle* AH, const void* buf, int len); -static int _ReadBuf(ArchiveHandle* AH, void* buf, int len); -static void _CloseArchive(ArchiveHandle* AH); -static void _PrintTocData(ArchiveHandle* AH, TocEntry* te, RestoreOptions *ropt); -static void _WriteExtraToc(ArchiveHandle* AH, TocEntry* te); -static void _ReadExtraToc(ArchiveHandle* AH, TocEntry* te); -static void _PrintExtraToc(ArchiveHandle* AH, TocEntry* te); - -static void _StartBlobs(ArchiveHandle* AH, TocEntry* te); -static void _StartBlob(ArchiveHandle* AH, TocEntry* te, int oid); -static void _EndBlob(ArchiveHandle* AH, TocEntry* te, int oid); -static void _EndBlobs(ArchiveHandle* AH, TocEntry* te); +static void _ArchiveEntry(ArchiveHandle *AH, TocEntry *te); +static void _StartData(ArchiveHandle *AH, TocEntry *te); +static int _WriteData(ArchiveHandle *AH, const void *data, int dLen); +static void _EndData(ArchiveHandle *AH, TocEntry *te); +static int _WriteByte(ArchiveHandle *AH, const int i); +static int _ReadByte(ArchiveHandle *); +static int _WriteBuf(ArchiveHandle *AH, const void *buf, int len); +static int _ReadBuf(ArchiveHandle *AH, void *buf, int len); +static void _CloseArchive(ArchiveHandle *AH); +static void _PrintTocData(ArchiveHandle *AH, TocEntry *te, RestoreOptions *ropt); +static void _WriteExtraToc(ArchiveHandle *AH, TocEntry *te); +static void _ReadExtraToc(ArchiveHandle *AH, TocEntry *te); +static void _PrintExtraToc(ArchiveHandle *AH, TocEntry *te); + +static void _StartBlobs(ArchiveHandle *AH, TocEntry *te); +static void _StartBlob(ArchiveHandle *AH, TocEntry *te, int oid); +static void _EndBlob(ArchiveHandle *AH, TocEntry *te, int oid); +static void _EndBlobs(ArchiveHandle *AH, TocEntry *te); #define K_STD_BUF_SIZE 1024 -typedef struct { - int hasSeek; - int filePos; - FILE *blobToc; +typedef struct +{ + int hasSeek; + int filePos; + FILE *blobToc; } lclContext; -typedef struct { +typedef struct +{ #ifdef HAVE_LIBZ - gzFile *FH; + gzFile *FH; #else - FILE *FH; + FILE *FH; #endif - char *filename; + char *filename; } lclTocEntry; -static char* progname = "Archiver(files)"; -static void _LoadBlobs(ArchiveHandle* AH, RestoreOptions *ropt); -static void _getBlobTocEntry(ArchiveHandle* AH, int *oid, char *fname); +static char *progname = "Archiver(files)"; +static void _LoadBlobs(ArchiveHandle *AH, RestoreOptions *ropt); +static void _getBlobTocEntry(ArchiveHandle *AH, int *oid, char *fname); /* - * Initializer + * Initializer */ -void InitArchiveFmt_Files(ArchiveHandle* AH) +void +InitArchiveFmt_Files(ArchiveHandle *AH) { - lclContext* ctx; - - /* Assuming static functions, this can be copied for each format. */ - AH->ArchiveEntryPtr = _ArchiveEntry; - AH->StartDataPtr = _StartData; - AH->WriteDataPtr = _WriteData; - AH->EndDataPtr = _EndData; - AH->WriteBytePtr = _WriteByte; - AH->ReadBytePtr = _ReadByte; - AH->WriteBufPtr = _WriteBuf; - AH->ReadBufPtr = _ReadBuf; - AH->ClosePtr = _CloseArchive; - AH->PrintTocDataPtr = _PrintTocData; - AH->ReadExtraTocPtr = _ReadExtraToc; - AH->WriteExtraTocPtr = _WriteExtraToc; - AH->PrintExtraTocPtr = _PrintExtraToc; - - AH->StartBlobsPtr = _StartBlobs; - AH->StartBlobPtr = _StartBlob; - AH->EndBlobPtr = _EndBlob; - AH->EndBlobsPtr = _EndBlobs; - - /* - * Set up some special context used in compressing data. - */ - ctx = (lclContext*)malloc(sizeof(lclContext)); - AH->formatData = (void*)ctx; - ctx->filePos = 0; - - /* - * Now open the TOC file - */ - if (AH->mode == archModeWrite) { + lclContext *ctx; + + /* Assuming static functions, this can be copied for each format. */ + AH->ArchiveEntryPtr = _ArchiveEntry; + AH->StartDataPtr = _StartData; + AH->WriteDataPtr = _WriteData; + AH->EndDataPtr = _EndData; + AH->WriteBytePtr = _WriteByte; + AH->ReadBytePtr = _ReadByte; + AH->WriteBufPtr = _WriteBuf; + AH->ReadBufPtr = _ReadBuf; + AH->ClosePtr = _CloseArchive; + AH->PrintTocDataPtr = _PrintTocData; + AH->ReadExtraTocPtr = _ReadExtraToc; + AH->WriteExtraTocPtr = _WriteExtraToc; + AH->PrintExtraTocPtr = _PrintExtraToc; + + AH->StartBlobsPtr = _StartBlobs; + AH->StartBlobPtr = _StartBlob; + AH->EndBlobPtr = _EndBlob; + AH->EndBlobsPtr = _EndBlobs; + + /* + * Set up some special context used in compressing data. + */ + ctx = (lclContext *) malloc(sizeof(lclContext)); + AH->formatData = (void *) ctx; + ctx->filePos = 0; + + /* + * Now open the TOC file + */ + if (AH->mode == archModeWrite) + { fprintf(stderr, "\n*************************************************************\n" - "* WARNING: This format is for demonstration purposes. It is *\n" - "* not intended for general use. Files will be dumped *\n" - "* into the current working directory. *\n" - "***************************************************************\n\n"); + "* WARNING: This format is for demonstration purposes. It is *\n" + "* not intended for general use. Files will be dumped *\n" + "* into the current working directory. *\n" + "***************************************************************\n\n"); - if (AH->fSpec && strcmp(AH->fSpec,"") != 0) { + if (AH->fSpec && strcmp(AH->fSpec, "") != 0) AH->FH = fopen(AH->fSpec, PG_BINARY_W); - } else { + else AH->FH = stdout; - } if (AH->FH == NULL) die_horribly(NULL, "%s: Could not open output file\n", progname); ctx->hasSeek = (fseek(AH->FH, 0, SEEK_CUR) == 0); - if (AH->compression < 0 || AH->compression > 9) { + if (AH->compression < 0 || AH->compression > 9) AH->compression = Z_DEFAULT_COMPRESSION; - } - } else { /* Read Mode */ + } + else + { /* Read Mode */ - if (AH->fSpec && strcmp(AH->fSpec,"") != 0) { + if (AH->fSpec && strcmp(AH->fSpec, "") != 0) AH->FH = fopen(AH->fSpec, PG_BINARY_R); - } else { + else AH->FH = stdin; - } if (AH->FH == NULL) die_horribly(NULL, "%s: Could not open input file\n", progname); @@ -155,85 +158,93 @@ void InitArchiveFmt_Files(ArchiveHandle* AH) ReadHead(AH); ReadToc(AH); - fclose(AH->FH); /* Nothing else in the file... */ - } + fclose(AH->FH); /* Nothing else in the file... */ + } } /* * - Start a new TOC entry - * Setup the output file name. + * Setup the output file name. */ -static void _ArchiveEntry(ArchiveHandle* AH, TocEntry* te) +static void +_ArchiveEntry(ArchiveHandle *AH, TocEntry *te) { - lclTocEntry* ctx; - char fn[K_STD_BUF_SIZE]; + lclTocEntry *ctx; + char fn[K_STD_BUF_SIZE]; - ctx = (lclTocEntry*)malloc(sizeof(lclTocEntry)); - if (te->dataDumper) { + ctx = (lclTocEntry *) malloc(sizeof(lclTocEntry)); + if (te->dataDumper) + { #ifdef HAVE_LIBZ - if (AH->compression == 0) { + if (AH->compression == 0) sprintf(fn, "%d.dat", te->id); - } else { + else sprintf(fn, "%d.dat.gz", te->id); - } #else sprintf(fn, "%d.dat", te->id); #endif ctx->filename = strdup(fn); - } else { + } + else + { ctx->filename = NULL; ctx->FH = NULL; - } - te->formatData = (void*)ctx; + } + te->formatData = (void *) ctx; } -static void _WriteExtraToc(ArchiveHandle* AH, TocEntry* te) +static void +_WriteExtraToc(ArchiveHandle *AH, TocEntry *te) { - lclTocEntry* ctx = (lclTocEntry*)te->formatData; + lclTocEntry *ctx = (lclTocEntry *) te->formatData; - if (ctx->filename) { + if (ctx->filename) WriteStr(AH, ctx->filename); - } else { + else WriteStr(AH, ""); - } } -static void _ReadExtraToc(ArchiveHandle* AH, TocEntry* te) +static void +_ReadExtraToc(ArchiveHandle *AH, TocEntry *te) { - lclTocEntry* ctx = (lclTocEntry*)te->formatData; + lclTocEntry *ctx = (lclTocEntry *) te->formatData; - if (ctx == NULL) { - ctx = (lclTocEntry*)malloc(sizeof(lclTocEntry)); - te->formatData = (void*)ctx; - } + if (ctx == NULL) + { + ctx = (lclTocEntry *) malloc(sizeof(lclTocEntry)); + te->formatData = (void *) ctx; + } - ctx->filename = ReadStr(AH); - if (strlen(ctx->filename) == 0) { + ctx->filename = ReadStr(AH); + if (strlen(ctx->filename) == 0) + { free(ctx->filename); ctx->filename = NULL; - } - ctx->FH = NULL; + } + ctx->FH = NULL; } -static void _PrintExtraToc(ArchiveHandle* AH, TocEntry* te) +static void +_PrintExtraToc(ArchiveHandle *AH, TocEntry *te) { - lclTocEntry* ctx = (lclTocEntry*)te->formatData; + lclTocEntry *ctx = (lclTocEntry *) te->formatData; - ahprintf(AH, "-- File: %s\n", ctx->filename); + ahprintf(AH, "-- File: %s\n", ctx->filename); } -static void _StartData(ArchiveHandle* AH, TocEntry* te) +static void +_StartData(ArchiveHandle *AH, TocEntry *te) { - lclTocEntry* tctx = (lclTocEntry*)te->formatData; - char fmode[10]; + lclTocEntry *tctx = (lclTocEntry *) te->formatData; + char fmode[10]; - sprintf(fmode, "wb%d", AH->compression); + sprintf(fmode, "wb%d", AH->compression); #ifdef HAVE_LIBZ - tctx->FH = gzopen(tctx->filename, fmode); + tctx->FH = gzopen(tctx->filename, fmode); #else - tctx->FH = fopen(tctx->filename, PG_BINARY_W); + tctx->FH = fopen(tctx->filename, PG_BINARY_W); #endif if (tctx->FH == NULL) @@ -241,77 +252,81 @@ static void _StartData(ArchiveHandle* AH, TocEntry* te) } -static int _WriteData(ArchiveHandle* AH, const void* data, int dLen) +static int +_WriteData(ArchiveHandle *AH, const void *data, int dLen) { - lclTocEntry* tctx = (lclTocEntry*)AH->currToc->formatData; + lclTocEntry *tctx = (lclTocEntry *) AH->currToc->formatData; - GZWRITE((void*)data, 1, dLen, tctx->FH); + GZWRITE((void *) data, 1, dLen, tctx->FH); - return dLen; + return dLen; } -static void _EndData(ArchiveHandle* AH, TocEntry* te) +static void +_EndData(ArchiveHandle *AH, TocEntry *te) { - lclTocEntry* tctx = (lclTocEntry*) te->formatData; + lclTocEntry *tctx = (lclTocEntry *) te->formatData; - /* Close the file */ - GZCLOSE(tctx->FH); - tctx->FH = NULL; + /* Close the file */ + GZCLOSE(tctx->FH); + tctx->FH = NULL; } -/* - * Print data for a given file +/* + * Print data for a given file */ -static void _PrintFileData(ArchiveHandle* AH, char *filename, RestoreOptions *ropt) +static void +_PrintFileData(ArchiveHandle *AH, char *filename, RestoreOptions *ropt) { - char buf[4096]; - int cnt; + char buf[4096]; + int cnt; - if (!filename) + if (!filename) return; #ifdef HAVE_LIBZ - AH->FH = gzopen(filename,"rb"); + AH->FH = gzopen(filename, "rb"); #else - AH->FH = fopen(filename,PG_BINARY_R); + AH->FH = fopen(filename, PG_BINARY_R); #endif if (AH->FH == NULL) die_horribly(AH, "%s: Could not open data file for input\n", progname); - while ( (cnt = GZREAD(buf, 1, 4095, AH->FH)) > 0) { + while ((cnt = GZREAD(buf, 1, 4095, AH->FH)) > 0) + { buf[cnt] = '\0'; ahwrite(buf, 1, cnt, AH); - } + } - GZCLOSE(AH->FH); + GZCLOSE(AH->FH); } /* * Print data for a given TOC entry */ -static void _PrintTocData(ArchiveHandle* AH, TocEntry* te, RestoreOptions *ropt) +static void +_PrintTocData(ArchiveHandle *AH, TocEntry *te, RestoreOptions *ropt) { - lclTocEntry* tctx = (lclTocEntry*) te->formatData; + lclTocEntry *tctx = (lclTocEntry *) te->formatData; - if (!tctx->filename) + if (!tctx->filename) return; if (strcmp(te->desc, "BLOBS") == 0) _LoadBlobs(AH, ropt); else - { _PrintFileData(AH, tctx->filename, ropt); - } } -static void _getBlobTocEntry(ArchiveHandle* AH, int *oid, char fname[K_STD_BUF_SIZE]) +static void +_getBlobTocEntry(ArchiveHandle *AH, int *oid, char fname[K_STD_BUF_SIZE]) { - lclContext* ctx = (lclContext*)AH->formatData; - char blobTe[K_STD_BUF_SIZE]; - int fpos; - int eos; + lclContext *ctx = (lclContext *) AH->formatData; + char blobTe[K_STD_BUF_SIZE]; + int fpos; + int eos; if (fgets(&blobTe[0], K_STD_BUF_SIZE - 1, ctx->blobToc) != NULL) { @@ -319,42 +334,45 @@ static void _getBlobTocEntry(ArchiveHandle* AH, int *oid, char fname[K_STD_BUF_S fpos = strcspn(blobTe, " "); - strncpy(fname, &blobTe[fpos+1], K_STD_BUF_SIZE - 1); + strncpy(fname, &blobTe[fpos + 1], K_STD_BUF_SIZE - 1); - eos = strlen(fname)-1; + eos = strlen(fname) - 1; if (fname[eos] == '\n') fname[eos] = '\0'; - } else { + } + else + { *oid = 0; fname[0] = '\0'; } } -static void _LoadBlobs(ArchiveHandle* AH, RestoreOptions *ropt) +static void +_LoadBlobs(ArchiveHandle *AH, RestoreOptions *ropt) { - int oid; - lclContext* ctx = (lclContext*)AH->formatData; - char fname[K_STD_BUF_SIZE]; + int oid; + lclContext *ctx = (lclContext *) AH->formatData; + char fname[K_STD_BUF_SIZE]; StartRestoreBlobs(AH); ctx->blobToc = fopen("blobs.toc", PG_BINARY_R); - if (ctx->blobToc == NULL) + if (ctx->blobToc == NULL) die_horribly(AH, "%s: Could not open BLOB TOC for input\n", progname); _getBlobTocEntry(AH, &oid, fname); - while(oid != 0) - { + while (oid != 0) + { StartRestoreBlob(AH, oid); _PrintFileData(AH, fname, ropt); EndRestoreBlob(AH, oid); _getBlobTocEntry(AH, &oid, fname); - } + } fclose(ctx->blobToc); @@ -362,62 +380,68 @@ static void _LoadBlobs(ArchiveHandle* AH, RestoreOptions *ropt) } -static int _WriteByte(ArchiveHandle* AH, const int i) +static int +_WriteByte(ArchiveHandle *AH, const int i) { - lclContext* ctx = (lclContext*)AH->formatData; + lclContext *ctx = (lclContext *) AH->formatData; - if (fputc(i, AH->FH) == EOF) + if (fputc(i, AH->FH) == EOF) die_horribly(AH, "%s: could not write byte\n", progname); ctx->filePos += 1; - return 1; + return 1; } -static int _ReadByte(ArchiveHandle* AH) +static int +_ReadByte(ArchiveHandle *AH) { - lclContext* ctx = (lclContext*)AH->formatData; - int res; + lclContext *ctx = (lclContext *) AH->formatData; + int res; - res = fgetc(AH->FH); - if (res != EOF) { + res = fgetc(AH->FH); + if (res != EOF) ctx->filePos += 1; - } - return res; + return res; } -static int _WriteBuf(ArchiveHandle* AH, const void* buf, int len) +static int +_WriteBuf(ArchiveHandle *AH, const void *buf, int len) { - lclContext* ctx = (lclContext*)AH->formatData; - int res; - res = fwrite(buf, 1, len, AH->FH); + lclContext *ctx = (lclContext *) AH->formatData; + int res; + + res = fwrite(buf, 1, len, AH->FH); if (res != len) die_horribly(AH, "%s: write error in _WriteBuf (%d != %d)\n", progname, res, len); - ctx->filePos += res; - return res; + ctx->filePos += res; + return res; } -static int _ReadBuf(ArchiveHandle* AH, void* buf, int len) +static int +_ReadBuf(ArchiveHandle *AH, void *buf, int len) { - lclContext* ctx = (lclContext*)AH->formatData; - int res; + lclContext *ctx = (lclContext *) AH->formatData; + int res; - res = fread(buf, 1, len, AH->FH); - ctx->filePos += res; - return res; + res = fread(buf, 1, len, AH->FH); + ctx->filePos += res; + return res; } -static void _CloseArchive(ArchiveHandle* AH) +static void +_CloseArchive(ArchiveHandle *AH) { - if (AH->mode == archModeWrite) { + if (AH->mode == archModeWrite) + { WriteHead(AH); WriteToc(AH); fclose(AH->FH); WriteDataChunks(AH); - } + } - AH->FH = NULL; + AH->FH = NULL; } @@ -427,19 +451,20 @@ static void _CloseArchive(ArchiveHandle* AH) */ /* - * Called by the archiver when starting to save all BLOB DATA (not schema). + * Called by the archiver when starting to save all BLOB DATA (not schema). * This routine should save whatever format-specific information is needed - * to read the BLOBs back into memory. + * to read the BLOBs back into memory. * * It is called just prior to the dumper's DataDumper routine. * * Optional, but strongly recommended. * */ -static void _StartBlobs(ArchiveHandle* AH, TocEntry* te) +static void +_StartBlobs(ArchiveHandle *AH, TocEntry *te) { - lclContext* ctx = (lclContext*)AH->formatData; - char fname[K_STD_BUF_SIZE]; + lclContext *ctx = (lclContext *) AH->formatData; + char fname[K_STD_BUF_SIZE]; sprintf(fname, "blobs.toc"); ctx->blobToc = fopen(fname, PG_BINARY_W); @@ -456,15 +481,16 @@ static void _StartBlobs(ArchiveHandle* AH, TocEntry* te) * * Must save the passed OID for retrieval at restore-time. */ -static void _StartBlob(ArchiveHandle* AH, TocEntry* te, int oid) +static void +_StartBlob(ArchiveHandle *AH, TocEntry *te, int oid) { - lclContext* ctx = (lclContext*)AH->formatData; - lclTocEntry* tctx = (lclTocEntry*)te->formatData; - char fmode[10]; - char fname[255]; - char *sfx; + lclContext *ctx = (lclContext *) AH->formatData; + lclTocEntry *tctx = (lclTocEntry *) te->formatData; + char fmode[10]; + char fname[255]; + char *sfx; - if (oid == 0) + if (oid == 0) die_horribly(AH, "%s: illegal OID for BLOB (%d)\n", progname, oid); if (AH->compression != 0) @@ -472,15 +498,15 @@ static void _StartBlob(ArchiveHandle* AH, TocEntry* te, int oid) else sfx = ""; - sprintf(fmode, "wb%d", AH->compression); + sprintf(fmode, "wb%d", AH->compression); sprintf(fname, "blob_%d.dat%s", oid, sfx); fprintf(ctx->blobToc, "%d %s\n", oid, fname); #ifdef HAVE_LIBZ - tctx->FH = gzopen(fname, fmode); + tctx->FH = gzopen(fname, fmode); #else - tctx->FH = fopen(fname, PG_BINARY_W); + tctx->FH = fopen(fname, PG_BINARY_W); #endif if (tctx->FH == NULL) @@ -493,27 +519,28 @@ static void _StartBlob(ArchiveHandle* AH, TocEntry* te, int oid) * Optional. * */ -static void _EndBlob(ArchiveHandle* AH, TocEntry* te, int oid) +static void +_EndBlob(ArchiveHandle *AH, TocEntry *te, int oid) { - lclTocEntry* tctx = (lclTocEntry*)te->formatData; + lclTocEntry *tctx = (lclTocEntry *) te->formatData; GZCLOSE(tctx->FH); } /* - * Called by the archiver when finishing saving all BLOB DATA. + * Called by the archiver when finishing saving all BLOB DATA. * * Optional. * */ -static void _EndBlobs(ArchiveHandle* AH, TocEntry* te) +static void +_EndBlobs(ArchiveHandle *AH, TocEntry *te) { - lclContext* ctx = (lclContext*)AH->formatData; + lclContext *ctx = (lclContext *) AH->formatData; + /* Write out a fake zero OID to mark end-of-blobs. */ - /* WriteInt(AH, 0); */ + /* WriteInt(AH, 0); */ fclose(ctx->blobToc); } - - diff --git a/src/bin/pg_dump/pg_backup_null.c b/src/bin/pg_dump/pg_backup_null.c index 96232f5734..1c3a09784e 100644 --- a/src/bin/pg_dump/pg_backup_null.c +++ b/src/bin/pg_dump/pg_backup_null.c @@ -2,30 +2,30 @@ * * pg_backup_null.c * - * Implementation of an archive that is never saved; it is used by + * Implementation of an archive that is never saved; it is used by * pg_dump to output output a plain text SQL script instead of save * a real archive. * * See the headers to pg_restore for more details. * * Copyright (c) 2000, Philip Warner - * Rights are granted to use this software in any way so long - * as this notice is not removed. + * Rights are granted to use this software in any way so long + * as this notice is not removed. * * The author is not responsible for loss or damages that may * result from it's use. * * * IDENTIFICATION - * $Header: /cvsroot/pgsql/src/bin/pg_dump/pg_backup_null.c,v 1.4 2001/03/19 02:35:28 pjw Exp $ + * $Header: /cvsroot/pgsql/src/bin/pg_dump/pg_backup_null.c,v 1.5 2001/03/22 04:00:13 momjian Exp $ * * Modifications - 09-Jul-2000 - pjw@rhyme.com.au * - * Initial version. + * Initial version. * * Modifications - 04-Jan-2001 - pjw@rhyme.com.au * - * - Check results of IO routines more carefully. + * - Check results of IO routines more carefully. * * *------------------------------------------------------------------------- @@ -36,33 +36,34 @@ #include <stdlib.h> #include <string.h> -#include <unistd.h> /* for dup */ +#include <unistd.h> /* for dup */ -static int _WriteData(ArchiveHandle* AH, const void* data, int dLen); -static void _EndData(ArchiveHandle* AH, TocEntry* te); -static int _WriteByte(ArchiveHandle* AH, const int i); -static int _WriteBuf(ArchiveHandle* AH, const void* buf, int len); -static void _CloseArchive(ArchiveHandle* AH); -static void _PrintTocData(ArchiveHandle* AH, TocEntry* te, RestoreOptions *ropt); +static int _WriteData(ArchiveHandle *AH, const void *data, int dLen); +static void _EndData(ArchiveHandle *AH, TocEntry *te); +static int _WriteByte(ArchiveHandle *AH, const int i); +static int _WriteBuf(ArchiveHandle *AH, const void *buf, int len); +static void _CloseArchive(ArchiveHandle *AH); +static void _PrintTocData(ArchiveHandle *AH, TocEntry *te, RestoreOptions *ropt); /* - * Initializer + * Initializer */ -void InitArchiveFmt_Null(ArchiveHandle* AH) +void +InitArchiveFmt_Null(ArchiveHandle *AH) { - /* Assuming static functions, this can be copied for each format. */ - AH->WriteDataPtr = _WriteData; - AH->EndDataPtr = _EndData; - AH->WriteBytePtr = _WriteByte; - AH->WriteBufPtr = _WriteBuf; - AH->ClosePtr = _CloseArchive; - AH->PrintTocDataPtr = _PrintTocData; + /* Assuming static functions, this can be copied for each format. */ + AH->WriteDataPtr = _WriteData; + AH->EndDataPtr = _EndData; + AH->WriteBytePtr = _WriteByte; + AH->WriteBufPtr = _WriteBuf; + AH->ClosePtr = _CloseArchive; + AH->PrintTocDataPtr = _PrintTocData; - /* - * Now prevent reading... - */ - if (AH->mode == archModeRead) - die_horribly(AH, "%s: This format can not be read\n"); + /* + * Now prevent reading... + */ + if (AH->mode == archModeRead) + die_horribly(AH, "%s: This format can not be read\n"); } @@ -71,20 +72,22 @@ void InitArchiveFmt_Null(ArchiveHandle* AH) */ /*------ - * Called by dumper via archiver from within a data dump routine + * Called by dumper via archiver from within a data dump routine * As at V1.3, this is only called for COPY FROM dfata, and BLOB data *------ */ -static int _WriteData(ArchiveHandle* AH, const void* data, int dLen) +static int +_WriteData(ArchiveHandle *AH, const void *data, int dLen) { - /* Just send it to output */ - ahwrite(data, 1, dLen, AH); - return dLen; + /* Just send it to output */ + ahwrite(data, 1, dLen, AH); + return dLen; } -static void _EndData(ArchiveHandle* AH, TocEntry* te) +static void +_EndData(ArchiveHandle *AH, TocEntry *te) { - ahprintf(AH, "\n\n"); + ahprintf(AH, "\n\n"); } /*------ @@ -92,30 +95,33 @@ static void _EndData(ArchiveHandle* AH, TocEntry* te) * just sends the data for a given TOC entry to the output. *------ */ -static void _PrintTocData(ArchiveHandle* AH, TocEntry* te, RestoreOptions *ropt) +static void +_PrintTocData(ArchiveHandle *AH, TocEntry *te, RestoreOptions *ropt) { - if (*te->dataDumper) + if (*te->dataDumper) { AH->currToc = te; - (*te->dataDumper)((Archive*)AH, te->oid, te->dataDumperArg); + (*te->dataDumper) ((Archive *) AH, te->oid, te->dataDumperArg); AH->currToc = NULL; } } -static int _WriteByte(ArchiveHandle* AH, const int i) +static int +_WriteByte(ArchiveHandle *AH, const int i) { - /* Don't do anything */ - return 0; + /* Don't do anything */ + return 0; } -static int _WriteBuf(ArchiveHandle* AH, const void* buf, int len) +static int +_WriteBuf(ArchiveHandle *AH, const void *buf, int len) { - /* Don't do anything */ - return len; + /* Don't do anything */ + return len; } -static void _CloseArchive(ArchiveHandle* AH) +static void +_CloseArchive(ArchiveHandle *AH) { - /* Nothing to do */ + /* Nothing to do */ } - diff --git a/src/bin/pg_dump/pg_backup_tar.c b/src/bin/pg_dump/pg_backup_tar.c index 76d1e6c743..9dbf862fc4 100644 --- a/src/bin/pg_dump/pg_backup_tar.c +++ b/src/bin/pg_dump/pg_backup_tar.c @@ -8,23 +8,23 @@ * See the headers to pg_backup_files & pg_restore for more details. * * Copyright (c) 2000, Philip Warner - * Rights are granted to use this software in any way so long - * as this notice is not removed. + * Rights are granted to use this software in any way so long + * as this notice is not removed. * * The author is not responsible for loss or damages that may * result from it's use. * * * IDENTIFICATION - * $Header: /cvsroot/pgsql/src/bin/pg_dump/pg_backup_tar.c,v 1.11 2001/03/19 02:35:28 pjw Exp $ + * $Header: /cvsroot/pgsql/src/bin/pg_dump/pg_backup_tar.c,v 1.12 2001/03/22 04:00:13 momjian Exp $ * * Modifications - 28-Jun-2000 - pjw@rhyme.com.au * - * Initial version. + * Initial version. * * Modifications - 04-Jan-2001 - pjw@rhyme.com.au * - * - Check results of IO routines more carefully. + * - Check results of IO routines more carefully. * *------------------------------------------------------------------------- */ @@ -38,270 +38,302 @@ #include <ctype.h> #include <unistd.h> -static void _ArchiveEntry(ArchiveHandle* AH, TocEntry* te); -static void _StartData(ArchiveHandle* AH, TocEntry* te); -static int _WriteData(ArchiveHandle* AH, const void* data, int dLen); -static void _EndData(ArchiveHandle* AH, TocEntry* te); -static int _WriteByte(ArchiveHandle* AH, const int i); -static int _ReadByte(ArchiveHandle* ); -static int _WriteBuf(ArchiveHandle* AH, const void* buf, int len); -static int _ReadBuf(ArchiveHandle* AH, void* buf, int len); -static void _CloseArchive(ArchiveHandle* AH); -static void _PrintTocData(ArchiveHandle* AH, TocEntry* te, RestoreOptions *ropt); -static void _WriteExtraToc(ArchiveHandle* AH, TocEntry* te); -static void _ReadExtraToc(ArchiveHandle* AH, TocEntry* te); -static void _PrintExtraToc(ArchiveHandle* AH, TocEntry* te); - -static void _StartBlobs(ArchiveHandle* AH, TocEntry* te); -static void _StartBlob(ArchiveHandle* AH, TocEntry* te, int oid); -static void _EndBlob(ArchiveHandle* AH, TocEntry* te, int oid); -static void _EndBlobs(ArchiveHandle* AH, TocEntry* te); +static void _ArchiveEntry(ArchiveHandle *AH, TocEntry *te); +static void _StartData(ArchiveHandle *AH, TocEntry *te); +static int _WriteData(ArchiveHandle *AH, const void *data, int dLen); +static void _EndData(ArchiveHandle *AH, TocEntry *te); +static int _WriteByte(ArchiveHandle *AH, const int i); +static int _ReadByte(ArchiveHandle *); +static int _WriteBuf(ArchiveHandle *AH, const void *buf, int len); +static int _ReadBuf(ArchiveHandle *AH, void *buf, int len); +static void _CloseArchive(ArchiveHandle *AH); +static void _PrintTocData(ArchiveHandle *AH, TocEntry *te, RestoreOptions *ropt); +static void _WriteExtraToc(ArchiveHandle *AH, TocEntry *te); +static void _ReadExtraToc(ArchiveHandle *AH, TocEntry *te); +static void _PrintExtraToc(ArchiveHandle *AH, TocEntry *te); + +static void _StartBlobs(ArchiveHandle *AH, TocEntry *te); +static void _StartBlob(ArchiveHandle *AH, TocEntry *te, int oid); +static void _EndBlob(ArchiveHandle *AH, TocEntry *te, int oid); +static void _EndBlobs(ArchiveHandle *AH, TocEntry *te); #define K_STD_BUF_SIZE 1024 #ifdef HAVE_LIBZ - /* typedef gzFile ThingFile; */ - typedef FILE ThingFile; + /* typedef gzFile ThingFile; */ +typedef FILE ThingFile; + #else - typedef FILE ThingFile; +typedef FILE ThingFile; + #endif -typedef struct { - ThingFile *zFH; - FILE *nFH; - FILE *tarFH; - FILE *tmpFH; - char *targetFile; - char mode; - int pos; - int fileLen; - ArchiveHandle *AH; +typedef struct +{ + ThingFile *zFH; + FILE *nFH; + FILE *tarFH; + FILE *tmpFH; + char *targetFile; + char mode; + int pos; + int fileLen; + ArchiveHandle *AH; } TAR_MEMBER; -typedef struct { +typedef struct +{ int hasSeek; - int filePos; - TAR_MEMBER *blobToc; - FILE *tarFH; + int filePos; + TAR_MEMBER *blobToc; + FILE *tarFH; int tarFHpos; int tarNextMember; - TAR_MEMBER *FH; + TAR_MEMBER *FH; int isSpecialScript; - TAR_MEMBER *scriptTH; + TAR_MEMBER *scriptTH; } lclContext; -typedef struct { - TAR_MEMBER *TH; - char *filename; +typedef struct +{ + TAR_MEMBER *TH; + char *filename; } lclTocEntry; -static char* progname = "Archiver(tar)"; +static char *progname = "Archiver(tar)"; + +static void _LoadBlobs(ArchiveHandle *AH, RestoreOptions *ropt); -static void _LoadBlobs(ArchiveHandle* AH, RestoreOptions *ropt); +static TAR_MEMBER *tarOpen(ArchiveHandle *AH, const char *filename, char mode); +static void tarClose(ArchiveHandle *AH, TAR_MEMBER *TH); -static TAR_MEMBER* tarOpen(ArchiveHandle *AH, const char *filename, char mode); -static void tarClose(ArchiveHandle *AH, TAR_MEMBER *TH); #ifdef __NOT_USED__ -static char* tarGets(char *buf, int len, TAR_MEMBER* th); +static char *tarGets(char *buf, int len, TAR_MEMBER *th); + #endif -static int tarPrintf(ArchiveHandle *AH, TAR_MEMBER *th, const char *fmt, ...); +static int tarPrintf(ArchiveHandle *AH, TAR_MEMBER *th, const char *fmt,...); -static void _tarAddFile(ArchiveHandle *AH, TAR_MEMBER* th); -static int _tarChecksum(char *th); -static TAR_MEMBER* _tarPositionTo(ArchiveHandle *AH, const char *filename); -static int tarRead(void *buf, int len, TAR_MEMBER *th); -static int tarWrite(const void *buf, int len, TAR_MEMBER *th); -static void _tarWriteHeader(TAR_MEMBER* th); -static int _tarGetHeader(ArchiveHandle *AH, TAR_MEMBER* th); -static int _tarReadRaw(ArchiveHandle *AH, void *buf, int len, TAR_MEMBER *th, FILE *fh); +static void _tarAddFile(ArchiveHandle *AH, TAR_MEMBER *th); +static int _tarChecksum(char *th); +static TAR_MEMBER *_tarPositionTo(ArchiveHandle *AH, const char *filename); +static int tarRead(void *buf, int len, TAR_MEMBER *th); +static int tarWrite(const void *buf, int len, TAR_MEMBER *th); +static void _tarWriteHeader(TAR_MEMBER *th); +static int _tarGetHeader(ArchiveHandle *AH, TAR_MEMBER *th); +static int _tarReadRaw(ArchiveHandle *AH, void *buf, int len, TAR_MEMBER *th, FILE *fh); -static int _scriptOut(ArchiveHandle *AH, const void *buf, int len); +static int _scriptOut(ArchiveHandle *AH, const void *buf, int len); /* - * Initializer + * Initializer */ -void InitArchiveFmt_Tar(ArchiveHandle* AH) +void +InitArchiveFmt_Tar(ArchiveHandle *AH) { - lclContext* ctx; - - /* Assuming static functions, this can be copied for each format. */ - AH->ArchiveEntryPtr = _ArchiveEntry; - AH->StartDataPtr = _StartData; - AH->WriteDataPtr = _WriteData; - AH->EndDataPtr = _EndData; - AH->WriteBytePtr = _WriteByte; - AH->ReadBytePtr = _ReadByte; - AH->WriteBufPtr = _WriteBuf; - AH->ReadBufPtr = _ReadBuf; - AH->ClosePtr = _CloseArchive; - AH->PrintTocDataPtr = _PrintTocData; - AH->ReadExtraTocPtr = _ReadExtraToc; - AH->WriteExtraTocPtr = _WriteExtraToc; - AH->PrintExtraTocPtr = _PrintExtraToc; - - AH->StartBlobsPtr = _StartBlobs; - AH->StartBlobPtr = _StartBlob; - AH->EndBlobPtr = _EndBlob; - AH->EndBlobsPtr = _EndBlobs; - - /* - * Set up some special context used in compressing data. - */ - ctx = (lclContext*)malloc(sizeof(lclContext)); - AH->formatData = (void*)ctx; - ctx->filePos = 0; - - /* - * Now open the TOC file - */ - if (AH->mode == archModeWrite) { - - if (AH->fSpec && strcmp(AH->fSpec,"") != 0) { + lclContext *ctx; + + /* Assuming static functions, this can be copied for each format. */ + AH->ArchiveEntryPtr = _ArchiveEntry; + AH->StartDataPtr = _StartData; + AH->WriteDataPtr = _WriteData; + AH->EndDataPtr = _EndData; + AH->WriteBytePtr = _WriteByte; + AH->ReadBytePtr = _ReadByte; + AH->WriteBufPtr = _WriteBuf; + AH->ReadBufPtr = _ReadBuf; + AH->ClosePtr = _CloseArchive; + AH->PrintTocDataPtr = _PrintTocData; + AH->ReadExtraTocPtr = _ReadExtraToc; + AH->WriteExtraTocPtr = _WriteExtraToc; + AH->PrintExtraTocPtr = _PrintExtraToc; + + AH->StartBlobsPtr = _StartBlobs; + AH->StartBlobPtr = _StartBlob; + AH->EndBlobPtr = _EndBlob; + AH->EndBlobsPtr = _EndBlobs; + + /* + * Set up some special context used in compressing data. + */ + ctx = (lclContext *) malloc(sizeof(lclContext)); + AH->formatData = (void *) ctx; + ctx->filePos = 0; + + /* + * Now open the TOC file + */ + if (AH->mode == archModeWrite) + { + + if (AH->fSpec && strcmp(AH->fSpec, "") != 0) ctx->tarFH = fopen(AH->fSpec, PG_BINARY_W); - } else { + else ctx->tarFH = stdout; - } - if (ctx->tarFH == NULL) + if (ctx->tarFH == NULL) die_horribly(NULL, "%s: Could not open TOC file for output.\n", progname); ctx->tarFHpos = 0; - /* Make unbuffered since we will dup() it, and the buffers screw each other */ + /* + * Make unbuffered since we will dup() it, and the buffers screw + * each other + */ /* setvbuf(ctx->tarFH, NULL, _IONBF, 0); */ ctx->hasSeek = (fseek(ctx->tarFH, 0, SEEK_CUR) == 0); - if (AH->compression < 0 || AH->compression > 9) { + if (AH->compression < 0 || AH->compression > 9) AH->compression = Z_DEFAULT_COMPRESSION; - } /* Don't compress into tar files unless asked to do so */ if (AH->compression == Z_DEFAULT_COMPRESSION) AH->compression = 0; - /* We don't support compression because reading the files back is not possible since - * gzdopen uses buffered IO which totally screws file positioning. + /* + * We don't support compression because reading the files back is + * not possible since gzdopen uses buffered IO which totally + * screws file positioning. */ if (AH->compression != 0) die_horribly(NULL, "%s: Compression not supported in TAR output\n", progname); - } else { /* Read Mode */ + } + else + { /* Read Mode */ - if (AH->fSpec && strcmp(AH->fSpec,"") != 0) { + if (AH->fSpec && strcmp(AH->fSpec, "") != 0) ctx->tarFH = fopen(AH->fSpec, PG_BINARY_R); - } else { + else ctx->tarFH = stdin; - } if (ctx->tarFH == NULL) die_horribly(NULL, "%s: Could not open TOC file for input\n", progname); - /* Make unbuffered since we will dup() it, and the buffers screw each other */ + /* + * Make unbuffered since we will dup() it, and the buffers screw + * each other + */ /* setvbuf(ctx->tarFH, NULL, _IONBF, 0); */ ctx->tarFHpos = 0; ctx->hasSeek = (fseek(ctx->tarFH, 0, SEEK_CUR) == 0); - /* Forcibly unmark the header as read since we use the lookahead buffer */ + /* + * Forcibly unmark the header as read since we use the lookahead + * buffer + */ AH->readHeader = 0; - ctx->FH = (void*)tarOpen(AH, "toc.dat", 'r'); + ctx->FH = (void *) tarOpen(AH, "toc.dat", 'r'); ReadHead(AH); ReadToc(AH); - tarClose(AH, ctx->FH); /* Nothing else in the file... */ - } + tarClose(AH, ctx->FH); /* Nothing else in the file... */ + } } /* * - Start a new TOC entry - * Setup the output file name. + * Setup the output file name. */ -static void _ArchiveEntry(ArchiveHandle* AH, TocEntry* te) +static void +_ArchiveEntry(ArchiveHandle *AH, TocEntry *te) { - lclTocEntry* ctx; - char fn[K_STD_BUF_SIZE]; + lclTocEntry *ctx; + char fn[K_STD_BUF_SIZE]; - ctx = (lclTocEntry*)malloc(sizeof(lclTocEntry)); - if (te->dataDumper) { + ctx = (lclTocEntry *) malloc(sizeof(lclTocEntry)); + if (te->dataDumper) + { #ifdef HAVE_LIBZ - if (AH->compression == 0) { + if (AH->compression == 0) sprintf(fn, "%d.dat", te->id); - } else { + else sprintf(fn, "%d.dat.gz", te->id); - } #else sprintf(fn, "%d.dat", te->id); #endif ctx->filename = strdup(fn); - } else { + } + else + { ctx->filename = NULL; ctx->TH = NULL; - } - te->formatData = (void*)ctx; + } + te->formatData = (void *) ctx; } -static void _WriteExtraToc(ArchiveHandle* AH, TocEntry* te) +static void +_WriteExtraToc(ArchiveHandle *AH, TocEntry *te) { - lclTocEntry* ctx = (lclTocEntry*)te->formatData; + lclTocEntry *ctx = (lclTocEntry *) te->formatData; - if (ctx->filename) { + if (ctx->filename) WriteStr(AH, ctx->filename); - } else { + else WriteStr(AH, ""); - } } -static void _ReadExtraToc(ArchiveHandle* AH, TocEntry* te) +static void +_ReadExtraToc(ArchiveHandle *AH, TocEntry *te) { - lclTocEntry* ctx = (lclTocEntry*)te->formatData; + lclTocEntry *ctx = (lclTocEntry *) te->formatData; - if (ctx == NULL) { - ctx = (lclTocEntry*)malloc(sizeof(lclTocEntry)); - te->formatData = (void*)ctx; - } + if (ctx == NULL) + { + ctx = (lclTocEntry *) malloc(sizeof(lclTocEntry)); + te->formatData = (void *) ctx; + } - ctx->filename = ReadStr(AH); - if (strlen(ctx->filename) == 0) { + ctx->filename = ReadStr(AH); + if (strlen(ctx->filename) == 0) + { free(ctx->filename); ctx->filename = NULL; - } - ctx->TH = NULL; + } + ctx->TH = NULL; } -static void _PrintExtraToc(ArchiveHandle* AH, TocEntry* te) +static void +_PrintExtraToc(ArchiveHandle *AH, TocEntry *te) { - lclTocEntry* ctx = (lclTocEntry*)te->formatData; + lclTocEntry *ctx = (lclTocEntry *) te->formatData; - ahprintf(AH, "-- File: %s\n", ctx->filename); + ahprintf(AH, "-- File: %s\n", ctx->filename); } -static void _StartData(ArchiveHandle* AH, TocEntry* te) +static void +_StartData(ArchiveHandle *AH, TocEntry *te) { - lclTocEntry* tctx = (lclTocEntry*)te->formatData; + lclTocEntry *tctx = (lclTocEntry *) te->formatData; tctx->TH = tarOpen(AH, tctx->filename, 'w'); } -static TAR_MEMBER* tarOpen(ArchiveHandle *AH, const char *filename, char mode) +static TAR_MEMBER * +tarOpen(ArchiveHandle *AH, const char *filename, char mode) { - lclContext* ctx = (lclContext*)AH->formatData; - TAR_MEMBER *tm; + lclContext *ctx = (lclContext *) AH->formatData; + TAR_MEMBER *tm; + #ifdef HAVE_LIBZ - char fmode[10]; + char fmode[10]; + #endif if (mode == 'r') { tm = _tarPositionTo(AH, filename); - if (!tm) /* Not found */ + if (!tm) /* Not found */ { - if (filename) /* Couldn't find the requested file. Future: DO SEEK(0) and retry. */ + if (filename) /* Couldn't find the requested file. + * Future: DO SEEK(0) and retry. */ die_horribly(AH, "%s: unable to find file '%s' in archive\n", progname, filename); - else /* Any file OK, non left, so return NULL */ + else +/* Any file OK, non left, so return NULL */ return NULL; } @@ -311,7 +343,7 @@ static TAR_MEMBER* tarOpen(ArchiveHandle *AH, const char *filename, char mode) tm->nFH = ctx->tarFH; else die_horribly(AH, "%s: compression support is disabled in this format\n", progname); - /* tm->zFH = gzdopen(dup(fileno(ctx->tarFH)), "rb"); */ + /* tm->zFH = gzdopen(dup(fileno(ctx->tarFH)), "rb"); */ #else @@ -319,12 +351,14 @@ static TAR_MEMBER* tarOpen(ArchiveHandle *AH, const char *filename, char mode) #endif - } else { + } + else + { tm = calloc(1, sizeof(TAR_MEMBER)); tm->tmpFH = tmpfile(); - if (tm->tmpFH == NULL) + if (tm->tmpFH == NULL) die_horribly(AH, "%s: could not generate temp file name.\n", progname); #ifdef HAVE_LIBZ @@ -336,7 +370,8 @@ static TAR_MEMBER* tarOpen(ArchiveHandle *AH, const char *filename, char mode) if (tm->zFH == NULL) die_horribly(AH, "%s: could not gzdopen temp file.\n", progname); - } else + } + else tm->nFH = tm->tmpFH; #else @@ -356,8 +391,10 @@ static TAR_MEMBER* tarOpen(ArchiveHandle *AH, const char *filename, char mode) } -static void tarClose(ArchiveHandle *AH, TAR_MEMBER* th) +static void +tarClose(ArchiveHandle *AH, TAR_MEMBER *th) { + /* * Close the GZ file since we dup'd. This will flush the buffers. */ @@ -366,13 +403,14 @@ static void tarClose(ArchiveHandle *AH, TAR_MEMBER* th) die_horribly(AH, "%s: could not close tar member\n", progname); if (th->mode == 'w') - _tarAddFile(AH, th); /* This will close the temp file */ - /* else - * Nothing to do for normal read since we don't dup() normal - * file handle, and we don't use temp files. + _tarAddFile(AH, th); /* This will close the temp file */ + + /* + * else Nothing to do for normal read since we don't dup() normal file + * handle, and we don't use temp files. */ - if (th->targetFile) + if (th->targetFile) free(th->targetFile); th->nFH = NULL; @@ -380,12 +418,13 @@ static void tarClose(ArchiveHandle *AH, TAR_MEMBER* th) } #ifdef __NOT_USED__ -static char* tarGets(char *buf, int len, TAR_MEMBER* th) +static char * +tarGets(char *buf, int len, TAR_MEMBER *th) { - char *s; - int cnt = 0; - char c = ' '; - int eof = 0; + char *s; + int cnt = 0; + char c = ' '; + int eof = 0; /* Can't read past logical EOF */ if (len > (th->fileLen - th->pos)) @@ -393,7 +432,8 @@ static char* tarGets(char *buf, int len, TAR_MEMBER* th) while (cnt < len && c != '\n') { - if (_tarReadRaw(th->AH, &c, 1, th, NULL) <= 0) { + if (_tarReadRaw(th->AH, &c, 1, th, NULL) <= 0) + { eof = 1; break; } @@ -410,30 +450,32 @@ static char* tarGets(char *buf, int len, TAR_MEMBER* th) if (s) { - len = strlen(s); + len = strlen(s); th->pos += len; } return s; } + #endif -/* +/* * Just read bytes from the archive. This is the low level read routine * that is used for ALL reads on a tar file. */ -static int _tarReadRaw(ArchiveHandle *AH, void *buf, int len, TAR_MEMBER *th, FILE *fh) +static int +_tarReadRaw(ArchiveHandle *AH, void *buf, int len, TAR_MEMBER *th, FILE *fh) { - lclContext *ctx = (lclContext*)AH->formatData; - int avail; - int used = 0; - int res = 0; + lclContext *ctx = (lclContext *) AH->formatData; + int avail; + int used = 0; + int res = 0; avail = AH->lookaheadLen - AH->lookaheadPos; if (avail > 0) { /* We have some lookahead bytes to use */ - if (avail >= len) /* Just use the lookahead buffer */ + if (avail >= len) /* Just use the lookahead buffer */ used = len; else used = avail; @@ -450,30 +492,32 @@ static int _tarReadRaw(ArchiveHandle *AH, void *buf, int len, TAR_MEMBER *th, FI if (len > 0) { if (fh) - res = fread(&((char*)buf)[used], 1, len, fh); + res = fread(&((char *) buf)[used], 1, len, fh); else if (th) { if (th->zFH) - res = GZREAD(&((char*)buf)[used], 1, len, th->zFH); + res = GZREAD(&((char *) buf)[used], 1, len, th->zFH); else - res = fread(&((char*)buf)[used], 1, len, th->nFH); - } + res = fread(&((char *) buf)[used], 1, len, th->nFH); + } else - die_horribly(AH, "%s: neither th nor fh specified in tarReadRaw\n",progname); + die_horribly(AH, "%s: neither th nor fh specified in tarReadRaw\n", progname); } - /* - * fprintf(stderr, "%s: requested %d bytes, got %d from lookahead and %d from file\n", progname, reqLen, used, res); + /* + * fprintf(stderr, "%s: requested %d bytes, got %d from lookahead and + * %d from file\n", progname, reqLen, used, res); */ ctx->tarFHpos += res + used; return (res + used); } - -static int tarRead(void *buf, int len, TAR_MEMBER *th) + +static int +tarRead(void *buf, int len, TAR_MEMBER *th) { - int res; + int res; if (th->pos + len > th->fileLen) len = th->fileLen - th->pos; @@ -488,12 +532,13 @@ static int tarRead(void *buf, int len, TAR_MEMBER *th) return res; } -static int tarWrite(const void *buf, int len, TAR_MEMBER *th) +static int +tarWrite(const void *buf, int len, TAR_MEMBER *th) { - int res; + int res; if (th->zFH != 0) - res = GZWRITE((void*)buf, 1, len, th->zFH); + res = GZWRITE((void *) buf, 1, len, th->zFH); else res = fwrite(buf, 1, len, th->nFH); @@ -504,60 +549,67 @@ static int tarWrite(const void *buf, int len, TAR_MEMBER *th) return res; } -static int _WriteData(ArchiveHandle* AH, const void* data, int dLen) +static int +_WriteData(ArchiveHandle *AH, const void *data, int dLen) { - lclTocEntry* tctx = (lclTocEntry*)AH->currToc->formatData; + lclTocEntry *tctx = (lclTocEntry *) AH->currToc->formatData; - dLen = tarWrite((void*)data, dLen, tctx->TH); + dLen = tarWrite((void *) data, dLen, tctx->TH); - return dLen; + return dLen; } -static void _EndData(ArchiveHandle* AH, TocEntry* te) +static void +_EndData(ArchiveHandle *AH, TocEntry *te) { - lclTocEntry* tctx = (lclTocEntry*) te->formatData; + lclTocEntry *tctx = (lclTocEntry *) te->formatData; - /* Close the file */ - tarClose(AH, tctx->TH); - tctx->TH = NULL; + /* Close the file */ + tarClose(AH, tctx->TH); + tctx->TH = NULL; } -/* - * Print data for a given file +/* + * Print data for a given file */ -static void _PrintFileData(ArchiveHandle* AH, char *filename, RestoreOptions *ropt) +static void +_PrintFileData(ArchiveHandle *AH, char *filename, RestoreOptions *ropt) { - lclContext* ctx = (lclContext*)AH->formatData; - char buf[4096]; - int cnt; - TAR_MEMBER *th; + lclContext *ctx = (lclContext *) AH->formatData; + char buf[4096]; + int cnt; + TAR_MEMBER *th; - if (!filename) + if (!filename) return; th = tarOpen(AH, filename, 'r'); ctx->FH = th; - while ( (cnt = tarRead(buf, 4095, th)) > 0) { + while ((cnt = tarRead(buf, 4095, th)) > 0) + { buf[cnt] = '\0'; ahwrite(buf, 1, cnt, AH); - } + } - tarClose(AH, th); + tarClose(AH, th); } /* * Print data for a given TOC entry */ -static void _PrintTocData(ArchiveHandle* AH, TocEntry* te, RestoreOptions *ropt) +static void +_PrintTocData(ArchiveHandle *AH, TocEntry *te, RestoreOptions *ropt) { - lclContext* ctx = (lclContext*)AH->formatData; - lclTocEntry* tctx = (lclTocEntry*) te->formatData; - char *tmpCopy; - int i, pos1, pos2; - - if (!tctx->filename) + lclContext *ctx = (lclContext *) AH->formatData; + lclTocEntry *tctx = (lclTocEntry *) te->formatData; + char *tmpCopy; + int i, + pos1, + pos2; + + if (!tctx->filename) return; if (ctx->isSpecialScript) @@ -570,12 +622,12 @@ static void _PrintTocData(ArchiveHandle* AH, TocEntry* te, RestoreOptions *ropt) /* Get a copy of the COPY statement and clean it up */ tmpCopy = strdup(te->copyStmt); - for (i=0 ; i < strlen(tmpCopy) ; i++) + for (i = 0; i < strlen(tmpCopy); i++) tmpCopy[i] = tolower((unsigned char) tmpCopy[i]); /* - * This is very nasty; we don't know if the archive used WITH OIDS, so - * we search the string for it in a paranoid sort of way. + * This is very nasty; we don't know if the archive used WITH + * OIDS, so we search the string for it in a paranoid sort of way. */ if (strncmp(tmpCopy, "copy ", 5) != 0) die_horribly(AH, "%s: COPY statment badly formatted - could not find 'copy' in '%s'\n", progname, tmpCopy); @@ -583,23 +635,23 @@ static void _PrintTocData(ArchiveHandle* AH, TocEntry* te, RestoreOptions *ropt) pos1 = 5; for (pos1 = 5; pos1 < strlen(tmpCopy); pos1++) if (tmpCopy[pos1] != ' ') - break; + break; if (tmpCopy[pos1] == '"') pos1 += 2; - + pos1 += strlen(te->name); - for (pos2 = pos1 ; pos2 < strlen(tmpCopy) ; pos2++) + for (pos2 = pos1; pos2 < strlen(tmpCopy); pos2++) if (strncmp(&tmpCopy[pos2], "from stdin", 10) == 0) break; if (pos2 >= strlen(tmpCopy)) die_horribly(AH, "%s: COPY statment badly formatted - could not find 'from stdin' in '%s' starting at %d\n", - progname, tmpCopy, pos1); + progname, tmpCopy, pos1); - ahwrite(tmpCopy, 1, pos2, AH); /* 'copy "table" [with oids]' */ - ahprintf(AH, " from '$$PATH$$/%s' %s", tctx->filename, &tmpCopy[pos2+10]); + ahwrite(tmpCopy, 1, pos2, AH); /* 'copy "table" [with oids]' */ + ahprintf(AH, " from '$$PATH$$/%s' %s", tctx->filename, &tmpCopy[pos2 + 10]); return; } @@ -607,9 +659,7 @@ static void _PrintTocData(ArchiveHandle* AH, TocEntry* te, RestoreOptions *ropt) if (strcmp(te->desc, "BLOBS") == 0) _LoadBlobs(AH, ropt); else - { _PrintFileData(AH, tctx->filename, ropt); - } } /* static void _getBlobTocEntry(ArchiveHandle* AH, int *oid, char fname[K_STD_BUF_SIZE]) @@ -640,30 +690,32 @@ static void _PrintTocData(ArchiveHandle* AH, TocEntry* te, RestoreOptions *ropt) *} */ -static void _LoadBlobs(ArchiveHandle* AH, RestoreOptions *ropt) +static void +_LoadBlobs(ArchiveHandle *AH, RestoreOptions *ropt) { - int oid; - lclContext* ctx = (lclContext*)AH->formatData; - TAR_MEMBER *th; - int cnt; - char buf[4096]; + int oid; + lclContext *ctx = (lclContext *) AH->formatData; + TAR_MEMBER *th; + int cnt; + char buf[4096]; StartRestoreBlobs(AH); - th = tarOpen(AH, NULL, 'r'); /* Open next file */ + th = tarOpen(AH, NULL, 'r');/* Open next file */ while (th != NULL) { ctx->FH = th; oid = atoi(&th->targetFile[5]); - if (strncmp(th->targetFile, "blob_",5) == 0 && oid != 0) + if (strncmp(th->targetFile, "blob_", 5) == 0 && oid != 0) { ahlog(AH, 1, " - Restoring BLOB oid %d\n", oid); StartRestoreBlob(AH, oid); - while ( (cnt = tarRead(buf, 4095, th)) > 0) { + while ((cnt = tarRead(buf, 4095, th)) > 0) + { buf[cnt] = '\0'; ahwrite(buf, 1, cnt, AH); } @@ -680,60 +732,65 @@ static void _LoadBlobs(ArchiveHandle* AH, RestoreOptions *ropt) } -static int _WriteByte(ArchiveHandle* AH, const int i) +static int +_WriteByte(ArchiveHandle *AH, const int i) { - lclContext* ctx = (lclContext*)AH->formatData; - int res; - char b = i; /* Avoid endian problems */ + lclContext *ctx = (lclContext *) AH->formatData; + int res; + char b = i; /* Avoid endian problems */ - res = tarWrite(&b, 1, ctx->FH); - if (res != EOF) { + res = tarWrite(&b, 1, ctx->FH); + if (res != EOF) ctx->filePos += res; - } - return res; + return res; } -static int _ReadByte(ArchiveHandle* AH) +static int +_ReadByte(ArchiveHandle *AH) { - lclContext* ctx = (lclContext*)AH->formatData; - int res; - char c = '\0'; + lclContext *ctx = (lclContext *) AH->formatData; + int res; + char c = '\0'; - res = tarRead(&c, 1, ctx->FH); - if (res != EOF) { + res = tarRead(&c, 1, ctx->FH); + if (res != EOF) ctx->filePos += res; - } - return c; + return c; } -static int _WriteBuf(ArchiveHandle* AH, const void* buf, int len) +static int +_WriteBuf(ArchiveHandle *AH, const void *buf, int len) { - lclContext* ctx = (lclContext*)AH->formatData; - int res; + lclContext *ctx = (lclContext *) AH->formatData; + int res; - res = tarWrite((void*)buf, len, ctx->FH); - ctx->filePos += res; - return res; + res = tarWrite((void *) buf, len, ctx->FH); + ctx->filePos += res; + return res; } -static int _ReadBuf(ArchiveHandle* AH, void* buf, int len) +static int +_ReadBuf(ArchiveHandle *AH, void *buf, int len) { - lclContext* ctx = (lclContext*)AH->formatData; - int res; + lclContext *ctx = (lclContext *) AH->formatData; + int res; - res = tarRead(buf, len, ctx->FH); - ctx->filePos += res; - return res; + res = tarRead(buf, len, ctx->FH); + ctx->filePos += res; + return res; } -static void _CloseArchive(ArchiveHandle* AH) +static void +_CloseArchive(ArchiveHandle *AH) { - lclContext* ctx = (lclContext*)AH->formatData; - TAR_MEMBER *th; - RestoreOptions *ropt; - int savVerbose, i; + lclContext *ctx = (lclContext *) AH->formatData; + TAR_MEMBER *th; + RestoreOptions *ropt; + int savVerbose, + i; - if (AH->mode == archModeWrite) { + if (AH->mode == archModeWrite) + { /* * Write the Header & TOC to the archive FIRST @@ -742,32 +799,33 @@ static void _CloseArchive(ArchiveHandle* AH) ctx->FH = th; WriteHead(AH); WriteToc(AH); - tarClose(AH, th); /* Not needed any more */ + tarClose(AH, th); /* Not needed any more */ /* * Now send the data (tables & blobs) */ WriteDataChunks(AH); - /* - * Now this format wants to append a script which does a full restore - * if the files have been extracted. + /* + * Now this format wants to append a script which does a full + * restore if the files have been extracted. */ th = tarOpen(AH, "restore.sql", 'w'); tarPrintf(AH, th, "create temporary table pgdump_restore_path(p text);\n"); - tarPrintf(AH, th, "--\n" - "-- NOTE:\n" - "--\n" - "-- File paths need to be edited. Search for $$PATH$$ and\n" - "-- replace it with the path to the directory containing\n" - "-- the extracted data files.\n" - "--\n" - "-- Edit the following to match the path where the\n" - "-- tar archive has been extracted.\n" - "--\n"); + tarPrintf(AH, th, "--\n" + "-- NOTE:\n" + "--\n" + "-- File paths need to be edited. Search for $$PATH$$ and\n" + "-- replace it with the path to the directory containing\n" + "-- the extracted data files.\n" + "--\n" + "-- Edit the following to match the path where the\n" + "-- tar archive has been extracted.\n" + "--\n"); tarPrintf(AH, th, "insert into pgdump_restore_path values('/tmp');\n\n"); AH->CustomOutPtr = _scriptOut; + ctx->isSpecialScript = 1; ctx->scriptTH = th; @@ -779,27 +837,29 @@ static void _CloseArchive(ArchiveHandle* AH) savVerbose = AH->public.verbose; AH->public.verbose = 0; - RestoreArchive((Archive*)AH, ropt); + RestoreArchive((Archive *) AH, ropt); AH->public.verbose = savVerbose; tarClose(AH, th); /* Add a block of NULLs since it's de-rigeur. */ - for(i=0; i<512; i++) + for (i = 0; i < 512; i++) { if (fputc(0, ctx->tarFH) == EOF) die_horribly(AH, "%s: could not write null block at end of TAR archive.\n", progname); } - } + } - AH->FH = NULL; + AH->FH = NULL; } -static int _scriptOut(ArchiveHandle *AH, const void *buf, int len) +static int +_scriptOut(ArchiveHandle *AH, const void *buf, int len) { - lclContext* ctx = (lclContext*)AH->formatData; + lclContext *ctx = (lclContext *) AH->formatData; + return tarWrite(buf, len, ctx->scriptTH); } @@ -808,19 +868,20 @@ static int _scriptOut(ArchiveHandle *AH, const void *buf, int len) */ /* - * Called by the archiver when starting to save all BLOB DATA (not schema). + * Called by the archiver when starting to save all BLOB DATA (not schema). * This routine should save whatever format-specific information is needed - * to read the BLOBs back into memory. + * to read the BLOBs back into memory. * * It is called just prior to the dumper's DataDumper routine. * * Optional, but strongly recommended. * */ -static void _StartBlobs(ArchiveHandle* AH, TocEntry* te) +static void +_StartBlobs(ArchiveHandle *AH, TocEntry *te) { - lclContext* ctx = (lclContext*)AH->formatData; - char fname[K_STD_BUF_SIZE]; + lclContext *ctx = (lclContext *) AH->formatData; + char fname[K_STD_BUF_SIZE]; sprintf(fname, "blobs.toc"); ctx->blobToc = tarOpen(AH, fname, 'w'); @@ -834,14 +895,15 @@ static void _StartBlobs(ArchiveHandle* AH, TocEntry* te) * * Must save the passed OID for retrieval at restore-time. */ -static void _StartBlob(ArchiveHandle* AH, TocEntry* te, int oid) +static void +_StartBlob(ArchiveHandle *AH, TocEntry *te, int oid) { - lclContext* ctx = (lclContext*)AH->formatData; - lclTocEntry* tctx = (lclTocEntry*)te->formatData; - char fname[255]; - char *sfx; + lclContext *ctx = (lclContext *) AH->formatData; + lclTocEntry *tctx = (lclTocEntry *) te->formatData; + char fname[255]; + char *sfx; - if (oid == 0) + if (oid == 0) die_horribly(AH, "%s: illegal OID for BLOB (%d)\n", progname, oid); if (AH->compression != 0) @@ -863,24 +925,27 @@ static void _StartBlob(ArchiveHandle* AH, TocEntry* te, int oid) * Optional. * */ -static void _EndBlob(ArchiveHandle* AH, TocEntry* te, int oid) +static void +_EndBlob(ArchiveHandle *AH, TocEntry *te, int oid) { - lclTocEntry* tctx = (lclTocEntry*)te->formatData; + lclTocEntry *tctx = (lclTocEntry *) te->formatData; tarClose(AH, tctx->TH); } /* - * Called by the archiver when finishing saving all BLOB DATA. + * Called by the archiver when finishing saving all BLOB DATA. * * Optional. * */ -static void _EndBlobs(ArchiveHandle* AH, TocEntry* te) +static void +_EndBlobs(ArchiveHandle *AH, TocEntry *te) { - lclContext* ctx = (lclContext*)AH->formatData; + lclContext *ctx = (lclContext *) AH->formatData; + /* Write out a fake zero OID to mark end-of-blobs. */ - /* WriteInt(AH, 0); */ + /* WriteInt(AH, 0); */ tarClose(AH, ctx->blobToc); @@ -893,24 +958,31 @@ static void _EndBlobs(ArchiveHandle* AH, TocEntry* te) *------------ */ -static int tarPrintf(ArchiveHandle *AH, TAR_MEMBER *th, const char *fmt, ...) +static int +tarPrintf(ArchiveHandle *AH, TAR_MEMBER *th, const char *fmt,...) { - char *p = NULL; + char *p = NULL; va_list ap; - int bSize = strlen(fmt) + 256; /* Should be enough */ + int bSize = strlen(fmt) + 256; /* Should be enough */ int cnt = -1; - /* This is paranoid: deal with the possibility that vsnprintf is willing to ignore trailing null */ - /* or returns > 0 even if string does not fit. It may be the case that it returns cnt = bufsize */ - while (cnt < 0 || cnt >= (bSize - 1) ) + /* + * This is paranoid: deal with the possibility that vsnprintf is + * willing to ignore trailing null + */ + + /* + * or returns > 0 even if string does not fit. It may be the case that + * it returns cnt = bufsize + */ + while (cnt < 0 || cnt >= (bSize - 1)) { - if (p != NULL) free(p); + if (p != NULL) + free(p); bSize *= 2; - p = (char*)malloc(bSize); + p = (char *) malloc(bSize); if (p == NULL) - { die_horribly(AH, "%s: could not allocate buffer for tarPrintf\n", progname); - } va_start(ap, fmt); cnt = vsnprintf(p, bSize, fmt, ap); va_end(ap); @@ -920,20 +992,24 @@ static int tarPrintf(ArchiveHandle *AH, TAR_MEMBER *th, const char *fmt, ...) return cnt; } -static int _tarChecksum(char *header) +static int +_tarChecksum(char *header) { - int i, sum; + int i, + sum; + sum = 0; - for(i = 0; i < 512; i++) + for (i = 0; i < 512; i++) if (i < 148 || i >= 156) sum += 0xFF & header[i]; - return sum + 256; /* Assume 8 blanks in checksum field */ + return sum + 256; /* Assume 8 blanks in checksum field */ } -int isValidTarHeader(char *header) +int +isValidTarHeader(char *header) { - int sum; - int chk = _tarChecksum(header); + int sum; + int chk = _tarChecksum(header); sscanf(&header[148], "%8o", &sum); @@ -941,15 +1017,17 @@ int isValidTarHeader(char *header) } /* Given the member, write the TAR header & copy the file */ -static void _tarAddFile(ArchiveHandle *AH, TAR_MEMBER* th) +static void +_tarAddFile(ArchiveHandle *AH, TAR_MEMBER *th) { - lclContext *ctx = (lclContext*)AH->formatData; - FILE *tmp = th->tmpFH; /* Grab it for convenience */ + lclContext *ctx = (lclContext *) AH->formatData; + FILE *tmp = th->tmpFH;/* Grab it for convenience */ char buf[32768]; int cnt; int len = 0; int res; - int i, pad; + int i, + pad; /* * Find file len & go back to start. @@ -960,48 +1038,52 @@ static void _tarAddFile(ArchiveHandle *AH, TAR_MEMBER* th) _tarWriteHeader(th); - while ( (cnt = fread(&buf[0], 1, 32767, tmp)) > 0) + while ((cnt = fread(&buf[0], 1, 32767, tmp)) > 0) { res = fwrite(&buf[0], 1, cnt, th->tarFH); - if (res != cnt) + if (res != cnt) die_horribly(AH, "%s: write error appending to TAR archive (%d != %d).\n", progname, res, cnt); len += res; } - if (fclose(tmp) != 0) /* This *should* delete it... */ + if (fclose(tmp) != 0) /* This *should* delete it... */ die_horribly(AH, "%s: Could not close tar member (fclose failed).\n", progname); if (len != th->fileLen) die_horribly(AH, "%s: Actual file length does not match expected (%d vs. %d).\n", - progname, len, th->pos); + progname, len, th->pos); pad = ((len + 511) & ~511) - len; - for (i=0 ; i < pad ; i++) + for (i = 0; i < pad; i++) { - if (fputc('\0',th->tarFH) == EOF) + if (fputc('\0', th->tarFH) == EOF) die_horribly(AH, "%s: Could not output padding at end of tar member.\n", progname); - } + } ctx->tarFHpos += len + pad; } /* Locate the file in the archive, read header and position to data */ -static TAR_MEMBER* _tarPositionTo(ArchiveHandle *AH, const char *filename) +static TAR_MEMBER * +_tarPositionTo(ArchiveHandle *AH, const char *filename) { - lclContext *ctx = (lclContext*)AH->formatData; - TAR_MEMBER* th = calloc(1, sizeof(TAR_MEMBER)); - char c; - char header[512]; - int i, len, blks, id; + lclContext *ctx = (lclContext *) AH->formatData; + TAR_MEMBER *th = calloc(1, sizeof(TAR_MEMBER)); + char c; + char header[512]; + int i, + len, + blks, + id; th->AH = AH; /* Go to end of current file, if any */ if (ctx->tarFHpos != 0) { - ahlog(AH, 4, "Moving from %d (%x) to next member at file position %d (%x)\n", - ctx->tarFHpos, ctx->tarFHpos, - ctx->tarNextMember, ctx->tarNextMember); + ahlog(AH, 4, "Moving from %d (%x) to next member at file position %d (%x)\n", + ctx->tarFHpos, ctx->tarFHpos, + ctx->tarNextMember, ctx->tarNextMember); while (ctx->tarFHpos < ctx->tarNextMember) _tarReadRaw(AH, &c, 1, NULL, ctx->tarFH); @@ -1016,28 +1098,29 @@ static TAR_MEMBER* _tarPositionTo(ArchiveHandle *AH, const char *filename) { if (filename) die_horribly(AH, "%s: unable to find header for %s\n", progname, filename); - else /* We're just scanning the archibe for the next file, so return null */ + else +/* We're just scanning the archibe for the next file, so return null */ { free(th); return NULL; } } - while(filename != NULL && strcmp(th->targetFile, filename) != 0) + while (filename != NULL && strcmp(th->targetFile, filename) != 0) { ahlog(AH, 4, "Skipping member %s\n", th->targetFile); id = atoi(th->targetFile); if ((TocIDRequired(AH, id, AH->ropt) & 2) != 0) die_horribly(AH, "%s: dumping data out of order is not supported in this archive format: " - "%s is required, but comes before %s in the archive file.\n", - progname, th->targetFile, filename); + "%s is required, but comes before %s in the archive file.\n", + progname, th->targetFile, filename); /* Header doesn't match, so read to next header */ - len = ((th->fileLen + 511) & ~511); /* Padded length */ - blks = len >> 9; /* # of 512 byte blocks */ + len = ((th->fileLen + 511) & ~511); /* Padded length */ + blks = len >> 9; /* # of 512 byte blocks */ - for(i=0 ; i < blks ; i++) + for (i = 0; i < blks; i++) _tarReadRaw(AH, &header[0], 512, NULL, ctx->tarFH); if (!_tarGetHeader(AH, th)) @@ -1052,23 +1135,26 @@ static TAR_MEMBER* _tarPositionTo(ArchiveHandle *AH, const char *filename) } /* Read & verify a header */ -static int _tarGetHeader(ArchiveHandle *AH, TAR_MEMBER* th) +static int +_tarGetHeader(ArchiveHandle *AH, TAR_MEMBER *th) { - lclContext *ctx = (lclContext*)AH->formatData; - char h[512]; - char name[100]; - int sum, chk; - int len; - int hPos; - int i; - bool gotBlock = false; + lclContext *ctx = (lclContext *) AH->formatData; + char h[512]; + char name[100]; + int sum, + chk; + int len; + int hPos; + int i; + bool gotBlock = false; while (!gotBlock) { + /* - * if ( ftell(ctx->tarFH) != ctx->tarFHpos) - * die_horribly(AH, "%s: mismatch in actual vs. predicted file pos - %d vs. %d\n", - * progname, ftell(ctx->tarFH), ctx->tarFHpos); + * if ( ftell(ctx->tarFH) != ctx->tarFHpos) die_horribly(AH, "%s: + * mismatch in actual vs. predicted file pos - %d vs. %d\n", + * progname, ftell(ctx->tarFH), ctx->tarFHpos); */ /* Save the pos for reporting purposes */ @@ -1076,7 +1162,7 @@ static int _tarGetHeader(ArchiveHandle *AH, TAR_MEMBER* th) /* Read a 512 byte block, return EOF, exit if short */ len = _tarReadRaw(AH, &h[0], 512, NULL, ctx->tarFH); - if (len == 0) /* EOF */ + if (len == 0) /* EOF */ return 0; if (len != 512) @@ -1086,18 +1172,19 @@ static int _tarGetHeader(ArchiveHandle *AH, TAR_MEMBER* th) chk = _tarChecksum(&h[0]); /* - * If the checksum failed, see if it is a null block. - * If so, then just try with next block... + * If the checksum failed, see if it is a null block. If so, then + * just try with next block... */ - if (chk == sum) { + if (chk == sum) gotBlock = true; - } else { - for( i = 0 ; i < 512 ; i++) + else + { + for (i = 0; i < 512; i++) { - if (h[0] != 0) + if (h[0] != 0) { - gotBlock = true; + gotBlock = true; break; } } @@ -1112,8 +1199,8 @@ static int _tarGetHeader(ArchiveHandle *AH, TAR_MEMBER* th) if (chk != sum) die_horribly(AH, "%s: corrupt tar header found in %s " - "(expected %d (%o), computed %d (%o)) file position %d (%x)\n", - progname, &name[0], sum, sum, chk, chk, ftell(ctx->tarFH), ftell(ctx->tarFH)); + "(expected %d (%o), computed %d (%o)) file position %d (%x)\n", + progname, &name[0], sum, sum, chk, chk, ftell(ctx->tarFH), ftell(ctx->tarFH)); th->targetFile = strdup(name); th->fileLen = len; @@ -1121,14 +1208,15 @@ static int _tarGetHeader(ArchiveHandle *AH, TAR_MEMBER* th) return 1; } -static void _tarWriteHeader(TAR_MEMBER* th) +static void +_tarWriteHeader(TAR_MEMBER *th) { char h[512]; int i; int lastSum = 0; int sum; - for (i = 0 ; i < 512 ; i++) + for (i = 0; i < 512; i++) h[i] = '\0'; /* Name 100 */ @@ -1147,7 +1235,7 @@ static void _tarWriteHeader(TAR_MEMBER* th) sprintf(&h[124], "%10o ", th->fileLen); /* Mod Time 12 */ - sprintf(&h[136], "%10o ", (int)time(NULL)); + sprintf(&h[136], "%10o ", (int) time(NULL)); /* Checksum 8 */ sprintf(&h[148], "%6o ", lastSum); @@ -1161,16 +1249,17 @@ static void _tarWriteHeader(TAR_MEMBER* th) /* Magic 8 */ sprintf(&h[257], "ustar "); - /* GNU Version... - * sprintf(&h[257], "ustar"); - * sprintf(&h[263], "00"); - */ + /* + * GNU Version... sprintf(&h[257], "ustar"); sprintf(&h[263], "00"); + */ /* User 32 */ - sprintf(&h[265], "%.31s", ""); /* How do I get username reliably? Do I need to? */ + sprintf(&h[265], "%.31s", ""); /* How do I get username reliably? + * Do I need to? */ /* Group 32 */ - sprintf(&h[297], "%.31s", ""); /* How do I get group reliably? Do I need to? */ + sprintf(&h[297], "%.31s", ""); /* How do I get group reliably? Do + * I need to? */ /* Maj Dev 8 */ /* sprintf(&h[329], "%6o ", 0); */ @@ -1179,14 +1268,13 @@ static void _tarWriteHeader(TAR_MEMBER* th) /* sprintf(&h[337], "%6o ", 0); */ - while ( (sum = _tarChecksum(h)) != lastSum) + while ((sum = _tarChecksum(h)) != lastSum) { sprintf(&h[148], "%6o ", sum); lastSum = sum; } - if (fwrite(h, 1, 512, th->tarFH) != 512) { + if (fwrite(h, 1, 512, th->tarFH) != 512) die_horribly(th->AH, "%s: unable to write tar header\n", progname); - } } diff --git a/src/bin/pg_dump/pg_backup_tar.h b/src/bin/pg_dump/pg_backup_tar.h index d53de29098..a183e24899 100644 --- a/src/bin/pg_dump/pg_backup_tar.h +++ b/src/bin/pg_dump/pg_backup_tar.h @@ -1,36 +1,34 @@ -/* - * $Header: /cvsroot/pgsql/src/bin/pg_dump/pg_backup_tar.h,v 1.2 2001/03/19 02:35:29 pjw Exp $ +/* + * $Header: /cvsroot/pgsql/src/bin/pg_dump/pg_backup_tar.h,v 1.3 2001/03/22 04:00:14 momjian Exp $ * * TAR Header * - * Offset Length Contents - * 0 100 bytes File name ('\0' terminated, 99 maxmum length) - * 100 8 bytes File mode (in octal ascii) - * 108 8 bytes User ID (in octal ascii) - * 116 8 bytes Group ID (in octal ascii) - * 124 12 bytes File size (s) (in octal ascii) - * 136 12 bytes Modify time (in octal ascii) - * 148 8 bytes Header checksum (in octal ascii) - * 156 1 bytes Link flag - * 157 100 bytes Linkname ('\0' terminated, 99 maxmum length) - * 257 8 bytes Magic ("ustar \0") - * 265 32 bytes User name ('\0' terminated, 31 maxmum length) - * 297 32 bytes Group name ('\0' terminated, 31 maxmum length) - * 329 8 bytes Major device ID (in octal ascii) - * 337 8 bytes Minor device ID (in octal ascii) - * 345 167 bytes Padding - * 512 (s+p)bytes File contents (s+p) := (((s) + 511) & ~511), round up to 512 bytes + * Offset Length Contents + * 0 100 bytes File name ('\0' terminated, 99 maxmum length) + * 100 8 bytes File mode (in octal ascii) + * 108 8 bytes User ID (in octal ascii) + * 116 8 bytes Group ID (in octal ascii) + * 124 12 bytes File size (s) (in octal ascii) + * 136 12 bytes Modify time (in octal ascii) + * 148 8 bytes Header checksum (in octal ascii) + * 156 1 bytes Link flag + * 157 100 bytes Linkname ('\0' terminated, 99 maxmum length) + * 257 8 bytes Magic ("ustar \0") + * 265 32 bytes User name ('\0' terminated, 31 maxmum length) + * 297 32 bytes Group name ('\0' terminated, 31 maxmum length) + * 329 8 bytes Major device ID (in octal ascii) + * 337 8 bytes Minor device ID (in octal ascii) + * 345 167 bytes Padding + * 512 (s+p)bytes File contents (s+p) := (((s) + 511) & ~511), round up to 512 bytes */ /* The linkflag defines the type of file */ -#define LF_OLDNORMAL '\0' /* Normal disk file, Unix compatible */ -#define LF_NORMAL '0' /* Normal disk file */ -#define LF_LINK '1' /* Link to previously dumped file */ -#define LF_SYMLINK '2' /* Symbolic link */ -#define LF_CHR '3' /* Character special file */ -#define LF_BLK '4' /* Block special file */ -#define LF_DIR '5' /* Directory */ -#define LF_FIFO '6' /* FIFO special file */ -#define LF_CONTIG '7' /* Contiguous file */ - - +#define LF_OLDNORMAL '\0' /* Normal disk file, Unix compatible */ +#define LF_NORMAL '0' /* Normal disk file */ +#define LF_LINK '1' /* Link to previously dumped file */ +#define LF_SYMLINK '2' /* Symbolic link */ +#define LF_CHR '3' /* Character special file */ +#define LF_BLK '4' /* Block special file */ +#define LF_DIR '5' /* Directory */ +#define LF_FIFO '6' /* FIFO special file */ +#define LF_CONTIG '7' /* Contiguous file */ diff --git a/src/bin/pg_dump/pg_dump.c b/src/bin/pg_dump/pg_dump.c index c612937836..a461f18e4a 100644 --- a/src/bin/pg_dump/pg_dump.c +++ b/src/bin/pg_dump/pg_dump.c @@ -2,7 +2,7 @@ * * pg_dump.c * pg_dump is an utility for dumping out a postgres database - * into a script file. + * into a script file. * * Portions Copyright (c) 1996-2001, PostgreSQL Global Development Group * Portions Copyright (c) 1994, Regents of the University of California @@ -22,7 +22,7 @@ * * * IDENTIFICATION - * $Header: /cvsroot/pgsql/src/bin/pg_dump/pg_dump.c,v 1.195 2001/03/19 02:35:29 pjw Exp $ + * $Header: /cvsroot/pgsql/src/bin/pg_dump/pg_dump.c,v 1.196 2001/03/22 04:00:14 momjian Exp $ * * Modifications - 6/10/96 - dave@bensoft.com - version 1.13.dhb * @@ -55,7 +55,7 @@ * output formats and simple rearrangement of order. * - Discouraged operations more appropriate to the 'restore' * operation. (eg. -c "clear schema" - now always dumps - * commands, but pg_restore can be told not to output them). + * commands, but pg_restore can be told not to output them). * - Added RI warnings to the 'as insert strings' output mode * - Added a small number of comments * - Added a -Z option for compression level on compressed formats @@ -68,7 +68,7 @@ * * Modifications - 28-Jul-2000 - pjw@rhyme.com.au (1.45) * - * Added --create, --no-owner, --superuser, --no-reconnect (pg_dump & pg_restore) + * Added --create, --no-owner, --superuser, --no-reconnect (pg_dump & pg_restore) * Added code to dump 'Create Schema' statement (pg_dump) * Don't bother to disable/enable triggers if we don't have a superuser (pg_restore) * Cleaned up code for reconnecting to database. @@ -79,10 +79,10 @@ * Fixed minor bug in language dumping code: expbuffres were not being reset. * Fixed version number initialization in _allocAH (pg_backup_archiver.c) * - * Modifications - 14-Sep-2000 - pjw@rhyme.com.au + * Modifications - 14-Sep-2000 - pjw@rhyme.com.au * Use symbols for tests on relkind (ie. use RELKIND_VIEW, not 'v') - * Support for relkind = RELKIND_VIEW. - * Fix bug in support for -b option (== --blobs). + * Support for relkind = RELKIND_VIEW. + * Fix bug in support for -b option (== --blobs). * Dump views as views (using 'create view'). * Remove 'isViewRule' since we check the relkind when getting tables. * Now uses temp table 'pgdump_oid' rather than 'pg_dump_oid' (errors otherwise). @@ -91,8 +91,8 @@ * * - Be more paranoid when getting views: call get_viewdef in separate statement * so we can be more informative in error messages. - * - Support for 'isstrict' procedure attribute. - * - Disable --blobs and --table since (a) it's a pain to get ONLY the blobs for the + * - Support for 'isstrict' procedure attribute. + * - Disable --blobs and --table since (a) it's a pain to get ONLY the blobs for the * table with the currently implementation, and (b) it's not clear how to restore * a partial BLOB backup (given the current OID-based BLOB implementation). * @@ -103,13 +103,13 @@ * * Modifications - 13-Feb-2001 - pjw@rhyme.com.au * - * - Fix help output: replace 'f' with 't' and change desc. - * - Add extra arg to formatStringLiteral to specify how to handle LF & TAB. - * I opted for encoding them except in procedure bodies. + * - Fix help output: replace 'f' with 't' and change desc. + * - Add extra arg to formatStringLiteral to specify how to handle LF & TAB. + * I opted for encoding them except in procedure bodies. * - Dump relevant parts of sequences only when doing schemaOnly & dataOnly * - Prevent double-dumping of sequences when dataOnly. * - * Modifications - 19-Mar-2001 - pjw@rhyme.com.au + * Modifications - 19-Mar-2001 - pjw@rhyme.com.au * * - Remove fmtId calls for all ArchiveEntry name fields. This fixes * quoting problems in trigger enable/disable code for mixed case @@ -155,12 +155,14 @@ #define atooid(x) ((Oid) strtoul((x), NULL, 10)) -typedef enum _formatLiteralOptions { - CONV_ALL = 0, - PASS_LFTAB = 3 /* NOTE: 1 and 2 are reserved in case we want to make a mask. */ - /* We could make this a bit mask for control chars, but I don't */ - /* see any value in making it more complex...the current code */ - /* only checks for 'opts == CONV_ALL' anyway. */ +typedef enum _formatLiteralOptions +{ + CONV_ALL = 0, + PASS_LFTAB = 3 /* NOTE: 1 and 2 are reserved in case we + * want to make a mask. */ + /* We could make this a bit mask for control chars, but I don't */ + /* see any value in making it more complex...the current code */ + /* only checks for 'opts == CONV_ALL' anyway. */ } formatLiteralOptions; static void dumpComment(Archive *outfile, const char *target, const char *oid); @@ -174,14 +176,14 @@ static void formatStringLiteral(PQExpBuffer buf, const char *str, const formatLi static void clearTableInfo(TableInfo *, int); static void dumpOneFunc(Archive *fout, FuncInfo *finfo, int i, TypeInfo *tinfo, int numTypes); -static Oid findLastBuiltinOid(const char*); +static Oid findLastBuiltinOid(const char *); static void setMaxOid(Archive *fout); static void AddAcl(char *aclbuf, const char *keyword); static char *GetPrivileges(const char *s); -static int dumpBlobs(Archive *AH, char*, void*); -static int dumpDatabase(Archive *AH); +static int dumpBlobs(Archive *AH, char *, void *); +static int dumpDatabase(Archive *AH); static PQExpBuffer getPKconstraint(TableInfo *tblInfo, IndInfo *indInfo); extern char *optarg; @@ -192,7 +194,7 @@ extern int optind, bool g_verbose; /* User wants verbose narration of our * activities. */ Oid g_last_builtin_oid; /* value of the last builtin oid */ -Archive *g_fout; /* the script file */ +Archive *g_fout; /* the script file */ PGconn *g_conn; /* the database connection */ bool force_quotes; /* User wants to suppress double-quotes */ @@ -209,9 +211,10 @@ char g_comment_start[10]; char g_comment_end[10]; -typedef struct _dumpContext { - TableInfo *tblinfo; - int tblidx; +typedef struct _dumpContext +{ + TableInfo *tblinfo; + int tblidx; bool oids; } DumpContext; @@ -225,61 +228,61 @@ help(const char *progname) #ifdef HAVE_GETOPT_LONG puts( - " -a, --data-only dump out only the data, not the schema\n" - " -b, --blobs dump out blob data\n" - " -c, --clean clean (drop) schema prior to create\n" - " -C, --create output commands to create database\n" - " -d, --inserts dump data as INSERT, rather than COPY, commands\n" - " -D, --attribute-inserts dump data as INSERT commands with attribute names\n" - " -f, --file=FILENAME specify output file name\n" - " -F, --format {c|t|p} output file format (custom, tar, plain text)\n" - " -h, --host=HOSTNAME server host name\n" - " -i, --ignore-version proceed when database version != pg_dump version\n" - " -n, --no-quotes suppress most quotes around identifiers\n" - " -N, --quotes enable most quotes around identifiers\n" - " -o, --oids dump object ids (oids)\n" - " -O, --no-owner do not output \\connect commands in plain text\n" - " format\n" - " -p, --port=PORT server port number\n" - " -R, --no-reconnect disable ALL reconnections to the database in\n" - " plain text format\n" - " -s, --schema-only dump out only the schema, no data\n" - " -S, --superuser=NAME specify the superuser user name to use in plain\n" - " text format\n" - " -t, --table=TABLE dump for this table only (* for all)\n" - " -u, --password use password authentication\n" - " -v, --verbose verbose\n" - " -x, --no-acl do not dump ACL's (grant/revoke)\n" - " -Z, --compress {0-9} compression level for compressed formats\n" + " -a, --data-only dump out only the data, not the schema\n" + " -b, --blobs dump out blob data\n" + " -c, --clean clean (drop) schema prior to create\n" + " -C, --create output commands to create database\n" + " -d, --inserts dump data as INSERT, rather than COPY, commands\n" + " -D, --attribute-inserts dump data as INSERT commands with attribute names\n" + " -f, --file=FILENAME specify output file name\n" + " -F, --format {c|t|p} output file format (custom, tar, plain text)\n" + " -h, --host=HOSTNAME server host name\n" + " -i, --ignore-version proceed when database version != pg_dump version\n" + " -n, --no-quotes suppress most quotes around identifiers\n" + " -N, --quotes enable most quotes around identifiers\n" + " -o, --oids dump object ids (oids)\n" + " -O, --no-owner do not output \\connect commands in plain text\n" + " format\n" + " -p, --port=PORT server port number\n" + " -R, --no-reconnect disable ALL reconnections to the database in\n" + " plain text format\n" + " -s, --schema-only dump out only the schema, no data\n" + " -S, --superuser=NAME specify the superuser user name to use in plain\n" + " text format\n" + " -t, --table=TABLE dump for this table only (* for all)\n" + " -u, --password use password authentication\n" + " -v, --verbose verbose\n" + " -x, --no-acl do not dump ACL's (grant/revoke)\n" + " -Z, --compress {0-9} compression level for compressed formats\n" ); #else puts( - " -a dump out only the data, no schema\n" - " -b dump out blob data\n" - " -c clean (drop) schema prior to create\n" - " -C output commands to create database\n" - " -d dump data as INSERT, rather than COPY, commands\n" - " -D dump data as INSERT commands with attribute names\n" - " -f FILENAME specify output file name\n" - " -F {c|t|p} output file format (custom, tar, plain text)\n" - " -h HOSTNAME server host name\n" - " -i proceed when database version != pg_dump version\n" - " -n suppress most quotes around identifiers\n" - " -N enable most quotes around identifiers\n" - " -o dump object ids (oids)\n" - " -O do not output \\connect commands in plain text\n" - " format\n" - " -p PORT server port number\n" - " -R disable ALL reconnections to the database in\n" - " plain text format\n" - " -s dump out only the schema, no data\n" - " -S NAME specify the superuser user name to use in plain\n" - " text format\n" - " -t TABLE dump for this table only (* for all)\n" - " -u use password authentication\n" - " -v verbose\n" - " -x do not dump ACL's (grant/revoke)\n" - " -Z {0-9} compression level for compressed formats\n" + " -a dump out only the data, no schema\n" + " -b dump out blob data\n" + " -c clean (drop) schema prior to create\n" + " -C output commands to create database\n" + " -d dump data as INSERT, rather than COPY, commands\n" + " -D dump data as INSERT commands with attribute names\n" + " -f FILENAME specify output file name\n" + " -F {c|t|p} output file format (custom, tar, plain text)\n" + " -h HOSTNAME server host name\n" + " -i proceed when database version != pg_dump version\n" + " -n suppress most quotes around identifiers\n" + " -N enable most quotes around identifiers\n" + " -o dump object ids (oids)\n" + " -O do not output \\connect commands in plain text\n" + " format\n" + " -p PORT server port number\n" + " -R disable ALL reconnections to the database in\n" + " plain text format\n" + " -s dump out only the schema, no data\n" + " -S NAME specify the superuser user name to use in plain\n" + " text format\n" + " -t TABLE dump for this table only (* for all)\n" + " -u use password authentication\n" + " -v verbose\n" + " -x do not dump ACL's (grant/revoke)\n" + " -Z {0-9} compression level for compressed formats\n" ); #endif puts("If no database name is not supplied, then the PGDATABASE environment\nvariable value is used.\n"); @@ -313,11 +316,11 @@ exit_nicely(PGconn *conn) * to be dumped. */ -static int -dumpClasses_nodumpData(Archive *fout, char* oid, void *dctxv) +static int +dumpClasses_nodumpData(Archive *fout, char *oid, void *dctxv) { - const DumpContext *dctx = (DumpContext*)dctxv; - const char *classname = dctx->tblinfo[dctx->tblidx].relname; + const DumpContext *dctx = (DumpContext *) dctxv; + const char *classname = dctx->tblinfo[dctx->tblidx].relname; const bool oids = dctx->oids; PGresult *res; @@ -326,16 +329,17 @@ dumpClasses_nodumpData(Archive *fout, char* oid, void *dctxv) bool copydone; char copybuf[COPYBUFSIZ]; - if (g_verbose) - fprintf(stderr, "%s dumping out the contents of table %s\n", g_comment_start, classname); + if (g_verbose) + fprintf(stderr, "%s dumping out the contents of table %s\n", g_comment_start, classname); if (oids == true) { - /* + + /* * archprintf(fout, "COPY %s WITH OIDS FROM stdin;\n", - * fmtId(classname, force_quotes)); + * fmtId(classname, force_quotes)); * - * - Not used as of V1.3 (needs to be in ArchiveEntry call) + * - Not used as of V1.3 (needs to be in ArchiveEntry call) * */ @@ -344,8 +348,10 @@ dumpClasses_nodumpData(Archive *fout, char* oid, void *dctxv) } else { - /* - *archprintf(fout, "COPY %s FROM stdin;\n", fmtId(classname, force_quotes)); + + /* + * archprintf(fout, "COPY %s FROM stdin;\n", fmtId(classname, + * force_quotes)); * * - Not used as of V1.3 (needs to be in ArchiveEntry call) * @@ -404,45 +410,50 @@ dumpClasses_nodumpData(Archive *fout, char* oid, void *dctxv) } } - /* + /* * THROTTLE: * - * There was considerable discussion in late July, 2000 regarding slowing down - * pg_dump when backing up large tables. Users with both slow & fast (muti-processor) - * machines experienced performance degradation when doing a backup. + * There was considerable discussion in late July, 2000 + * regarding slowing down pg_dump when backing up large + * tables. Users with both slow & fast (muti-processor) + * machines experienced performance degradation when doing + * a backup. * - * Initial attempts based on sleeping for a number of ms for each ms of work were deemed - * too complex, then a simple 'sleep in each loop' implementation was suggested. The latter - * failed because the loop was too tight. Finally, the following was implemented: + * Initial attempts based on sleeping for a number of ms for + * each ms of work were deemed too complex, then a simple + * 'sleep in each loop' implementation was suggested. The + * latter failed because the loop was too tight. Finally, + * the following was implemented: * - * If throttle is non-zero, then - * See how long since the last sleep. - * Work out how long to sleep (based on ratio). - * If sleep is more than 100ms, then - * sleep - * reset timer - * EndIf + * If throttle is non-zero, then See how long since the last + * sleep. Work out how long to sleep (based on ratio). If + * sleep is more than 100ms, then sleep reset timer EndIf * EndIf * - * where the throttle value was the number of ms to sleep per ms of work. The calculation was - * done in each loop. + * where the throttle value was the number of ms to sleep per + * ms of work. The calculation was done in each loop. * - * Most of the hard work is done in the backend, and this solution still did not work - * particularly well: on slow machines, the ratio was 50:1, and on medium paced machines, 1:1, - * and on fast multi-processor machines, it had little or no effect, for reasons that were unclear. + * Most of the hard work is done in the backend, and this + * solution still did not work particularly well: on slow + * machines, the ratio was 50:1, and on medium paced + * machines, 1:1, and on fast multi-processor machines, it + * had little or no effect, for reasons that were unclear. * * Further discussion ensued, and the proposal was dropped. * - * For those people who want this feature, it can be implemented using gettimeofday in each - * loop, calculating the time since last sleep, multiplying that by the sleep ratio, then - * if the result is more than a preset 'minimum sleep time' (say 100ms), call the 'select' - * function to sleep for a subsecond period ie. + * For those people who want this feature, it can be + * implemented using gettimeofday in each loop, + * calculating the time since last sleep, multiplying that + * by the sleep ratio, then if the result is more than a + * preset 'minimum sleep time' (say 100ms), call the + * 'select' function to sleep for a subsecond period ie. * - * select(0, NULL, NULL, NULL, &tvi); + * select(0, NULL, NULL, NULL, &tvi); * - * This will return after the interval specified in the structure tvi. Fianally, call - * gettimeofday again to save the 'last sleep time'. - */ + * This will return after the interval specified in the + * structure tvi. Fianally, call gettimeofday again to + * save the 'last sleep time'. + */ } archprintf(fout, "\\.\n"); } @@ -464,10 +475,10 @@ dumpClasses_nodumpData(Archive *fout, char* oid, void *dctxv) } static int -dumpClasses_dumpData(Archive *fout, char* oid, void *dctxv) +dumpClasses_dumpData(Archive *fout, char *oid, void *dctxv) { - const DumpContext *dctx = (DumpContext*)dctxv; - const char *classname = dctx->tblinfo[dctx->tblidx].relname; + const DumpContext *dctx = (DumpContext *) dctxv; + const char *classname = dctx->tblinfo[dctx->tblidx].relname; PGresult *res; PQExpBuffer q = createPQExpBuffer(); @@ -479,8 +490,8 @@ dumpClasses_dumpData(Archive *fout, char* oid, void *dctxv) if (!res || PQresultStatus(res) != PGRES_TUPLES_OK) { - fprintf(stderr, "dumpClasses(): command failed. Explanation from backend: '%s'.\n", - PQerrorMessage(g_conn)); + fprintf(stderr, "dumpClasses(): command failed. Explanation from backend: '%s'.\n", + PQerrorMessage(g_conn)); exit_nicely(g_conn); } for (tuple = 0; tuple < PQntuples(res); tuple++) @@ -518,7 +529,7 @@ dumpClasses_dumpData(Archive *fout, char* oid, void *dctxv) case FLOAT8OID:/* float types */ /* These types are printed without quotes */ archprintf(fout, "%s", - PQgetvalue(res, tuple, field)); + PQgetvalue(res, tuple, field)); break; case ZPBITOID: case VARBITOID: @@ -556,19 +567,23 @@ formatStringLiteral(PQExpBuffer buf, const char *str, const formatLiteralOptions appendPQExpBufferChar(buf, '\''); while (*str) { - char ch = *str++; + char ch = *str++; if (ch == '\\' || ch == '\'') { - appendPQExpBufferChar(buf, ch); /* double these */ + appendPQExpBufferChar(buf, ch); /* double these */ appendPQExpBufferChar(buf, ch); } else if ((unsigned char) ch < (unsigned char) ' ' && - ( opts == CONV_ALL - || (ch != '\n' && ch != '\t') - )) + (opts == CONV_ALL + || (ch != '\n' && ch != '\t') + )) { - /* generate octal escape for control chars other than whitespace */ + + /* + * generate octal escape for control chars other than + * whitespace + */ appendPQExpBufferChar(buf, '\\'); appendPQExpBufferChar(buf, ((ch >> 6) & 3) + '0'); appendPQExpBufferChar(buf, ((ch >> 3) & 7) + '0'); @@ -586,18 +601,18 @@ formatStringLiteral(PQExpBuffer buf, const char *str, const formatLiteralOptions */ static void dumpClasses(const TableInfo *tblinfo, const int numTables, Archive *fout, - const char *onlytable, const bool oids, const bool force_quotes) + const char *onlytable, const bool oids, const bool force_quotes) { - int i; - char *all_only; - DataDumperPtr dumpFn; - DumpContext *dumpCtx; - char *oidsPart; - char copyBuf[512]; - char *copyStmt; - - if (onlytable == NULL || (strlen(onlytable) == 0) ) + int i; + char *all_only; + DataDumperPtr dumpFn; + DumpContext *dumpCtx; + char *oidsPart; + char copyBuf[512]; + char *copyStmt; + + if (onlytable == NULL || (strlen(onlytable) == 0)) all_only = "all"; else all_only = "only"; @@ -611,9 +626,9 @@ dumpClasses(const TableInfo *tblinfo, const int numTables, Archive *fout, if (g_verbose) fprintf(stderr, "%s preparing to dump out the contents of %s %d table%s/sequence%s %s\n", g_comment_start, all_only, - (onlytable == NULL || (strlen(onlytable) == 0)) ? numTables : 1, - (onlytable == NULL || (strlen(onlytable) == 0)) ? "s" : "", - (onlytable == NULL || (strlen(onlytable) == 0)) ? "s" : "", + (onlytable == NULL || (strlen(onlytable) == 0)) ? numTables : 1, + (onlytable == NULL || (strlen(onlytable) == 0)) ? "s" : "", + (onlytable == NULL || (strlen(onlytable) == 0)) ? "s" : "", g_comment_end); for (i = 0; i < numTables; i++) @@ -635,12 +650,12 @@ dumpClasses(const TableInfo *tblinfo, const int numTables, Archive *fout, /* becomeUser(fout, tblinfo[i].usename); */ - dumpCtx = (DumpContext*)malloc(sizeof(DumpContext)); - dumpCtx->tblinfo = (TableInfo*)tblinfo; + dumpCtx = (DumpContext *) malloc(sizeof(DumpContext)); + dumpCtx->tblinfo = (TableInfo *) tblinfo; dumpCtx->tblidx = i; dumpCtx->oids = oids; - if (!dumpData) /* Dump/restore using COPY */ + if (!dumpData) /* Dump/restore using COPY */ { dumpFn = dumpClasses_nodumpData; /* dumpClasses_nodumpData(fout, classname, oids); */ @@ -648,7 +663,8 @@ dumpClasses(const TableInfo *tblinfo, const int numTables, Archive *fout, oidsPart); copyStmt = copyBuf; } - else /* Restore using INSERT */ + else +/* Restore using INSERT */ { dumpFn = dumpClasses_dumpData; /* dumpClasses_dumpData(fout, classname); */ @@ -656,8 +672,8 @@ dumpClasses(const TableInfo *tblinfo, const int numTables, Archive *fout, } ArchiveEntry(fout, tblinfo[i].oid, tblinfo[i].relname, - "TABLE DATA", NULL, "", "", copyStmt, tblinfo[i].usename, - dumpFn, dumpCtx); + "TABLE DATA", NULL, "", "", copyStmt, tblinfo[i].usename, + dumpFn, dumpCtx); } } } @@ -685,14 +701,14 @@ main(int argc, char **argv) int outputBlobs = 0; int outputNoOwner = 0; int outputNoReconnect = 0; - char *outputSuperuser = NULL; + char *outputSuperuser = NULL; - RestoreOptions *ropt; + RestoreOptions *ropt; #ifdef HAVE_GETOPT_LONG static struct option long_options[] = { {"data-only", no_argument, NULL, 'a'}, - {"blobs", no_argument, NULL, 'b' }, + {"blobs", no_argument, NULL, 'b'}, {"clean", no_argument, NULL, 'c'}, {"create", no_argument, NULL, 'C'}, {"file", required_argument, NULL, 'f'}, @@ -744,12 +760,12 @@ main(int argc, char **argv) if (argc > 1) { - if (strcmp(argv[1], "--help")==0 || strcmp(argv[1], "-?")==0) + if (strcmp(argv[1], "--help") == 0 || strcmp(argv[1], "-?") == 0) { help(progname); exit(0); } - if (strcmp(argv[1], "--version")==0 || strcmp(argv[1], "-V")==0) + if (strcmp(argv[1], "--version") == 0 || strcmp(argv[1], "-V") == 0) { version(); exit(0); @@ -774,10 +790,10 @@ main(int argc, char **argv) break; case 'c': /* clean (i.e., drop) schema prior to - * create */ + * create */ outputClean = 1; - break; - + break; + case 'C': /* Create DB */ outputCreate = 1; @@ -839,7 +855,8 @@ main(int argc, char **argv) schemaOnly = true; break; - case 'S': /* Username for superuser in plain text output */ + case 'S': /* Username for superuser in plain text + * output */ outputSuperuser = strdup(optarg); break; @@ -866,8 +883,11 @@ main(int argc, char **argv) if (isupper((unsigned char) tablename[i])) tablename[i] = tolower((unsigned char) tablename[i]); - /* '*' is a special case meaning ALL tables, but only if unquoted */ - if (strcmp(tablename,"*") == 0) + /* + * '*' is a special case meaning ALL tables, but + * only if unquoted + */ + if (strcmp(tablename, "*") == 0) tablename[0] = '\0'; } @@ -898,7 +918,7 @@ main(int argc, char **argv) #ifndef HAVE_GETOPT_LONG case '-': fprintf(stderr, "%s was compiled without support for long options.\n" - "Use --help for help on invocation options.\n", progname); + "Use --help for help on invocation options.\n", progname); exit(1); break; #endif @@ -908,23 +928,24 @@ main(int argc, char **argv) } } - if (optind < (argc - 1)) { + if (optind < (argc - 1)) + { fprintf(stderr, "%s: extra parameters found on command line after '%s' (first is '%s').\n" - "Please respecify command.\nUse --help for help on invocation options.\n", - progname, argv[optind], argv[optind+1]); + "Please respecify command.\nUse --help for help on invocation options.\n", + progname, argv[optind], argv[optind + 1]); exit(1); } if (dataOnly && schemaOnly) { fprintf(stderr, - "%s: 'Schema Only' and 'Data Only' are incompatible options.\n", + "%s: 'Schema Only' and 'Data Only' are incompatible options.\n", progname); exit(1); } - if (outputBlobs && tablename != NULL && strlen(tablename) > 0 ) + if (outputBlobs && tablename != NULL && strlen(tablename) > 0) { fprintf(stderr, "%s: BLOB output is not supported for a single table. Use all tables or a full dump instead.\n", @@ -940,16 +961,17 @@ main(int argc, char **argv) exit(1); } - if (outputBlobs == true && (format[0] == 'p' || format[0] == 'P') ) + if (outputBlobs == true && (format[0] == 'p' || format[0] == 'P')) { fprintf(stderr, - "%s: BLOB output is not supported for plain text dump files. Use a different output format.\n", - progname); + "%s: BLOB output is not supported for plain text dump files. Use a different output format.\n", + progname); exit(1); } /* open the output file */ - switch (format[0]) { + switch (format[0]) + { case 'c': case 'C': @@ -974,14 +996,14 @@ main(int argc, char **argv) default: fprintf(stderr, - "%s: invalid output format '%s' specified\n", progname, format); - exit(1); + "%s: invalid output format '%s' specified\n", progname, format); + exit(1); } if (g_fout == NULL) { fprintf(stderr, - "%s: could not open output file named %s for writing\n", + "%s: could not open output file named %s for writing\n", progname, filename); exit(1); } @@ -991,7 +1013,10 @@ main(int argc, char **argv) dbname = argv[optind]; - /* Open the database using the Archiver, so it knows about it. Errors mean death */ + /* + * Open the database using the Archiver, so it knows about it. Errors + * mean death + */ g_conn = ConnectDatabase(g_fout, dbname, pghost, pgport, use_password, ignore_version); /* @@ -1002,14 +1027,14 @@ main(int argc, char **argv) res = PQexec(g_conn, "begin"); if (!res || PQresultStatus(res) != PGRES_COMMAND_OK) - exit_horribly(g_fout, "BEGIN command failed. Explanation from backend: '%s'.\n", - PQerrorMessage(g_conn)); + exit_horribly(g_fout, "BEGIN command failed. Explanation from backend: '%s'.\n", + PQerrorMessage(g_conn)); PQclear(res); res = PQexec(g_conn, "set transaction isolation level serializable"); if (!res || PQresultStatus(res) != PGRES_COMMAND_OK) - exit_horribly(g_fout, "SET TRANSACTION command failed. Explanation from backend: '%s'.\n", - PQerrorMessage(g_conn)); + exit_horribly(g_fout, "SET TRANSACTION command failed. Explanation from backend: '%s'.\n", + PQerrorMessage(g_conn)); PQclear(res); } @@ -1024,17 +1049,15 @@ main(int argc, char **argv) setMaxOid(g_fout); if (g_verbose) - fprintf(stderr, "%s last builtin oid is %u %s\n", - g_comment_start, g_last_builtin_oid, g_comment_end); + fprintf(stderr, "%s last builtin oid is %u %s\n", + g_comment_start, g_last_builtin_oid, g_comment_end); tblinfo = dumpSchema(g_fout, &numTables, tablename, aclsSkip, oids, schemaOnly, dataOnly); if (!schemaOnly) - { - dumpClasses(tblinfo, numTables, g_fout, tablename, oids, force_quotes); - } + dumpClasses(tblinfo, numTables, g_fout, tablename, oids, force_quotes); if (outputBlobs) - ArchiveEntry(g_fout, "0", "BLOBS", "BLOBS", NULL, "", "", "", "", dumpBlobs, 0); + ArchiveEntry(g_fout, "0", "BLOBS", "BLOBS", NULL, "", "", "", "", dumpBlobs, 0); if (!dataOnly) /* dump indexes and triggers at the end * for performance */ @@ -1054,10 +1077,10 @@ main(int argc, char **argv) MoveToEnd(g_fout, "RULE"); MoveToEnd(g_fout, "SEQUENCE SET"); - if (plainText) + if (plainText) { ropt = NewRestoreOptions(); - ropt->filename = (char*)filename; + ropt->filename = (char *) filename; ropt->dropSchema = outputClean; ropt->aclsSkip = aclsSkip; ropt->superuser = outputSuperuser; @@ -1071,9 +1094,9 @@ main(int argc, char **argv) ropt->superuser = PQuser(g_conn); if (compressLevel == -1) - ropt->compression = 0; + ropt->compression = 0; else - ropt->compression = compressLevel; + ropt->compression = compressLevel; RestoreArchive(g_fout, ropt); } @@ -1090,30 +1113,30 @@ main(int argc, char **argv) * dump the database definition * */ -static int +static int dumpDatabase(Archive *AH) { - PQExpBuffer dbQry = createPQExpBuffer(); - PQExpBuffer delQry = createPQExpBuffer(); - PQExpBuffer creaQry = createPQExpBuffer(); - PGresult *res; - int ntups; - int i_dba; + PQExpBuffer dbQry = createPQExpBuffer(); + PQExpBuffer delQry = createPQExpBuffer(); + PQExpBuffer creaQry = createPQExpBuffer(); + PGresult *res; + int ntups; + int i_dba; if (g_verbose) fprintf(stderr, "%s saving database definition\n", g_comment_start); /* Get the dba */ appendPQExpBuffer(dbQry, "select (select usename from pg_user where datdba = usesysid) as dba from pg_database" - " where datname = "); + " where datname = "); formatStringLiteral(dbQry, PQdb(g_conn), CONV_ALL); res = PQexec(g_conn, dbQry->data); if (!res || PQresultStatus(res) != PGRES_TUPLES_OK) { - fprintf(stderr, "getDatabase(): SELECT failed. Explanation from backend: '%s'.\n", - PQerrorMessage(g_conn)); + fprintf(stderr, "getDatabase(): SELECT failed. Explanation from backend: '%s'.\n", + PQerrorMessage(g_conn)); exit_nicely(g_conn); } @@ -1129,10 +1152,10 @@ dumpDatabase(Archive *AH) appendPQExpBuffer(delQry, "Drop Database \"%s\";\n", PQdb(g_conn)); i_dba = PQfnumber(res, "dba"); - ArchiveEntry(AH, "0" /* OID */, PQdb(g_conn) /* Name */, "DATABASE", NULL, - creaQry->data /* Create */, delQry->data /*Del*/, - "" /* Copy */, PQgetvalue(res, 0, i_dba) /*Owner*/, - NULL /* Dumper */, NULL /* Dumper Arg */); + ArchiveEntry(AH, "0" /* OID */ , PQdb(g_conn) /* Name */ , "DATABASE", NULL, + creaQry->data /* Create */ , delQry->data /* Del */ , + "" /* Copy */ , PQgetvalue(res, 0, i_dba) /* Owner */ , + NULL /* Dumper */ , NULL /* Dumper Arg */ ); PQclear(res); @@ -1146,47 +1169,48 @@ dumpDatabase(Archive *AH) * */ -#define loBufSize 16384 +#define loBufSize 16384 #define loFetchSize 1000 -static int -dumpBlobs(Archive *AH, char* junkOid, void *junkVal) +static int +dumpBlobs(Archive *AH, char *junkOid, void *junkVal) { - PQExpBuffer oidQry = createPQExpBuffer(); - PQExpBuffer oidFetchQry = createPQExpBuffer(); - PGresult *res; - int i; - int loFd; - char buf[loBufSize]; - int cnt; - int blobOid; + PQExpBuffer oidQry = createPQExpBuffer(); + PQExpBuffer oidFetchQry = createPQExpBuffer(); + PGresult *res; + int i; + int loFd; + char buf[loBufSize]; + int cnt; + int blobOid; if (g_verbose) fprintf(stderr, "%s saving BLOBs\n", g_comment_start); /* Cursor to get all BLOB tables */ - appendPQExpBuffer(oidQry, "Declare blobOid Cursor for SELECT DISTINCT loid FROM pg_largeobject"); + appendPQExpBuffer(oidQry, "Declare blobOid Cursor for SELECT DISTINCT loid FROM pg_largeobject"); res = PQexec(g_conn, oidQry->data); if (!res || PQresultStatus(res) != PGRES_COMMAND_OK) { - fprintf(stderr, "dumpBlobs(): Declare Cursor failed. Explanation from backend: '%s'.\n", - PQerrorMessage(g_conn)); + fprintf(stderr, "dumpBlobs(): Declare Cursor failed. Explanation from backend: '%s'.\n", + PQerrorMessage(g_conn)); exit_nicely(g_conn); } /* Fetch for cursor */ appendPQExpBuffer(oidFetchQry, "Fetch %d in blobOid", loFetchSize); - do { + do + { /* Do a fetch */ PQclear(res); res = PQexec(g_conn, oidFetchQry->data); if (!res || PQresultStatus(res) != PGRES_TUPLES_OK) { - fprintf(stderr, "dumpBlobs(): Fetch Cursor failed. Explanation from backend: '%s'.\n", PQerrorMessage(g_conn)); - exit_nicely(g_conn); + fprintf(stderr, "dumpBlobs(): Fetch Cursor failed. Explanation from backend: '%s'.\n", PQerrorMessage(g_conn)); + exit_nicely(g_conn); } /* Process the tuples, if any */ @@ -1198,22 +1222,24 @@ dumpBlobs(Archive *AH, char* junkOid, void *junkVal) if (loFd == -1) { fprintf(stderr, "dumpBlobs(): Could not open large object. " - "Explanation from backend: '%s'.\n", PQerrorMessage(g_conn)); + "Explanation from backend: '%s'.\n", PQerrorMessage(g_conn)); exit_nicely(g_conn); } StartBlob(AH, blobOid); /* Now read it in chunks, sending data to archive */ - do { + do + { cnt = lo_read(g_conn, loFd, buf, loBufSize); - if (cnt < 0) { + if (cnt < 0) + { fprintf(stderr, "dumpBlobs(): Error reading large object. " - " Explanation from backend: '%s'.\n", PQerrorMessage(g_conn)); + " Explanation from backend: '%s'.\n", PQerrorMessage(g_conn)); exit_nicely(g_conn); } - WriteData(AH, buf, cnt); + WriteData(AH, buf, cnt); } while (cnt > 0); @@ -1273,11 +1299,11 @@ getTypes(int *numTypes) */ appendPQExpBuffer(query, "SELECT pg_type.oid, typowner, typname, typlen, typprtlen, " - "typinput, typoutput, typreceive, typsend, typelem, typdelim, " - "typdefault, typrelid, typbyval, " - "(select usename from pg_user where typowner = usesysid) as usename, " - "format_type(pg_type.oid, NULL) as typedefn " - "from pg_type" ); + "typinput, typoutput, typreceive, typsend, typelem, typdelim, " + "typdefault, typrelid, typbyval, " + "(select usename from pg_user where typowner = usesysid) as usename, " + "format_type(pg_type.oid, NULL) as typedefn " + "from pg_type"); res = PQexec(g_conn, query->data); if (!res || @@ -1327,7 +1353,7 @@ getTypes(int *numTypes) tinfo[i].typedefn = strdup(PQgetvalue(res, i, i_typedefn)); if (strlen(tinfo[i].usename) == 0) - fprintf(stderr, "WARNING: owner of type '%s' appears to be invalid\n",tinfo[i].typname); + fprintf(stderr, "WARNING: owner of type '%s' appears to be invalid\n", tinfo[i].typname); if (strcmp(PQgetvalue(res, i, i_typbyval), "f") == 0) tinfo[i].passedbyvalue = 0; @@ -1392,9 +1418,9 @@ getOperators(int *numOprs) appendPQExpBuffer(query, "SELECT pg_operator.oid, oprname, oprkind, oprcode, " "oprleft, oprright, oprcom, oprnegate, oprrest, oprjoin, " - "oprcanhash, oprlsortop, oprrsortop, " - "(select usename from pg_user where oprowner = usesysid) as usename " - "from pg_operator"); + "oprcanhash, oprlsortop, oprrsortop, " + "(select usename from pg_user where oprowner = usesysid) as usename " + "from pg_operator"); res = PQexec(g_conn, query->data); if (!res || @@ -1443,7 +1469,7 @@ getOperators(int *numOprs) if (strlen(oprinfo[i].usename) == 0) fprintf(stderr, "WARNING: owner of operator '%s' appears to be invalid\n", - oprinfo[i].oprname); + oprinfo[i].oprname); } @@ -1553,8 +1579,9 @@ clearTableInfo(TableInfo *tblinfo, int numTables) free(tblinfo[i].typnames[j]); } - if (tblinfo[i].triggers) { - for (j = 0; j < tblinfo[i].ntrig ; j++) + if (tblinfo[i].triggers) + { + for (j = 0; j < tblinfo[i].ntrig; j++) { if (tblinfo[i].triggers[j].tgsrc) free(tblinfo[i].triggers[j].tgsrc); @@ -1738,18 +1765,18 @@ getAggregates(int *numAggs) /* find all user-defined aggregates */ appendPQExpBuffer(query, - "SELECT pg_aggregate.oid, aggname, aggtransfn, " - "aggfinalfn, aggtranstype, aggbasetype, " - "agginitval, " - "(select usename from pg_user where aggowner = usesysid) as usename " - "from pg_aggregate" ); + "SELECT pg_aggregate.oid, aggname, aggtransfn, " + "aggfinalfn, aggtranstype, aggbasetype, " + "agginitval, " + "(select usename from pg_user where aggowner = usesysid) as usename " + "from pg_aggregate"); res = PQexec(g_conn, query->data); if (!res || PQresultStatus(res) != PGRES_TUPLES_OK) { fprintf(stderr, "getAggregates(): SELECT failed. Explanation from backend: '%s'.\n", - PQerrorMessage(g_conn)); + PQerrorMessage(g_conn)); exit_nicely(g_conn); } @@ -1779,7 +1806,7 @@ getAggregates(int *numAggs) agginfo[i].usename = strdup(PQgetvalue(res, i, i_usename)); if (strlen(agginfo[i].usename) == 0) fprintf(stderr, "WARNING: owner of aggregate '%s' appears to be invalid\n", - agginfo[i].aggname); + agginfo[i].aggname); } @@ -1824,18 +1851,18 @@ getFuncs(int *numFuncs) appendPQExpBuffer(query, "SELECT pg_proc.oid, proname, prolang, pronargs, prorettype, " "proretset, proargtypes, prosrc, probin, " - "(select usename from pg_user where proowner = usesysid) as usename, " + "(select usename from pg_user where proowner = usesysid) as usename, " "proiscachable, proisstrict " "from pg_proc " - "where pg_proc.oid > '%u'::oid", + "where pg_proc.oid > '%u'::oid", g_last_builtin_oid); res = PQexec(g_conn, query->data); if (!res || PQresultStatus(res) != PGRES_TUPLES_OK) { - fprintf(stderr, "getFuncs(): SELECT failed. Explanation from backend: '%s'.\n", - PQerrorMessage(g_conn)); + fprintf(stderr, "getFuncs(): SELECT failed. Explanation from backend: '%s'.\n", + PQerrorMessage(g_conn)); exit_nicely(g_conn); } @@ -1873,12 +1900,12 @@ getFuncs(int *numFuncs) finfo[i].nargs = atoi(PQgetvalue(res, i, i_pronargs)); finfo[i].lang = atoi(PQgetvalue(res, i, i_prolang)); finfo[i].usename = strdup(PQgetvalue(res, i, i_usename)); - finfo[i].iscachable = (strcmp(PQgetvalue(res, i, i_iscachable),"t") == 0); - finfo[i].isstrict = (strcmp(PQgetvalue(res, i, i_isstrict),"t") == 0); + finfo[i].iscachable = (strcmp(PQgetvalue(res, i, i_iscachable), "t") == 0); + finfo[i].isstrict = (strcmp(PQgetvalue(res, i, i_isstrict), "t") == 0); if (strlen(finfo[i].usename) == 0) fprintf(stderr, "WARNING: owner of function '%s' appears to be invalid\n", - finfo[i].proname); + finfo[i].proname); if (finfo[i].nargs < 0 || finfo[i].nargs > FUNC_MAX_ARGS) { @@ -1941,21 +1968,21 @@ getTables(int *numTables, FuncInfo *finfo, int numFuncs) */ appendPQExpBuffer(query, - "SELECT pg_class.oid, relname, relkind, relacl, " - "(select usename from pg_user where relowner = usesysid) as usename, " + "SELECT pg_class.oid, relname, relkind, relacl, " + "(select usename from pg_user where relowner = usesysid) as usename, " "relchecks, reltriggers, relhasindex " "from pg_class " "where relname !~ '^pg_' " "and relkind in ('%c', '%c', '%c') " "order by oid", - RELKIND_RELATION, RELKIND_SEQUENCE, RELKIND_VIEW); + RELKIND_RELATION, RELKIND_SEQUENCE, RELKIND_VIEW); res = PQexec(g_conn, query->data); if (!res || PQresultStatus(res) != PGRES_TUPLES_OK) { - fprintf(stderr, "getTables(): SELECT failed. Explanation from backend: '%s'.\n", - PQerrorMessage(g_conn)); + fprintf(stderr, "getTables(): SELECT failed. Explanation from backend: '%s'.\n", + PQerrorMessage(g_conn)); exit_nicely(g_conn); } @@ -1986,7 +2013,7 @@ getTables(int *numTables, FuncInfo *finfo, int numFuncs) if (strlen(tblinfo[i].usename) == 0) fprintf(stderr, "WARNING: owner of table '%s' appears to be invalid\n", - tblinfo[i].relname); + tblinfo[i].relname); /* Get view definition */ if (strcmp(PQgetvalue(res, i, i_relkind), relkindview) == 0) @@ -2001,30 +2028,32 @@ getTables(int *numTables, FuncInfo *finfo, int numFuncs) if (!res2 || PQresultStatus(res2) != PGRES_TUPLES_OK) { fprintf(stderr, "getTables(): SELECT (for VIEW DEFINITION) failed. " - "Explanation from backend: %s", - PQerrorMessage(g_conn)); + "Explanation from backend: %s", + PQerrorMessage(g_conn)); exit_nicely(g_conn); } - if (PQntuples(res2) != 1) + if (PQntuples(res2) != 1) { if (PQntuples(res2) < 1) { fprintf(stderr, "getTables(): SELECT (for VIEW %s) returned no definitions", - tblinfo[i].relname); - } else { + tblinfo[i].relname); + } + else + { fprintf(stderr, "getTables(): SELECT (for VIEW %s) returned more than 1 definition", - tblinfo[i].relname); + tblinfo[i].relname); } exit_nicely(g_conn); } tblinfo[i].viewdef = strdup(PQgetvalue(res2, 0, 0)); - if (strlen(tblinfo[i].viewdef) == 0) + if (strlen(tblinfo[i].viewdef) == 0) { fprintf(stderr, "getTables(): SELECT (for VIEW %s) returned empty definition", - tblinfo[i].relname); + tblinfo[i].relname); exit_nicely(g_conn); } } @@ -2048,7 +2077,10 @@ getTables(int *numTables, FuncInfo *finfo, int numFuncs) tblinfo[i].relname, g_comment_end); - /* XXXX: Use LOJ maybe - need to compare with subsequent query for non-inherited */ + /* + * XXXX: Use LOJ maybe - need to compare with subsequent query + * for non-inherited + */ resetPQExpBuffer(query); appendPQExpBuffer(query, "SELECT rcname from pg_relcheck, pg_inherits as i " "where rcrelid = '%s'::oid " @@ -2064,7 +2096,7 @@ getTables(int *numTables, FuncInfo *finfo, int numFuncs) PQresultStatus(res2) != PGRES_TUPLES_OK) { fprintf(stderr, "getTables(): SELECT (for inherited CHECK) failed. " - "Explanation from backend: '%s'.\n", PQerrorMessage(g_conn)); + "Explanation from backend: '%s'.\n", PQerrorMessage(g_conn)); exit_nicely(g_conn); } ntups2 = PQntuples(res2); @@ -2158,17 +2190,17 @@ getTables(int *numTables, FuncInfo *finfo, int numFuncs) exit_nicely(g_conn); } - if (PQntuples(res2) > 1) { + if (PQntuples(res2) > 1) + { fprintf(stderr, "getTables(): SELECT (for PRIMARY KEY) produced more than one row on table %s.\n", tblinfo[i].relname); exit_nicely(g_conn); } - if (PQntuples(res2) == 1) { + if (PQntuples(res2) == 1) tblinfo[i].pkIndexOid = strdup(PQgetvalue(res2, 0, 0)); - } else { + else tblinfo[i].pkIndexOid = NULL; - } } else @@ -2178,7 +2210,7 @@ getTables(int *numTables, FuncInfo *finfo, int numFuncs) if (tblinfo[i].pkIndexOid != NULL) { PGresult *res2; - int n; + int n; resetPQExpBuffer(query); appendPQExpBuffer(query, @@ -2200,7 +2232,7 @@ getTables(int *numTables, FuncInfo *finfo, int numFuncs) { fprintf(stderr, "getTables(): SELECT (for PRIMARY KEY NAME) failed for table %s. " - "This is impossible but object with OID == %s have %d primary keys.\n", + "This is impossible but object with OID == %s have %d primary keys.\n", tblinfo[i].relname, tblinfo[i].oid, n); @@ -2210,7 +2242,7 @@ getTables(int *numTables, FuncInfo *finfo, int numFuncs) /* Sanity check on LOJ */ if (PQgetisnull(res2, 0, 0)) { - fprintf(stderr,"getTables(): SELECT (for PRIMARY KEY NAME) on table %s returned NULL value.\n", + fprintf(stderr, "getTables(): SELECT (for PRIMARY KEY NAME) on table %s returned NULL value.\n", tblinfo[i].relname); exit_nicely(g_conn); } @@ -2259,7 +2291,7 @@ getTables(int *numTables, FuncInfo *finfo, int numFuncs) PQresultStatus(res2) != PGRES_TUPLES_OK) { fprintf(stderr, "getTables(): SELECT (for TRIGGER) failed. " - "Explanation from backend: '%s'.\n", PQerrorMessage(g_conn)); + "Explanation from backend: '%s'.\n", PQerrorMessage(g_conn)); exit_nicely(g_conn); } ntups2 = PQntuples(res2); @@ -2280,7 +2312,7 @@ getTables(int *numTables, FuncInfo *finfo, int numFuncs) i_tgdeferrable = PQfnumber(res2, "tgdeferrable"); i_tginitdeferred = PQfnumber(res2, "tginitdeferred"); - tblinfo[i].triggers = (TrigInfo*) malloc(ntups2 * sizeof(TrigInfo)); + tblinfo[i].triggers = (TrigInfo *) malloc(ntups2 * sizeof(TrigInfo)); resetPQExpBuffer(query); for (i2 = 0; i2 < ntups2; i2++) { @@ -2339,16 +2371,17 @@ getTables(int *numTables, FuncInfo *finfo, int numFuncs) r = PQexec(g_conn, query->data); if (!r || PQresultStatus(r) != PGRES_TUPLES_OK) { - fprintf(stderr, "getTables(): SELECT (funcname) failed for trigger %s. Explanation from backend: '%s'.\n", - PQgetvalue(res2, i2, i_tgname), PQerrorMessage(g_conn)); + fprintf(stderr, "getTables(): SELECT (funcname) failed for trigger %s. Explanation from backend: '%s'.\n", + PQgetvalue(res2, i2, i_tgname), PQerrorMessage(g_conn)); exit_nicely(g_conn); } /* Sanity: Check we got only one tuple */ numFuncs = PQntuples(r); - if (numFuncs != 1) { - fprintf(stderr, "getTables(): SELECT (funcname) for trigger %s returned %d tuples. Expected 1.\n", - PQgetvalue(res2, i2, i_tgname), numFuncs); + if (numFuncs != 1) + { + fprintf(stderr, "getTables(): SELECT (funcname) for trigger %s returned %d tuples. Expected 1.\n", + PQgetvalue(res2, i2, i_tgname), numFuncs); exit_nicely(g_conn); } @@ -2359,10 +2392,10 @@ getTables(int *numTables, FuncInfo *finfo, int numFuncs) tgfunc = strdup(finfo[findx].proname); appendPQExpBuffer(delqry, "DROP TRIGGER %s ", - fmtId(PQgetvalue(res2, i2, i_tgname), - force_quotes)); + fmtId(PQgetvalue(res2, i2, i_tgname), + force_quotes)); appendPQExpBuffer(delqry, "ON %s;\n", - fmtId(tblinfo[i].relname, force_quotes)); + fmtId(tblinfo[i].relname, force_quotes)); resetPQExpBuffer(query); if (tgisconstraint) @@ -2469,7 +2502,7 @@ getTables(int *numTables, FuncInfo *finfo, int numFuncs) fmtId(tblinfo[i].relname, force_quotes)); tblinfo[i].triggers[i2].tgcomment = strdup(query->data); tblinfo[i].triggers[i2].oid = strdup(PQgetvalue(res2, i2, i_tgoid)); - tblinfo[i].triggers[i2].tgname = strdup(fmtId(PQgetvalue(res2, i2, i_tgname),false)); + tblinfo[i].triggers[i2].tgname = strdup(fmtId(PQgetvalue(res2, i2, i_tgname), false)); tblinfo[i].triggers[i2].tgdel = strdup(delqry->data); if (tgfunc) @@ -2478,9 +2511,7 @@ getTables(int *numTables, FuncInfo *finfo, int numFuncs) PQclear(res2); } else - { tblinfo[i].triggers = NULL; - } } @@ -2519,7 +2550,7 @@ getInherits(int *numInherits) if (!res || PQresultStatus(res) != PGRES_TUPLES_OK) { - fprintf(stderr, "getInherits(): SELECT failed. Explanation from backend: '%s'.\n", + fprintf(stderr, "getInherits(): SELECT failed. Explanation from backend: '%s'.\n", PQerrorMessage(g_conn)); exit_nicely(g_conn); } @@ -2592,7 +2623,7 @@ getTableAttrs(TableInfo *tblinfo, int numTables) appendPQExpBuffer(q, "SELECT a.oid as attoid, a.attnum, a.attname, t.typname, a.atttypmod, " "a.attnotnull, a.atthasdef, format_type(a.atttypid, a.atttypmod) as atttypedefn " "from pg_attribute a LEFT OUTER JOIN pg_type t ON a.atttypid = t.oid " - "where a.attrelid = '%s'::oid " + "where a.attrelid = '%s'::oid " "and a.attnum > 0 order by attnum", tblinfo[i].oid); res = PQexec(g_conn, q->data); @@ -2600,7 +2631,7 @@ getTableAttrs(TableInfo *tblinfo, int numTables) PQresultStatus(res) != PGRES_TUPLES_OK) { fprintf(stderr, "getTableAttrs(): SELECT failed. " - "Explanation from backend: '%s'.\n", PQerrorMessage(g_conn)); + "Explanation from backend: '%s'.\n", PQerrorMessage(g_conn)); exit_nicely(g_conn); } @@ -2670,9 +2701,10 @@ getTableAttrs(TableInfo *tblinfo, int numTables) /* Sanity: Check we got only one tuple */ numAttr = PQntuples(res2); - if (numAttr != 1) { - fprintf(stderr, "getTableAttrs(): SELECT (for DEFAULT) for attr %s returned %d tuples. Expected 1.\n", - tblinfo[i].attnames[j], numAttr); + if (numAttr != 1) + { + fprintf(stderr, "getTableAttrs(): SELECT (for DEFAULT) for attr %s returned %d tuples. Expected 1.\n", + tblinfo[i].attnames[j], numAttr); exit_nicely(g_conn); } @@ -2730,7 +2762,7 @@ getIndices(int *numIndices) appendPQExpBuffer(query, "SELECT i.oid, t1.oid as indoid, t1.relname as indexrelname, t2.relname as indrelname, " "i.indproc, i.indkey, i.indclass, " - "a.amname as indamname, i.indisunique, i.indisprimary " + "a.amname as indamname, i.indisunique, i.indisprimary " "from pg_index i, pg_class t1, pg_class t2, pg_am a " "WHERE t1.oid = i.indexrelid and t2.oid = i.indrelid " "and t1.relam = a.oid and i.indexrelid > '%u'::oid " @@ -2742,7 +2774,7 @@ getIndices(int *numIndices) PQresultStatus(res) != PGRES_TUPLES_OK) { fprintf(stderr, "getIndices(): SELECT failed. " - "Explanation from backend: '%s'.\n", PQerrorMessage(g_conn)); + "Explanation from backend: '%s'.\n", PQerrorMessage(g_conn)); exit_nicely(g_conn); } @@ -2833,8 +2865,8 @@ dumpComment(Archive *fout, const char *target, const char *oid) formatStringLiteral(query, PQgetvalue(res, 0, i_description), PASS_LFTAB); appendPQExpBuffer(query, ";\n"); - ArchiveEntry(fout, oid, target, "COMMENT", NULL, query->data, "" /*Del*/, - "" /* Copy */, "" /*Owner*/, NULL, NULL); + ArchiveEntry(fout, oid, target, "COMMENT", NULL, query->data, "" /* Del */ , + "" /* Copy */ , "" /* Owner */ , NULL, NULL); } @@ -2905,7 +2937,7 @@ dumpTypes(Archive *fout, FuncInfo *finfo, int numFuncs, { int i; PQExpBuffer q = createPQExpBuffer(); - PQExpBuffer delq = createPQExpBuffer(); + PQExpBuffer delq = createPQExpBuffer(); int funcInd; for (i = 0; i < numTypes; i++) @@ -2979,7 +3011,7 @@ dumpTypes(Archive *fout, FuncInfo *finfo, int numFuncs, appendPQExpBuffer(q, ");\n"); ArchiveEntry(fout, tinfo[i].oid, tinfo[i].typname, "TYPE", NULL, - q->data, delq->data, "", tinfo[i].usename, NULL, NULL); + q->data, delq->data, "", tinfo[i].usename, NULL, NULL); /*** Dump Type Comments ***/ @@ -3054,7 +3086,7 @@ dumpProcLangs(Archive *fout, FuncInfo *finfo, int numFuncs, if (fidx >= numFuncs) { fprintf(stderr, "dumpProcLangs(): handler procedure for " - "language %s not found\n", PQgetvalue(res, i, i_lanname)); + "language %s not found\n", PQgetvalue(res, i, i_lanname)); exit_nicely(g_conn); } @@ -3077,7 +3109,7 @@ dumpProcLangs(Archive *fout, FuncInfo *finfo, int numFuncs, appendPQExpBuffer(defqry, ";\n"); ArchiveEntry(fout, PQgetvalue(res, i, i_oid), lanname, "PROCEDURAL LANGUAGE", - NULL, defqry->data, delqry->data, "", "", NULL, NULL); + NULL, defqry->data, delqry->data, "", "", NULL, NULL); resetPQExpBuffer(defqry); resetPQExpBuffer(delqry); @@ -3125,10 +3157,10 @@ dumpOneFunc(Archive *fout, FuncInfo *finfo, int i, int i_lanname; char query[256]; - char *listSep; - char *listSepComma = ","; - char *listSepNone = ""; - char *rettypename; + char *listSep; + char *listSepComma = ","; + char *listSepNone = ""; + char *rettypename; if (finfo[i].dumped) return; @@ -3142,23 +3174,23 @@ dumpOneFunc(Archive *fout, FuncInfo *finfo, int i, res = PQexec(g_conn, query); if (!res || PQresultStatus(res) != PGRES_TUPLES_OK) - { + { fprintf(stderr, "dumpOneFunc(): SELECT for procedural language failed. Explanation from backend: '%s'.\n", PQerrorMessage(g_conn)); exit_nicely(g_conn); - } + } nlangs = PQntuples(res); if (nlangs != 1) - { + { fprintf(stderr, "dumpOneFunc(): procedural language for function %s not found\n", finfo[i].proname); exit_nicely(g_conn); - } - + } + i_lanname = PQfnumber(res, "lanname"); /* - * See backend/commands/define.c for details of how the 'AS' clause - * is used. + * See backend/commands/define.c for details of how the 'AS' clause is + * used. */ if (strcmp(finfo[i].probin, "-") != 0) { @@ -3180,14 +3212,14 @@ dumpOneFunc(Archive *fout, FuncInfo *finfo, int i, } strcpy(func_lang, PQgetvalue(res, 0, i_lanname)); - + PQclear(res); - + resetPQExpBuffer(fn); appendPQExpBuffer(fn, "%s (", fmtId(finfo[i].proname, force_quotes)); for (j = 0; j < finfo[i].nargs; j++) { - char *typname; + char *typname; typname = findTypeByOid(tinfo, numTypes, finfo[i].argtypes[j], zeroAsOpaque); if (typname == NULL) @@ -3205,17 +3237,17 @@ dumpOneFunc(Archive *fout, FuncInfo *finfo, int i, return; } - appendPQExpBuffer(fn, "%s%s", - (j > 0) ? "," : "", - typname); + appendPQExpBuffer(fn, "%s%s", + (j > 0) ? "," : "", + typname); appendPQExpBuffer(fnlist, "%s%s", - (j > 0) ? "," : "", - typname ); + (j > 0) ? "," : "", + typname); } appendPQExpBuffer(fn, ")"); resetPQExpBuffer(delqry); - appendPQExpBuffer(delqry, "DROP FUNCTION %s;\n", fn->data ); + appendPQExpBuffer(delqry, "DROP FUNCTION %s;\n", fn->data); rettypename = findTypeByOid(tinfo, numTypes, finfo[i].prorettype, zeroAsOpaque); @@ -3226,33 +3258,35 @@ dumpOneFunc(Archive *fout, FuncInfo *finfo, int i, fprintf(stderr, "Reason: return type name (oid %s) not found.\n", finfo[i].prorettype); - resetPQExpBuffer(q); - resetPQExpBuffer(fn); - resetPQExpBuffer(delqry); - resetPQExpBuffer(fnlist); - resetPQExpBuffer(asPart); - return; + resetPQExpBuffer(q); + resetPQExpBuffer(fn); + resetPQExpBuffer(delqry); + resetPQExpBuffer(fnlist); + resetPQExpBuffer(asPart); + return; } resetPQExpBuffer(q); - appendPQExpBuffer(q, "CREATE FUNCTION %s ", fn->data ); + appendPQExpBuffer(q, "CREATE FUNCTION %s ", fn->data); appendPQExpBuffer(q, "RETURNS %s%s %s LANGUAGE ", (finfo[i].retset) ? "SETOF " : "", rettypename, asPart->data); formatStringLiteral(q, func_lang, CONV_ALL); - if (finfo[i].iscachable || finfo[i].isstrict) /* OR in new attrs here */ + if (finfo[i].iscachable || finfo[i].isstrict) /* OR in new attrs here */ { appendPQExpBuffer(q, " WITH ("); listSep = listSepNone; - if (finfo[i].iscachable) { + if (finfo[i].iscachable) + { appendPQExpBuffer(q, "%s iscachable", listSep); listSep = listSepComma; } - if (finfo[i].isstrict) { + if (finfo[i].isstrict) + { appendPQExpBuffer(q, "%s isstrict", listSep); listSep = listSepComma; } @@ -3262,7 +3296,7 @@ dumpOneFunc(Archive *fout, FuncInfo *finfo, int i, appendPQExpBuffer(q, ";\n"); ArchiveEntry(fout, finfo[i].oid, fn->data, "FUNCTION", NULL, q->data, delqry->data, - "", finfo[i].usename, NULL, NULL); + "", finfo[i].usename, NULL, NULL); /*** Dump Function Comments ***/ @@ -3303,7 +3337,7 @@ dumpOprs(Archive *fout, OprInfo *oprinfo, int numOperators, for (i = 0; i < numOperators; i++) { - char *name; + char *name; resetPQExpBuffer(leftarg); resetPQExpBuffer(rightarg); @@ -3332,21 +3366,21 @@ dumpOprs(Archive *fout, OprInfo *oprinfo, int numOperators, if (strcmp(oprinfo[i].oprkind, "r") == 0 || strcmp(oprinfo[i].oprkind, "b") == 0) { - name = findTypeByOid(tinfo, numTypes, - oprinfo[i].oprleft, zeroAsOpaque); + name = findTypeByOid(tinfo, numTypes, + oprinfo[i].oprleft, zeroAsOpaque); if (name == NULL) { OPR_NOTICE(oprleft); continue; } - appendPQExpBuffer(leftarg, ",\n\tLEFTARG = %s ",name); + appendPQExpBuffer(leftarg, ",\n\tLEFTARG = %s ", name); } if (strcmp(oprinfo[i].oprkind, "l") == 0 || strcmp(oprinfo[i].oprkind, "b") == 0) { - name = findTypeByOid(tinfo, numTypes, - oprinfo[i].oprright, zeroAsOpaque); + name = findTypeByOid(tinfo, numTypes, + oprinfo[i].oprright, zeroAsOpaque); if (name == NULL) { OPR_NOTICE(oprright); @@ -3385,7 +3419,7 @@ dumpOprs(Archive *fout, OprInfo *oprinfo, int numOperators, if (!(strcmp(oprinfo[i].oprlsortop, "0") == 0)) { - name = findOprByOid(oprinfo, numOperators, oprinfo[i].oprlsortop); + name = findOprByOid(oprinfo, numOperators, oprinfo[i].oprlsortop); if (name == NULL) { OPR_NOTICE(oprlsortop); @@ -3396,7 +3430,7 @@ dumpOprs(Archive *fout, OprInfo *oprinfo, int numOperators, if (!(strcmp(oprinfo[i].oprrsortop, "0") == 0)) { - name = findOprByOid(oprinfo, numOperators, oprinfo[i].oprrsortop); + name = findOprByOid(oprinfo, numOperators, oprinfo[i].oprrsortop); if (name == NULL) { OPR_NOTICE(oprrsortop); @@ -3407,9 +3441,9 @@ dumpOprs(Archive *fout, OprInfo *oprinfo, int numOperators, resetPQExpBuffer(delq); appendPQExpBuffer(delq, "DROP OPERATOR %s (%s", oprinfo[i].oprname, - findTypeByOid(tinfo, numTypes, oprinfo[i].oprleft, zeroAsOpaque) ); + findTypeByOid(tinfo, numTypes, oprinfo[i].oprleft, zeroAsOpaque)); appendPQExpBuffer(delq, ", %s);\n", - findTypeByOid(tinfo, numTypes, oprinfo[i].oprright, zeroAsOpaque) ); + findTypeByOid(tinfo, numTypes, oprinfo[i].oprright, zeroAsOpaque)); resetPQExpBuffer(q); appendPQExpBuffer(q, @@ -3422,13 +3456,13 @@ dumpOprs(Archive *fout, OprInfo *oprinfo, int numOperators, commutator->data, negator->data, restrictor->data, - (strcmp(oprinfo[i].oprcanhash, "t") == 0) ? ",\n\tHASHES" : "", + (strcmp(oprinfo[i].oprcanhash, "t") == 0) ? ",\n\tHASHES" : "", join->data, sort1->data, sort2->data); ArchiveEntry(fout, oprinfo[i].oid, oprinfo[i].oprname, "OPERATOR", NULL, - q->data, delq->data, "", oprinfo[i].usename, NULL, NULL); + q->data, delq->data, "", oprinfo[i].usename, NULL, NULL); } } @@ -3455,7 +3489,7 @@ dumpAggs(Archive *fout, AggInfo *agginfo, int numAggs, for (i = 0; i < numAggs; i++) { - char *name; + char *name; resetPQExpBuffer(details); @@ -3493,7 +3527,7 @@ dumpAggs(Archive *fout, AggInfo *agginfo, int numAggs, resetPQExpBuffer(aggSig); appendPQExpBuffer(aggSig, "%s %s", agginfo[i].aggname, - findTypeByOid(tinfo, numTypes, agginfo[i].aggbasetype, zeroAsOpaque + useBaseTypeName)); + findTypeByOid(tinfo, numTypes, agginfo[i].aggbasetype, zeroAsOpaque + useBaseTypeName)); resetPQExpBuffer(delq); appendPQExpBuffer(delq, "DROP AGGREGATE %s;\n", aggSig->data); @@ -3504,7 +3538,7 @@ dumpAggs(Archive *fout, AggInfo *agginfo, int numAggs, details->data); ArchiveEntry(fout, agginfo[i].oid, aggSig->data, "AGGREGATE", NULL, - q->data, delq->data, "", agginfo[i].usename, NULL, NULL); + q->data, delq->data, "", agginfo[i].usename, NULL, NULL); /*** Dump Aggregate Comments ***/ @@ -3564,19 +3598,22 @@ GetPrivileges(const char *s) } /* - * The name says it all; a function to append a string is the dest + * The name says it all; a function to append a string is the dest * is big enough. If not, it does a realloc. */ -static void strcatalloc(char **dest, int *dSize, char *src) +static void +strcatalloc(char **dest, int *dSize, char *src) { - int dLen = strlen(*dest); - int sLen = strlen(src); - if ( (dLen + sLen) >= *dSize) { - *dSize = (dLen + sLen) * 2; - *dest = realloc(*dest, *dSize); - } - strcpy(*dest + dLen, src); -} + int dLen = strlen(*dest); + int sLen = strlen(src); + + if ((dLen + sLen) >= *dSize) + { + *dSize = (dLen + sLen) * 2; + *dest = realloc(*dest, *dSize); + } + strcpy(*dest + dLen, src); +} /* @@ -3588,14 +3625,14 @@ static void strcatalloc(char **dest, int *dSize, char *src) static void dumpACL(Archive *fout, TableInfo tbinfo) { - const char *acls = tbinfo.relacl; - char *aclbuf, + const char *acls = tbinfo.relacl; + char *aclbuf, *tok, *eqpos, *priv; - char *sql; + char *sql; char tmp[1024]; - int sSize = 4096; + int sSize = 4096; if (strlen(acls) == 0) return; /* table has default permissions */ @@ -3603,13 +3640,13 @@ dumpACL(Archive *fout, TableInfo tbinfo) /* * Allocate a larginsh buffer for the output SQL. */ - sql = (char*)malloc(sSize); + sql = (char *) malloc(sSize); /* * Revoke Default permissions for PUBLIC. Is this actually necessary, * or is it just a waste of time? */ - sprintf(sql, "REVOKE ALL on %s from PUBLIC;\n", + sprintf(sql, "REVOKE ALL on %s from PUBLIC;\n", fmtId(tbinfo.relname, force_quotes)); /* Make a working copy of acls so we can use strtok */ @@ -3644,7 +3681,7 @@ dumpACL(Archive *fout, TableInfo tbinfo) priv = GetPrivileges(eqpos + 1); if (*priv) { - sprintf(tmp, "GRANT %s on %s to ", + sprintf(tmp, "GRANT %s on %s to ", priv, fmtId(tbinfo.relname, force_quotes)); strcatalloc(&sql, &sSize, tmp); @@ -3770,13 +3807,13 @@ dumpTables(Archive *fout, TableInfo *tblinfo, int numTables, /* Attr name & type */ appendPQExpBuffer(q, "%s %s", - fmtId(tblinfo[i].attnames[j], force_quotes), - tblinfo[i].atttypedefns[j]); + fmtId(tblinfo[i].attnames[j], force_quotes), + tblinfo[i].atttypedefns[j]); /* Default value */ if (tblinfo[i].adef_expr[j] != NULL) appendPQExpBuffer(q, " DEFAULT %s", - tblinfo[i].adef_expr[j]); + tblinfo[i].adef_expr[j]); /* Not Null constraint */ if (tblinfo[i].notnull[j]) @@ -3795,31 +3832,31 @@ dumpTables(Archive *fout, TableInfo *tblinfo, int numTables, appendPQExpBuffer(q, ",\n\t"); appendPQExpBuffer(q, "%s", - tblinfo[i].check_expr[k]); + tblinfo[i].check_expr[k]); } /* Primary Key */ if (tblinfo[i].pkIndexOid != NULL) { - PQExpBuffer consDef; + PQExpBuffer consDef; /* Find the corresponding index */ for (k = 0; k < numIndices; k++) { - if (strcmp(indinfo[k].oid, tblinfo[i].pkIndexOid) == 0) + if (strcmp(indinfo[k].oid, tblinfo[i].pkIndexOid) == 0) break; } if (k >= numIndices) { fprintf(stderr, "dumpTables(): failed sanity check, could not find index (%s) for PK constraint\n", - tblinfo[i].pkIndexOid); + tblinfo[i].pkIndexOid); exit_nicely(g_conn); } consDef = getPKconstraint(&tblinfo[i], &indinfo[k]); - if ( (actual_atts + tblinfo[i].ncheck) > 0) + if ((actual_atts + tblinfo[i].ncheck) > 0) appendPQExpBuffer(q, ",\n\t"); appendPQExpBuffer(q, "%s", consDef->data); @@ -3836,8 +3873,8 @@ dumpTables(Archive *fout, TableInfo *tblinfo, int numTables, for (k = 0; k < numParents; k++) { appendPQExpBuffer(q, "%s%s", - (k > 0) ? ", " : "", - fmtId(parentRels[k], force_quotes)); + (k > 0) ? ", " : "", + fmtId(parentRels[k], force_quotes)); } appendPQExpBuffer(q, ")"); } @@ -3845,11 +3882,12 @@ dumpTables(Archive *fout, TableInfo *tblinfo, int numTables, appendPQExpBuffer(q, ";\n"); } - if (!dataOnly) { + if (!dataOnly) + { ArchiveEntry(fout, tblinfo[i].oid, tblinfo[i].relname, - reltypename, NULL, q->data, delq->data, "", tblinfo[i].usename, - NULL, NULL); + reltypename, NULL, q->data, delq->data, "", tblinfo[i].usename, + NULL, NULL); if (!aclsSkip) dumpACL(fout, tblinfo[i]); @@ -3877,16 +3915,17 @@ dumpTables(Archive *fout, TableInfo *tblinfo, int numTables, } } -static PQExpBuffer getPKconstraint(TableInfo *tblInfo, IndInfo *indInfo) +static PQExpBuffer +getPKconstraint(TableInfo *tblInfo, IndInfo *indInfo) { - PQExpBuffer pkBuf = createPQExpBuffer(); - int k; - int indkey; + PQExpBuffer pkBuf = createPQExpBuffer(); + int k; + int indkey; - resetPQExpBuffer(pkBuf); + resetPQExpBuffer(pkBuf); appendPQExpBuffer(pkBuf, "Constraint %s Primary Key (", - tblInfo->primary_key_name); + tblInfo->primary_key_name); for (k = 0; k < INDEX_MAX_KEYS; k++) @@ -3903,8 +3942,8 @@ static PQExpBuffer getPKconstraint(TableInfo *tblInfo, IndInfo *indInfo) attname = tblInfo->attnames[indkey]; appendPQExpBuffer(pkBuf, "%s%s", - (k == 0) ? "" : ", ", - fmtId(attname, force_quotes)); + (k == 0) ? "" : ", ", + fmtId(attname, force_quotes)); } appendPQExpBuffer(pkBuf, ")"); @@ -3954,21 +3993,25 @@ dumpIndices(Archive *fout, IndInfo *indinfo, int numIndices, /* * ***PK: Enable this code when ALTER TABLE supports PK constraints. *** * - * PQExpBuffer consDef = getPKconstraint(&tblinfo[tableInd], &indinfo[i]); + * PQExpBuffer consDef = getPKconstraint(&tblinfo[tableInd], &indinfo[i]); * * resetPQExpBuffer(attlist); * - * appendPQExpBuffer(attlist, "Alter Table %s Add %s;", + * appendPQExpBuffer(attlist, "Alter Table %s Add %s;", * fmtId(tblinfo[tableInd].relname, force_quotes), * consDef->data); * - * ArchiveEntry(fout, indinfo[i].oid, tblinfo[tableInd].primary_key_name, "CONSTRAINT", NULL, + * ArchiveEntry(fout, indinfo[i].oid, tblinfo[tableInd].primary_key_name, "CONSTRAINT", NULL, * attlist->data, "", * "", tblinfo[tableInd].usename, NULL, NULL); * * destroyPQExpBuffer(consDef); */ - /* Don't need to do anything else for this system-generated index */ + + /* + * Don't need to do anything else for this system-generated + * index + */ continue; } @@ -3977,7 +4020,7 @@ dumpIndices(Archive *fout, IndInfo *indinfo, int numIndices, funcname = NULL; else { - int numFuncs; + int numFuncs; /* * the funcname is an oid which we use to find the name of the @@ -4000,9 +4043,10 @@ dumpIndices(Archive *fout, IndInfo *indinfo, int numIndices, /* Sanity: Check we got only one tuple */ numFuncs = PQntuples(res); - if (numFuncs != 1) { - fprintf(stderr, "dumpIndices(): SELECT (funcname) for index %s returned %d tuples. Expected 1.\n", - indinfo[i].indrelname, numFuncs); + if (numFuncs != 1) + { + fprintf(stderr, "dumpIndices(): SELECT (funcname) for index %s returned %d tuples. Expected 1.\n", + indinfo[i].indrelname, numFuncs); exit_nicely(g_conn); } @@ -4013,7 +4057,7 @@ dumpIndices(Archive *fout, IndInfo *indinfo, int numIndices, /* convert opclass oid(s) into names */ for (nclass = 0; nclass < INDEX_MAX_KEYS; nclass++) { - int numRows; + int numRows; indclass = atoi(indinfo[i].indclass[nclass]); if (indclass == 0) @@ -4027,15 +4071,16 @@ dumpIndices(Archive *fout, IndInfo *indinfo, int numIndices, if (!res || PQresultStatus(res) != PGRES_TUPLES_OK) { fprintf(stderr, "dumpIndices(): SELECT (classname) failed. " - "Explanation from backend: '%s'.\n", PQerrorMessage(g_conn)); + "Explanation from backend: '%s'.\n", PQerrorMessage(g_conn)); exit_nicely(g_conn); } /* Sanity: Check we got only one tuple */ numRows = PQntuples(res); - if (numRows != 1) { - fprintf(stderr, "dumpIndices(): SELECT (classname) for index %s returned %d tuples. Expected 1.\n", - indinfo[i].indrelname, numRows); + if (numRows != 1) + { + fprintf(stderr, "dumpIndices(): SELECT (classname) for index %s returned %d tuples. Expected 1.\n", + indinfo[i].indrelname, numRows); exit_nicely(g_conn); } @@ -4086,7 +4131,7 @@ dumpIndices(Archive *fout, IndInfo *indinfo, int numIndices, } } - if (!tablename || (strcmp(indinfo[i].indrelname, tablename) == 0) || (strlen(tablename) == 0) ) + if (!tablename || (strcmp(indinfo[i].indrelname, tablename) == 0) || (strlen(tablename) == 0)) { /* @@ -4105,16 +4150,16 @@ dumpIndices(Archive *fout, IndInfo *indinfo, int numIndices, resetPQExpBuffer(q); appendPQExpBuffer(q, "CREATE %s INDEX %s on %s using %s (", - (strcmp(indinfo[i].indisunique, "t") == 0) ? "UNIQUE" : "", - id1->data, - id2->data, - indinfo[i].indamname); + (strcmp(indinfo[i].indisunique, "t") == 0) ? "UNIQUE" : "", + id1->data, + id2->data, + indinfo[i].indamname); if (funcname) { /* need 2 printf's here cuz fmtId has static return area */ appendPQExpBuffer(q, " %s", fmtId(funcname, false)); - appendPQExpBuffer(q, " (%s) %s );\n", attlist->data, - fmtId(classname[0], force_quotes)); + appendPQExpBuffer(q, " (%s) %s );\n", attlist->data, + fmtId(classname[0], force_quotes)); free(funcname); free(classname[0]); } @@ -4124,7 +4169,7 @@ dumpIndices(Archive *fout, IndInfo *indinfo, int numIndices, /* Dump Index Comments */ ArchiveEntry(fout, tblinfo[tableInd].oid, id1->data, "INDEX", NULL, q->data, delq->data, - "", tblinfo[tableInd].usename, NULL, NULL); + "", tblinfo[tableInd].usename, NULL, NULL); resetPQExpBuffer(q); appendPQExpBuffer(q, "INDEX %s", id1->data); @@ -4208,17 +4253,17 @@ dumpTuples(PGresult *res, FILE *fout, int *attrmap) static void setMaxOid(Archive *fout) { - PGresult *res; - Oid max_oid; + PGresult *res; + Oid max_oid; char sql[1024]; - int pos; + int pos; res = PQexec(g_conn, "CREATE TEMPORARY TABLE pgdump_oid (dummy int4)"); if (!res || PQresultStatus(res) != PGRES_COMMAND_OK) { fprintf(stderr, "Can not create pgdump_oid table. " - "Explanation from backend: '%s'.\n", PQerrorMessage(g_conn)); + "Explanation from backend: '%s'.\n", PQerrorMessage(g_conn)); exit_nicely(g_conn); } PQclear(res); @@ -4227,7 +4272,7 @@ setMaxOid(Archive *fout) PQresultStatus(res) != PGRES_COMMAND_OK) { fprintf(stderr, "Can not insert into pgdump_oid table. " - "Explanation from backend: '%s'.\n", PQerrorMessage(g_conn)); + "Explanation from backend: '%s'.\n", PQerrorMessage(g_conn)); exit_nicely(g_conn); } max_oid = atol(PQoidStatus(res)); @@ -4242,7 +4287,7 @@ setMaxOid(Archive *fout) PQresultStatus(res) != PGRES_COMMAND_OK) { fprintf(stderr, "Can not drop pgdump_oid table. " - "Explanation from backend: '%s'.\n", PQerrorMessage(g_conn)); + "Explanation from backend: '%s'.\n", PQerrorMessage(g_conn)); exit_nicely(g_conn); } PQclear(res); @@ -4250,10 +4295,10 @@ setMaxOid(Archive *fout) fprintf(stderr, "%s maximum system oid is %u %s\n", g_comment_start, max_oid, g_comment_end); pos = snprintf(sql, 1024, "CREATE TEMPORARY TABLE pgdump_oid (dummy int4);\n"); - pos = pos + snprintf(sql+pos, 1024-pos, "COPY pgdump_oid WITH OIDS FROM stdin;\n"); - pos = pos + snprintf(sql+pos, 1024-pos, "%-d\t0\n", max_oid); - pos = pos + snprintf(sql+pos, 1024-pos, "\\.\n"); - pos = pos + snprintf(sql+pos, 1024-pos, "DROP TABLE pgdump_oid;\n"); + pos = pos + snprintf(sql + pos, 1024 - pos, "COPY pgdump_oid WITH OIDS FROM stdin;\n"); + pos = pos + snprintf(sql + pos, 1024 - pos, "%-d\t0\n", max_oid); + pos = pos + snprintf(sql + pos, 1024 - pos, "\\.\n"); + pos = pos + snprintf(sql + pos, 1024 - pos, "DROP TABLE pgdump_oid;\n"); ArchiveEntry(fout, "0", "Max OID", "<Init>", NULL, sql, "", "", "", NULL, NULL); } @@ -4265,7 +4310,7 @@ setMaxOid(Archive *fout) */ static Oid -findLastBuiltinOid(const char* dbname) +findLastBuiltinOid(const char *dbname) { PGresult *res; int ntups; @@ -4327,7 +4372,7 @@ dumpSequence(Archive *fout, TableInfo tbinfo, const bool schemaOnly, const bool if (!res || PQresultStatus(res) != PGRES_TUPLES_OK) { fprintf(stderr, "dumpSequence(%s): SELECT failed. " - "Explanation from backend: '%s'.\n", tbinfo.relname, PQerrorMessage(g_conn)); + "Explanation from backend: '%s'.\n", tbinfo.relname, PQerrorMessage(g_conn)); exit_nicely(g_conn); } @@ -4358,10 +4403,10 @@ dumpSequence(Archive *fout, TableInfo tbinfo, const bool schemaOnly, const bool called = *t; /* - * The logic we use for restoring sequences is as follows: - * - Add a basic CREATE SEQUENCE statement - * (use last_val for start if called == 'f', else use min_val for start_val). - * - Add a 'SETVAL(seq, last_val, iscalled)' at restore-time iff we load data + * The logic we use for restoring sequences is as follows: - Add a + * basic CREATE SEQUENCE statement (use last_val for start if called + * == 'f', else use min_val for start_val). - Add a 'SETVAL(seq, + * last_val, iscalled)' at restore-time iff we load data */ if (!dataOnly) @@ -4373,15 +4418,15 @@ dumpSequence(Archive *fout, TableInfo tbinfo, const bool schemaOnly, const bool resetPQExpBuffer(query); appendPQExpBuffer(query, - "CREATE SEQUENCE %s start %d increment %d maxvalue %d " + "CREATE SEQUENCE %s start %d increment %d maxvalue %d " "minvalue %d cache %d %s;\n", - fmtId(tbinfo.relname, force_quotes), + fmtId(tbinfo.relname, force_quotes), (called == 't') ? minv : last, incby, maxv, minv, cache, (cycled == 't') ? "cycle" : ""); ArchiveEntry(fout, tbinfo.oid, tbinfo.relname, "SEQUENCE", NULL, - query->data, delqry->data, "", tbinfo.usename, NULL, NULL); + query->data, delqry->data, "", tbinfo.usename, NULL, NULL); } if (!schemaOnly) @@ -4392,7 +4437,7 @@ dumpSequence(Archive *fout, TableInfo tbinfo, const bool schemaOnly, const bool appendPQExpBuffer(query, ", %d, '%c');\n", last, called); ArchiveEntry(fout, tbinfo.oid, tbinfo.relname, "SEQUENCE SET", NULL, - query->data, "" /* Del */, "", "", NULL, NULL); + query->data, "" /* Del */ , "", "", NULL, NULL); } if (!dataOnly) @@ -4419,14 +4464,14 @@ dumpTriggers(Archive *fout, const char *tablename, for (i = 0; i < numTables; i++) { - if (tablename && (strcmp(tblinfo[i].relname, tablename) != 0) && (strlen(tablename) > 0) ) + if (tablename && (strcmp(tblinfo[i].relname, tablename) != 0) && (strlen(tablename) > 0)) continue; for (j = 0; j < tblinfo[i].ntrig; j++) { ArchiveEntry(fout, tblinfo[i].triggers[j].oid, tblinfo[i].triggers[j].tgname, - "TRIGGER", NULL, tblinfo[i].triggers[j].tgsrc, "", "", - tblinfo[i].usename, NULL, NULL); + "TRIGGER", NULL, tblinfo[i].triggers[j].tgsrc, "", "", + tblinfo[i].usename, NULL, NULL); dumpComment(fout, tblinfo[i].triggers[j].tgcomment, tblinfo[i].triggers[j].oid); } } @@ -4457,13 +4502,12 @@ dumpRules(Archive *fout, const char *tablename, */ for (t = 0; t < numTables; t++) { - if (tablename && (strcmp(tblinfo[t].relname, tablename) != 0) && (strlen(tablename) > 0) ) + if (tablename && (strcmp(tblinfo[t].relname, tablename) != 0) && (strlen(tablename) > 0)) continue; /* - * Get all rules defined for this table - * We include pg_rules in the cross since it filters out - * all view rules (pjw 15-Sep-2000). + * Get all rules defined for this table We include pg_rules in the + * cross since it filters out all view rules (pjw 15-Sep-2000). * * XXXX: Use LOJ here */ @@ -4477,7 +4521,7 @@ dumpRules(Archive *fout, const char *tablename, appendPQExpBuffer(query, " AND pg_rewrite.ev_class = pg_class.oid " " AND pg_rules.tablename = pg_class.relname " - " AND pg_rules.rulename = pg_rewrite.rulename " + " AND pg_rules.rulename = pg_rewrite.rulename " "ORDER BY pg_rewrite.oid"); res = PQexec(g_conn, query->data); if (!res || @@ -4501,8 +4545,8 @@ dumpRules(Archive *fout, const char *tablename, for (i = 0; i < nrules; i++) { ArchiveEntry(fout, PQgetvalue(res, i, i_oid), PQgetvalue(res, i, i_rulename), - "RULE", NULL, PQgetvalue(res, i, i_definition), - "", "", PQgetvalue(res, i, i_owner), NULL, NULL); + "RULE", NULL, PQgetvalue(res, i, i_definition), + "", "", PQgetvalue(res, i, i_owner), NULL, NULL); /* Dump rule comments */ @@ -4515,4 +4559,3 @@ dumpRules(Archive *fout, const char *tablename, PQclear(res); } } - diff --git a/src/bin/pg_dump/pg_dump.h b/src/bin/pg_dump/pg_dump.h index 7488221346..ae481cfa80 100644 --- a/src/bin/pg_dump/pg_dump.h +++ b/src/bin/pg_dump/pg_dump.h @@ -6,7 +6,7 @@ * Portions Copyright (c) 1996-2001, PostgreSQL Global Development Group * Portions Copyright (c) 1994, Regents of the University of California * - * $Id: pg_dump.h,v 1.58 2001/02/10 02:31:27 tgl Exp $ + * $Id: pg_dump.h,v 1.59 2001/03/22 04:00:15 momjian Exp $ * * Modifications - 6/12/96 - dave@bensoft.com - version 1.13.dhb.2 * @@ -19,8 +19,8 @@ * in pg_dump.c * * Modifications - 14-Sep-2000 - pjw@rhyme.com.au - * - Added typedefn fields to typeinfo and relinfo - * - Added enum for findTypeByOid to allow special handling of + * - Added typedefn fields to typeinfo and relinfo + * - Added enum for findTypeByOid to allow special handling of * '0' OID. * *------------------------------------------------------------------------- @@ -114,9 +114,9 @@ typedef struct _tableInfo int ncheck; /* # of CHECK expressions */ char **check_expr; /* [CONSTRAINT name] CHECK expressions */ int ntrig; /* # of triggers */ - TrigInfo *triggers; /* Triggers on the table */ + TrigInfo *triggers; /* Triggers on the table */ char *pkIndexOid; /* Primary Key index OID */ - char *primary_key_name; /* PRIMARY KEY name, if any */ + char *primary_key_name; /* PRIMARY KEY name, if any */ } TableInfo; typedef struct _inhInfo @@ -209,10 +209,11 @@ extern void dumpSchemaIdx(Archive *fout, TableInfo *tblinfo, int numTables); -typedef enum _OidOptions { +typedef enum _OidOptions +{ zeroAsOpaque = 1, zeroAsAny = 2, - useBaseTypeName = 1024 + useBaseTypeName = 1024 } OidOptions; extern char *findTypeByOid(TypeInfo *tinfo, int numTypes, const char *oid, OidOptions opts); diff --git a/src/bin/pg_dump/pg_restore.c b/src/bin/pg_dump/pg_restore.c index 073930c23f..7b4ec4c1f1 100644 --- a/src/bin/pg_dump/pg_restore.c +++ b/src/bin/pg_dump/pg_restore.c @@ -2,7 +2,7 @@ * * pg_restore.c * pg_restore is an utility extracting postgres database definitions - * from a backup archive created by pg_dump using the archiver + * from a backup archive created by pg_dump using the archiver * interface. * * pg_restore will read the backup archive and @@ -19,22 +19,22 @@ * the output script is SQL that is understood by PostgreSQL * * Basic process in a restore operation is: - * - * Open the Archive and read the TOC. - * Set flags in TOC entries, and *maybe* reorder them. - * Generate script to stdout - * Exit + * + * Open the Archive and read the TOC. + * Set flags in TOC entries, and *maybe* reorder them. + * Generate script to stdout + * Exit * * Copyright (c) 2000, Philip Warner - * Rights are granted to use this software in any way so long - * as this notice is not removed. + * Rights are granted to use this software in any way so long + * as this notice is not removed. * * The author is not responsible for loss or damages that may * result from it's use. * * * IDENTIFICATION - * $Header: /cvsroot/pgsql/src/bin/pg_dump/pg_restore.c,v 1.18 2001/03/19 02:35:29 pjw Exp $ + * $Header: /cvsroot/pgsql/src/bin/pg_dump/pg_restore.c,v 1.19 2001/03/22 04:00:15 momjian Exp $ * * Modifications - 28-Jun-2000 - pjw@rhyme.com.au * @@ -42,7 +42,7 @@ * * Modifications - 28-Jul-2000 - pjw@rhyme.com.au (1.45) * - * Added --create, --no-owner, --superuser, --no-reconnect (pg_dump & pg_restore) + * Added --create, --no-owner, --superuser, --no-reconnect (pg_dump & pg_restore) * Added code to dump 'Create Schema' statement (pg_dump) * Don't bother to disable/enable triggers if we don't have a superuser (pg_restore) * Cleaned up code for reconnecting to database. @@ -69,54 +69,56 @@ #include <termios.h> #endif -#ifdef HAVE_GETOPT_H +#ifdef HAVE_GETOPT_H #include <getopt.h> #endif /* Forward decls */ static void usage(const char *progname); -static char* _cleanupName(char* name); +static char *_cleanupName(char *name); typedef struct option optType; #ifdef HAVE_GETOPT_LONG -struct option cmdopts[] = { - { "clean", 0, NULL, 'c' }, - { "create", 0, NULL, 'C' }, - { "data-only", 0, NULL, 'a' }, - { "dbname", 1, NULL, 'd' }, - { "file", 1, NULL, 'f' }, - { "format", 1, NULL, 'F' }, - { "function", 2, NULL, 'P' }, - { "host", 1, NULL, 'h' }, - { "ignore-version", 0, NULL, 'i'}, - { "index", 2, NULL, 'I'}, - { "list", 0, NULL, 'l'}, - { "no-acl", 0, NULL, 'x' }, - { "no-owner", 0, NULL, 'O'}, - { "no-reconnect", 0, NULL, 'R' }, - { "port", 1, NULL, 'p' }, - { "oid-order", 0, NULL, 'o'}, - { "orig-order", 0, NULL, 'N'}, - { "password", 0, NULL, 'u' }, - { "rearrange", 0, NULL, 'r'}, - { "schema-only", 0, NULL, 's' }, - { "superuser", 1, NULL, 'S' }, - { "table", 2, NULL, 't'}, - { "trigger", 2, NULL, 'T' }, - { "use-list", 1, NULL, 'L'}, - { "verbose", 0, NULL, 'v' }, - { NULL, 0, NULL, 0} - }; +struct option cmdopts[] = { + {"clean", 0, NULL, 'c'}, + {"create", 0, NULL, 'C'}, + {"data-only", 0, NULL, 'a'}, + {"dbname", 1, NULL, 'd'}, + {"file", 1, NULL, 'f'}, + {"format", 1, NULL, 'F'}, + {"function", 2, NULL, 'P'}, + {"host", 1, NULL, 'h'}, + {"ignore-version", 0, NULL, 'i'}, + {"index", 2, NULL, 'I'}, + {"list", 0, NULL, 'l'}, + {"no-acl", 0, NULL, 'x'}, + {"no-owner", 0, NULL, 'O'}, + {"no-reconnect", 0, NULL, 'R'}, + {"port", 1, NULL, 'p'}, + {"oid-order", 0, NULL, 'o'}, + {"orig-order", 0, NULL, 'N'}, + {"password", 0, NULL, 'u'}, + {"rearrange", 0, NULL, 'r'}, + {"schema-only", 0, NULL, 's'}, + {"superuser", 1, NULL, 'S'}, + {"table", 2, NULL, 't'}, + {"trigger", 2, NULL, 'T'}, + {"use-list", 1, NULL, 'L'}, + {"verbose", 0, NULL, 'v'}, + {NULL, 0, NULL, 0} +}; + #endif -int main(int argc, char **argv) +int +main(int argc, char **argv) { - RestoreOptions *opts; - char *progname; - int c; - Archive* AH; - char *fileSpec = NULL; + RestoreOptions *opts; + char *progname; + int c; + Archive *AH; + char *fileSpec = NULL; extern int optind; extern char *optarg; @@ -126,12 +128,12 @@ int main(int argc, char **argv) if (argc > 1) { - if (strcmp(argv[1], "--help")==0 || strcmp(argv[1], "-?")==0) + if (strcmp(argv[1], "--help") == 0 || strcmp(argv[1], "-?") == 0) { usage(progname); exit(0); } - if (strcmp(argv[1], "--version")==0 || strcmp(argv[1], "-V")==0) + if (strcmp(argv[1], "--version") == 0 || strcmp(argv[1], "-V") == 0) { puts("pg_restore (PostgreSQL) " PG_VERSION); exit(0); @@ -167,8 +169,8 @@ int main(int argc, char **argv) opts->filename = strdup(optarg); break; case 'F': - if (strlen(optarg) != 0) - opts->formatName = strdup(optarg); + if (strlen(optarg) != 0) + opts->formatName = strdup(optarg); break; case 'h': if (strlen(optarg) != 0) @@ -205,17 +207,17 @@ int main(int argc, char **argv) case 'R': opts->noReconnect = 1; break; - case 'P': /* Function */ + case 'P': /* Function */ opts->selTypes = 1; opts->selFunction = 1; opts->functionNames = optarg ? strdup(optarg) : NULL; break; - case 'I': /* Index */ + case 'I': /* Index */ opts->selTypes = 1; opts->selIndex = 1; opts->indexNames = _cleanupName(optarg); break; - case 'T': /* Trigger */ + case 'T': /* Trigger */ opts->selTypes = 1; opts->selTrigger = 1; opts->triggerNames = _cleanupName(optarg); @@ -249,15 +251,16 @@ int main(int argc, char **argv) } } - if (optind < argc) { - fileSpec = argv[optind]; - } else { - fileSpec = NULL; - } + if (optind < argc) + fileSpec = argv[optind]; + else + fileSpec = NULL; - if (opts->formatName) { + if (opts->formatName) + { - switch (opts->formatName[0]) { + switch (opts->formatName[0]) + { case 'c': case 'C': @@ -276,25 +279,26 @@ int main(int argc, char **argv) default: fprintf(stderr, "%s: Unknown archive format '%s', please specify 't' or 'c'\n", - progname, opts->formatName); - exit (1); + progname, opts->formatName); + exit(1); } - } + } - AH = OpenArchive(fileSpec, opts->format); + AH = OpenArchive(fileSpec, opts->format); /* Let the archiver know how noisy to be */ AH->verbose = opts->verbose; - if (opts->tocFile) + if (opts->tocFile) SortTocFromFile(AH, opts); - if (opts->oidOrder) + if (opts->oidOrder) SortTocByOID(AH); - else if (opts->origOrder) + else if (opts->origOrder) SortTocByID(AH); - if (opts->rearrange) { + if (opts->rearrange) + { MoveToStart(AH, "<Init>"); MoveToEnd(AH, "TABLE DATA"); MoveToEnd(AH, "BLOBS"); @@ -302,23 +306,23 @@ int main(int argc, char **argv) MoveToEnd(AH, "TRIGGER"); MoveToEnd(AH, "RULE"); MoveToEnd(AH, "SEQUENCE SET"); - } + } /* Database MUST be at start */ MoveToStart(AH, "DATABASE"); - if (opts->tocSummary) { + if (opts->tocSummary) PrintTOCSummary(AH, opts); - } else { + else RestoreArchive(AH, opts); - } - CloseArchive(AH); + CloseArchive(AH); - return 1; + return 1; } -static void usage(const char *progname) +static void +usage(const char *progname) { printf("%s restores a PostgreSQL database from an archive created by pg_dump.\n\n" "Usage:\n %s [options] [file]\n\n" @@ -326,92 +330,92 @@ static void usage(const char *progname) progname, progname); #ifdef HAVE_GETOPT_LONG puts( - " -a, --data-only restore only the data, no schema\n" - " -c, --clean clean (drop) schema prior to create\n" - " -C, --create output commands to create the database\n" - " -d, --dbname=NAME specify database name\n" - " -f, --file=FILENAME script output file name\n" - " -F, --format {c|f} specify backup file format\n" - " -h, --host HOSTNAME server host name\n" - " -i, --index[=NAME] restore indices or named index\n" - " -l, --list dump summarized TOC for this file\n" - " -L, --use-list=FILENAME use specified table of contents for ordering\n" - " output from this file\n" - " -N, --orig-order restore in original dump order\n" - " -o, --oid-order restore in oid order\n" - " -O, --no-owner do not reconnect to database to match\n" - " object owner\n" - " -p, --port PORT server port number\n" - " -P, --function[=NAME] restore functions or named function\n" - " -r, --rearrange rearrange output to put indexes etc. at end\n" - " -R, --no-reconnect disallow ALL reconnections to the database\n" - " -s, --schema-only restore only the schema, no data\n" - " -S, --superuser=NAME specify the superuser user name to use for\n" - " disabling triggers\n" - " -t, --table[=TABLE] restore this table only\n" - " -T, --trigger[=NAME] restore triggers or named trigger\n" - " -u, --password use password authentication\n" - " -v, --verbose verbose\n" - " -x, --no-acl skip dumping of ACLs (grant/revoke)\n"); - -#else /* not HAVE_GETOPT_LONG */ + " -a, --data-only restore only the data, no schema\n" + " -c, --clean clean (drop) schema prior to create\n" + " -C, --create output commands to create the database\n" + " -d, --dbname=NAME specify database name\n" + " -f, --file=FILENAME script output file name\n" + " -F, --format {c|f} specify backup file format\n" + " -h, --host HOSTNAME server host name\n" + " -i, --index[=NAME] restore indices or named index\n" + " -l, --list dump summarized TOC for this file\n" + " -L, --use-list=FILENAME use specified table of contents for ordering\n" + " output from this file\n" + " -N, --orig-order restore in original dump order\n" + " -o, --oid-order restore in oid order\n" + " -O, --no-owner do not reconnect to database to match\n" + " object owner\n" + " -p, --port PORT server port number\n" + " -P, --function[=NAME] restore functions or named function\n" + " -r, --rearrange rearrange output to put indexes etc. at end\n" + " -R, --no-reconnect disallow ALL reconnections to the database\n" + " -s, --schema-only restore only the schema, no data\n" + " -S, --superuser=NAME specify the superuser user name to use for\n" + " disabling triggers\n" + " -t, --table[=TABLE] restore this table only\n" + " -T, --trigger[=NAME] restore triggers or named trigger\n" + " -u, --password use password authentication\n" + " -v, --verbose verbose\n" + " -x, --no-acl skip dumping of ACLs (grant/revoke)\n"); + +#else /* not HAVE_GETOPT_LONG */ puts( - " -a restore only the data, no schema\n" - " -c clean (drop) schema prior to create\n" - " -C output commands to create the database\n" - " -d NAME specify database name\n" - " -f FILENAME script output file name\n" - " -F {c|f} specify backup file format\n" - " -h HOSTNAME server host name\n" - " -i NAME restore indices or named index\n" - " -l dump summarized TOC for this file\n" - " -L FILENAME use specified table of contents for ordering\n" - " output from this file\n" - " -N restore in original dump order\n" - " -o restore in oid order\n" - " -O do not output reconnect to database to match\n" - " object owner\n" - " -p PORT server port number\n" - " -P NAME restore functions or named function\n" - " -r rearrange output to put indexes etc at end\n" - " -R disallow ALL reconnections to the database\n" - " -s restore only the schema, no data\n" - " -S NAME specify the superuser user name to use for\n" - " disabling triggers\n" - " -t NAME restore this table only\n" - " -T NAME restore triggers or named trigger\n" - " -u use password authentication\n" - " -v verbose\n" - " -x skip dumping of ACLs (grant/revoke)\n"); + " -a restore only the data, no schema\n" + " -c clean (drop) schema prior to create\n" + " -C output commands to create the database\n" + " -d NAME specify database name\n" + " -f FILENAME script output file name\n" + " -F {c|f} specify backup file format\n" + " -h HOSTNAME server host name\n" + " -i NAME restore indices or named index\n" + " -l dump summarized TOC for this file\n" + " -L FILENAME use specified table of contents for ordering\n" + " output from this file\n" + " -N restore in original dump order\n" + " -o restore in oid order\n" + " -O do not output reconnect to database to match\n" + " object owner\n" + " -p PORT server port number\n" + " -P NAME restore functions or named function\n" + " -r rearrange output to put indexes etc at end\n" + " -R disallow ALL reconnections to the database\n" + " -s restore only the schema, no data\n" + " -S NAME specify the superuser user name to use for\n" + " disabling triggers\n" + " -t NAME restore this table only\n" + " -T NAME restore triggers or named trigger\n" + " -u use password authentication\n" + " -v verbose\n" + " -x skip dumping of ACLs (grant/revoke)\n"); #endif puts("If [file] is not supplied, then standard input is used.\n"); puts("Report bugs to <pgsql-bugs@postgresql.org>."); } -static char* _cleanupName(char* name) +static char * +_cleanupName(char *name) { - int i; + int i; - if (!name || ! name[0]) + if (!name || !name[0]) return NULL; - name = strdup(name); + name = strdup(name); - if (name[0] == '"') - { + if (name[0] == '"') + { strcpy(name, &name[1]); if (name[0] && *(name + strlen(name) - 1) == '"') *(name + strlen(name) - 1) = '\0'; - } - /* otherwise, convert table name to lowercase... */ - else - { + } + /* otherwise, convert table name to lowercase... */ + else + { for (i = 0; name[i]; i++) if (isupper((unsigned char) name[i])) name[i] = tolower((unsigned char) name[i]); - } - return name; + } + return name; } - |
