pg_dump.c 53.0 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
/*-------------------------------------------------------------------------
 *
 * pg_dump.c--
 *    pg_dump is an utility for dumping out a postgres database
 * into a script file.
 *
 *  pg_dump will read the system catalogs in a database and 
 *  dump out a script that reproduces
 *  the schema of the database in terms of
 *        user-defined types
 *        user-defined functions
 *        tables
 *        indices
 *        aggregates
 *        operators
 *
 * the output script is SQL that is understood by Postgres95
 *
 * Copyright (c) 1994, Regents of the University of California
 *
 *
 * IDENTIFICATION
23
 *    $Header: /cvsroot/pgsql/src/bin/pg_dump/pg_dump.c,v 1.24 1997/02/13 08:31:27 scrappy Exp $
24
 *
25
 * Modifications - 6/10/96 - dave@bensoft.com - version 1.13.dhb
26 27 28 29 30
 *
 *   Applied 'insert string' patch from "Marc G. Fournier" <scrappy@ki.net>
 *   Added '-t table' option
 *   Added '-a' option
 *   Added '-da' option
31
 *
32 33 34 35 36 37
 * Modifications - 6/12/96 - dave@bensoft.com - version 1.13.dhb.2
 *
 *   - Fixed dumpTable output to output lengths for char and varchar types!
 *   - Added single. quote to twin single quote expansion for 'insert' string
 *     mode.
 *
38 39 40 41
 * Modifications - 7/26/96 - asussman@vidya.com
 *
 *   - Fixed ouput lengths for char and varchar type where the length is variable (-1)
 *
42 43 44 45
 *-------------------------------------------------------------------------
 */

#include <stdlib.h>
46
#include <unistd.h>     /* for getopt() */
47 48
#include <stdio.h>
#include <string.h>
49
#include <sys/param.h>  /* for MAXHOSTNAMELEN on most */
50
#ifdef sparc_solaris
51
#include <netdb.h>      /* for MAXHOSTNAMELEN on some */
52 53 54
#endif

#include "postgres.h"
55
#include "access/htup.h"
56
#include "libpq-fe.h"
57
#ifndef HAVE_STRDUP
58 59
#include "strdup.h"
#endif
60 61 62 63 64 65 66

#include "pg_dump.h"

extern char *optarg;
extern int optind, opterr;

/* global decls */
67
bool g_verbose;  /* User wants verbose narration of our activities. */
68 69 70
int g_last_builtin_oid; /* value of the last builtin oid */
FILE *g_fout;     /* the script file */
PGconn *g_conn;   /* the database connection */
71 72
int dumpData; /* dump data using proper insert strings */
int attrNames; /* put attr names into insert strings */
73 74 75 76 77 78 79 80 81

char g_opaque_type[10]; /* name for the opaque type */

/* placeholders for the delimiters for comments */
char g_comment_start[10]; 
char g_comment_end[10]; 


static void
82
usage(const char* progname)
83
{
84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110
    fprintf(stderr, 
            "%s - version 1.13.dhb.2\n\n",progname);
    fprintf(stderr, 
            "usage:  %s [options] [dbname]\n",progname);
    fprintf(stderr, 
            "\t -f filename \t\t script output filename\n");
    fprintf(stderr, 
            "\t -H hostname \t\t server host name\n");
    fprintf(stderr, 
            "\t -p port     \t\t server port number\n");
    fprintf(stderr, 
            "\t -v          \t\t verbose\n");
    fprintf(stderr, 
            "\t -d          \t\t dump data as proper insert strings\n");
    fprintf(stderr, 
            "\t -D          \t\t dump data as inserts with attribute names\n");
    fprintf(stderr, 
            "\t -S          \t\t dump out only the schema, no data\n");
    fprintf(stderr, 
            "\t -a          \t\t dump out only the data, no schema\n");
    fprintf(stderr, 
            "\t -t table    \t\t dump for this table only\n");
    fprintf(stderr, 
            "\t -o          \t\t dump object id's (oids)\n");
    fprintf(stderr, 
            "\nIf dbname is not supplied, then the DATABASE environment "
            "variable value is used.\n");
111 112 113 114 115
    fprintf(stderr, "\n");

    exit(1);
}

116
static void 
117 118 119 120 121 122 123
exit_nicely(PGconn* conn)
{
  PQfinish(conn);
  exit(1);
}


M
Marc G. Fournier 已提交
124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161
/*
 * isViewRule
 *		Determine if the relation is a VIEW 
 *
 */
bool
isViewRule(char *relname)
{
    PGresult *res;
    int ntups;
    char query[MAXQUERYLEN];
    
    res = PQexec(g_conn, "begin");
    if (!res || 
        PQresultStatus(res) != PGRES_COMMAND_OK) {
        fprintf(stderr,"BEGIN command failed\n");
        exit_nicely(g_conn);
    }
    PQclear(res);

    sprintf(query, "select relname from pg_class, pg_rewrite "
		   "where pg_class.oid = ev_class "
		   "and rulename = '_RET%s'", relname);

    res = PQexec(g_conn, query);
    if (!res || 
        PQresultStatus(res) != PGRES_TUPLES_OK) {
        fprintf(stderr,"isViewRule(): SELECT failed\n");
        exit_nicely(g_conn);
    }
    
    ntups = PQntuples(res);

    PQclear(res);
    res = PQexec(g_conn, "end");
    PQclear(res);
    return ntups > 0 ? TRUE : FALSE;
}
162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201

#define COPYBUFSIZ      8192


static void 
dumpClasses_nodumpData(FILE *fout, const char *classname, const bool oids) {

    PGresult *res;
    char query[255];
    int ret;
    bool copydone;
    char copybuf[COPYBUFSIZ];

    if (oids) {
        fprintf(fout, "COPY %s WITH OIDS FROM stdin;\n", 
                classname);
        sprintf(query, "COPY %s WITH OIDS TO stdout;\n", 
                classname);
    } else {
        fprintf(fout, "COPY %s FROM stdin;\n", classname);
        sprintf(query, "COPY %s TO stdout;\n", classname);
    }
    res = PQexec(g_conn, query);
    if (!res) {
        fprintf(stderr, "SQL query to dump the contents of Table %s "
                "did not execute.  Explanation from backend: '%s'.\n"
                "The query was: '%s'.\n",
                classname, PQerrorMessage(g_conn), query);
        exit_nicely(g_conn);
    } else {
        if (PQresultStatus(res) != PGRES_COPY_OUT) {
            fprintf(stderr,"SQL query to dump the contents of Table %s "
                    "executed abnormally.\n"
                    "PQexec() returned status %d when %d was expected.\n"
                    "The query was: '%s'.\n",
                    classname, PQresultStatus(res), PGRES_COPY_OUT, query);
            exit_nicely(g_conn);
        } else {
            copydone = false;
            while (!copydone) {
202 203
                ret = PQgetline(res->conn, copybuf, COPYBUFSIZ); 
               
204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224
                if (copybuf[0] == '\\' &&
                    copybuf[1] == '.' &&
                    copybuf[2] == '\0') {
                    copydone = true;        /* don't print this... */
                } else {
                    fputs(copybuf, fout);
                    switch (ret) {
                      case EOF:
                        copydone = true;
                        /*FALLTHROUGH*/
                      case 0:
                        fputc('\n', fout);
                        break;
                      case 1:
                        break;
                    }
                }
            }
            fprintf(fout, "\\.\n");
        }
        PQclear(res);
225 226 227 228 229 230 231 232 233 234
        ret = PQendcopy(res->conn);
        if (ret != 0) {
            fprintf(stderr, "SQL query to dump the contents of Table %s "
                    "did not execute correctly.  After we read all the "
                    "table contents from the backend, PQendcopy() failed.  "
                    "Explanation from backend: '%s'.\n"
                    "The query was: '%s'.\n",
                    classname, PQerrorMessage(g_conn), query);
            exit_nicely(g_conn);
        }
235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290
    }
}



static void
dumpClasses_dumpData(FILE *fout, const char *classname, 
                     const TableInfo tblinfo, bool oids) {        

    PGresult *res;
    char query[255];
    int actual_atts; /* number of attrs in this a table */
    char expandbuf[COPYBUFSIZ];
    char q[MAXQUERYLEN];
    int tuple;
    int field;

    sprintf(query, "select * from %s;\n", classname);
    res = PQexec(g_conn, query);
    if (!res ||
        PQresultStatus(res) != PGRES_TUPLES_OK) {
        fprintf(stderr,"dumpClasses(): command failed\n");
        exit_nicely(g_conn);
    }
    tuple=0;
    while(tuple < PQntuples(res)) {
        fprintf(fout, "insert into %s ", classname);
        if (attrNames) {
            int j;
            actual_atts = 0;
            sprintf(q, "(");
            for (j=0;j<tblinfo.numatts;j++) {
                if (tblinfo.inhAttrs[j] == 0) {
                    sprintf(q, "%s%s%s",
                            q,
                            (actual_atts > 0) ? "," : "",
                            tblinfo.attnames[j]);
                    actual_atts++;
                }
            }
            sprintf(q,"%s%s",q, ") ");
            fprintf(fout, q);
        }
        fprintf(fout, "values (");
        field=0;
        do {
            if (PQgetisnull(res,tuple,field)) {
                fprintf(fout,"NULL");
            } else {
                switch(PQftype(res,field)) {
                  case 21: case 22: case 23: /* int types */
                  case 810: case 910: /* oldint types */
                  case 700: case 701: /* float types */
                    fprintf(fout, "%s", 
                            PQgetvalue(res,tuple,field));
                    break;
291 292 293 294 295
                  case 1005: case 1006: case 1007: /* _int types */
                  case 1021: case 1022: /* _float types */
                    fprintf(fout, "'%s'", 
                            PQgetvalue(res,tuple,field));
                    break;
296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339
                  default: {
                      char *expsrc,*expdest;
  
                    /* Before outputting string value, expand all
                       single quotes to twin single quotes -
                       dhb - 6/11/96 */
                    expsrc=PQgetvalue(res,tuple,field);
                      expdest=expandbuf;
                      while (*expsrc) {
                          *expdest++=*expsrc;
                          if (*expsrc == (char)0x27)  /*single quote*/
                            *expdest++ = *expsrc;
                          expsrc++;
                      }
                      *expdest=*expsrc; /* null term. */
                      
                      fprintf(fout, "'%s'", expandbuf);
                  }
                    break;
                }
            }
            field++;
            if(field != PQnfields(res))
              fprintf(fout, ",");
        } while(field < PQnfields(res));
        fprintf(fout, ");\n");
        tuple++;
    }
    PQclear(res);
}



/*
 * DumpClasses -
 *    dump the contents of all the classes.
 */
static void
dumpClasses(const TableInfo tblinfo[], const int numTables, FILE *fout, 
            const char *onlytable, const bool oids) {

    int i;
    char *all_only;

340
    if (onlytable == NULL) all_only = "all";
341 342 343 344 345 346 347 348
    else all_only = "one";
    
    if (g_verbose)
      fprintf(stderr, "%s dumping out the contents of %s of %d tables %s\n",
              g_comment_start, all_only, numTables, g_comment_end);
    
    for(i = 0; i < numTables; i++) {
        const char *classname = tblinfo[i].relname;
349

M
Marc G. Fournier 已提交
350 351 352 353
	/* Skip VIEW relations */
	if (isViewRule(tblinfo[i].relname))
		continue;

354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372
        if (!onlytable || (!strcmp(classname,onlytable))) {
            if (g_verbose)
              fprintf(stderr, "%s dumping out the contents of Table %s %s\n",
                      g_comment_start, classname, g_comment_end);

            /* skip archive names*/
            if (isArchiveName(classname))
              continue;

            if(!dumpData) 
              dumpClasses_nodumpData(fout, classname, oids);
            else 
              dumpClasses_dumpData(fout, classname, tblinfo[i], oids);
        }
    }        
}



373
int
374 375 376
main(int argc, char** argv)
{
    int c;
377 378 379
    const char* progname;
    const char* filename;
    const char* dbname;
380
    int schemaOnly;
381
    int dataOnly;
382 383 384
    const char *pghost = NULL;
    const char *pgport = NULL;
    const char *tablename;
385
    int oids;
386 387 388 389 390
    TableInfo *tblinfo;
    int numTables;

    dbname = NULL;
    filename = NULL;
391
    tablename = NULL;
392
    g_verbose = false;
393 394
    oids = 0;
    
395 396 397 398
    strcpy(g_comment_start,"-- ");
    g_comment_end[0] = '\0';
    strcpy(g_opaque_type, "opaque");

399
    dataOnly = schemaOnly = dumpData = attrNames = 0;
400 401 402

    progname = *argv;

B
Bruce Momjian 已提交
403
    while ((c = getopt(argc, argv,"f:H:p:t:vSDdDao")) != EOF) {
404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419
        switch(c) {
        case 'f': /* output file name */
            filename = optarg;
            break;
        case 'H' : /* server host */
            pghost = optarg;
            break;
        case 'p' : /* server port */
            pgport = optarg;
            break;
        case 'v': /* verbose */
            g_verbose = true;
            break;
        case 'S': /* dump schema only */
            schemaOnly = 1;
            break;
420 421
        case 'd': /* dump data as proper insert strings */
            dumpData = 1;
B
Bruce Momjian 已提交
422 423 424 425
            break;
        case 'D': /* dump data as proper insert strings with attr names */
            dumpData = 1;
            attrNames = 1;
426
            break;
427 428 429 430 431 432 433 434 435 436 437 438 439
        case 't': /* Dump data for this table only */
            tablename = optarg;
            break;
        case 'a': /* Dump data only */
            dataOnly = 1;
            break;
        case 'o': /* Dump oids */
            oids = 1;
            break;
        default:
            usage(progname);
            break;
        }
440 441 442 443
    }

    /* open the output file */
    if (filename == NULL) {
444
        g_fout = stdout;
445
    } else {
446 447 448 449 450 451 452
        g_fout = fopen(filename, "w");
        if (g_fout == NULL) {
            fprintf(stderr,
                    "%s: could not open output file named %s for writing\n",
                    progname, filename);
            exit(2);
        }
453 454 455 456
    }

    /* find database */
    if (!(dbname = argv[optind]) &&
457 458 459 460
        !(dbname = getenv("DATABASE")) ) {
            fprintf(stderr, "%s: no database name specified\n",progname);
            exit (2);
        }
461 462 463 464

    g_conn = PQsetdb(pghost, pgport, NULL, NULL, dbname);
    /* check to see that the backend connection was successfully made */
    if (PQstatus(g_conn) == CONNECTION_BAD) {
465 466 467
        fprintf(stderr,"Connection to database '%s' failed.\n", dbname);
        fprintf(stderr,"%s\n",PQerrorMessage(g_conn));
        exit_nicely(g_conn);
468 469 470 471
    }

    g_last_builtin_oid = findLastBuiltinOid();

472 473
    if (oids)
        setMaxOid(g_fout);
474
    if (!dataOnly) {
475 476 477 478
        if (g_verbose) 
            fprintf(stderr, "%s last builtin oid is %d %s\n",
                    g_comment_start,  g_last_builtin_oid, g_comment_end);
        tblinfo = dumpSchema(g_fout, &numTables, tablename);
479
    }
480
    else
481
      tblinfo = dumpSchema(NULL, &numTables, tablename);
482 483
    
    if (!schemaOnly) {
484
      dumpClasses(tblinfo, numTables, g_fout, tablename, oids);
485 486
    }     

487
    if (!dataOnly) /* dump indexes at the end for performance */
488
        dumpSchemaIdx(g_fout, &numTables, tablename, tblinfo, numTables);
489
    
490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531
    fflush(g_fout);
    fclose(g_fout);

    PQfinish(g_conn);
    exit(0);
}


/*
 * getTypes: 
 *    read all base types in the system catalogs and return them in the 
 * TypeInfo* structure
 *
 *  numTypes is set to the number of types read in 
 *
 */
TypeInfo*
getTypes(int *numTypes)
{
    PGresult *res;
    int ntups;
    int i;
    char query[MAXQUERYLEN];
    TypeInfo *tinfo;

    int i_oid;
    int i_typowner;
    int i_typname;
    int i_typlen;
    int i_typprtlen;
    int i_typinput;
    int i_typoutput;
    int i_typreceive;
    int i_typsend;
    int i_typelem;
    int i_typdelim;
    int i_typdefault;
    int i_typrelid;
    int i_typbyval;

    res = PQexec(g_conn, "begin");
    if (!res || 
532 533 534
        PQresultStatus(res) != PGRES_COMMAND_OK) {
        fprintf(stderr,"BEGIN command failed\n");
        exit_nicely(g_conn);
535 536 537 538 539 540 541 542 543
    }
    PQclear(res);
    
   /* find all base types */
   /* we include even the built-in types 
      because those may be used as array elements by user-defined types */
   /* we filter out the built-in types when 
      we dump out the types */

544 545 546
    sprintf(query, "SELECT oid, typowner,typname, typlen, typprtlen, "
            "typinput, typoutput, typreceive, typsend, typelem, typdelim, "
            "typdefault, typrelid,typbyval from pg_type");
547 548 549
    
    res = PQexec(g_conn,query);
    if (!res || 
550 551 552
        PQresultStatus(res) != PGRES_TUPLES_OK) {
        fprintf(stderr,"getTypes(): SELECT failed\n");
        exit_nicely(g_conn);
553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574
    }
    
    ntups = PQntuples(res);
    
    tinfo = (TypeInfo*)malloc(ntups * sizeof(TypeInfo));

    i_oid = PQfnumber(res,"oid");
    i_typowner = PQfnumber(res,"typowner");
    i_typname = PQfnumber(res,"typname");
    i_typlen = PQfnumber(res,"typlen");
    i_typprtlen = PQfnumber(res,"typprtlen");
    i_typinput = PQfnumber(res,"typinput");
    i_typoutput = PQfnumber(res,"typoutput");
    i_typreceive = PQfnumber(res,"typreceive");
    i_typsend = PQfnumber(res,"typsend");
    i_typelem = PQfnumber(res,"typelem");
    i_typdelim = PQfnumber(res,"typdelim");
    i_typdefault = PQfnumber(res,"typdefault");
    i_typrelid = PQfnumber(res,"typrelid");
    i_typbyval = PQfnumber(res,"typbyval");

    for (i=0;i<ntups;i++) {
575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600
        tinfo[i].oid = strdup(PQgetvalue(res,i,i_oid));
        tinfo[i].typowner = strdup(PQgetvalue(res,i,i_typowner));
        tinfo[i].typname = strdup(PQgetvalue(res,i,i_typname));
        tinfo[i].typlen = strdup(PQgetvalue(res,i,i_typlen));
        tinfo[i].typprtlen = strdup(PQgetvalue(res,i,i_typprtlen));
        tinfo[i].typinput = strdup(PQgetvalue(res,i,i_typinput));
        tinfo[i].typoutput = strdup(PQgetvalue(res,i,i_typoutput));
        tinfo[i].typreceive = strdup(PQgetvalue(res,i,i_typreceive));
        tinfo[i].typsend = strdup(PQgetvalue(res,i,i_typsend));
        tinfo[i].typelem = strdup(PQgetvalue(res,i,i_typelem));
        tinfo[i].typdelim = strdup(PQgetvalue(res,i,i_typdelim));
        tinfo[i].typdefault = strdup(PQgetvalue(res,i,i_typdefault));
        tinfo[i].typrelid = strdup(PQgetvalue(res,i,i_typrelid));

        if (strcmp(PQgetvalue(res,i,i_typbyval), "f") == 0)
            tinfo[i].passedbyvalue = 0;
        else
            tinfo[i].passedbyvalue = 1;

        /* check for user-defined array types,
           omit system generated ones */
        if ( (strcmp(tinfo[i].typelem, "0") != 0)  &&
             tinfo[i].typname[0] != '_')
            tinfo[i].isArray = 1;
        else
            tinfo[i].isArray = 0;
601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649
    }

    *numTypes = ntups;

    PQclear(res);

    res = PQexec(g_conn,"end");
    PQclear(res);

    return tinfo;
}

/*
 * getOperators:
 *    read all operators in the system catalogs and return them in the 
 * OprInfo* structure
 *
 *  numOprs is set to the number of operators read in 
 *    
 *
 */
OprInfo*
getOperators(int *numOprs)
{
    PGresult *res;
    int ntups;
    int i;
    char query[MAXQUERYLEN];

    OprInfo* oprinfo;

    int i_oid;
    int i_oprname;
    int i_oprkind;
    int i_oprcode;
    int i_oprleft;
    int i_oprright;
    int i_oprcom;
    int i_oprnegate;
    int i_oprrest;
    int i_oprjoin;
    int i_oprcanhash;
    int i_oprlsortop;
    int i_oprrsortop;
    
    /* find all operators, including builtin operators,
       filter out system-defined operators at dump-out time */
    res = PQexec(g_conn, "begin");
    if (!res || 
650 651 652
        PQresultStatus(res) != PGRES_COMMAND_OK) {
        fprintf(stderr,"BEGIN command failed\n");
        exit_nicely(g_conn);
653 654 655
    }
    PQclear(res);

656 657 658
    sprintf(query, "SELECT oid, oprname, oprkind, oprcode, oprleft, "
            "oprright, oprcom, oprnegate, oprrest, oprjoin, oprcanhash, "
            "oprlsortop, oprrsortop from pg_operator");
659 660 661

    res = PQexec(g_conn, query);
    if (!res || 
662 663 664
        PQresultStatus(res) != PGRES_TUPLES_OK) {
        fprintf(stderr,"getOperators(): SELECT failed\n");
        exit_nicely(g_conn);
665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686
    }
    
    ntups = PQntuples(res);
    *numOprs = ntups;

    oprinfo = (OprInfo*)malloc(ntups * sizeof(OprInfo));

    i_oid = PQfnumber(res,"oid");
    i_oprname = PQfnumber(res,"oprname");
    i_oprkind = PQfnumber(res,"oprkind");
    i_oprcode = PQfnumber(res,"oprcode");
    i_oprleft = PQfnumber(res,"oprleft");
    i_oprright = PQfnumber(res,"oprright");
    i_oprcom = PQfnumber(res,"oprcom");
    i_oprnegate = PQfnumber(res,"oprnegate");
    i_oprrest = PQfnumber(res,"oprrest");
    i_oprjoin = PQfnumber(res,"oprjoin");
    i_oprcanhash = PQfnumber(res,"oprcanhash");
    i_oprlsortop = PQfnumber(res,"oprlsortop");
    i_oprrsortop = PQfnumber(res,"oprrsortop");

    for (i=0;i<ntups;i++) {
687 688 689 690 691 692 693 694 695 696 697 698 699
        oprinfo[i].oid = strdup(PQgetvalue(res,i,i_oid));
        oprinfo[i].oprname = strdup(PQgetvalue(res,i,i_oprname));
        oprinfo[i].oprkind = strdup(PQgetvalue(res,i,i_oprkind));
        oprinfo[i].oprcode = strdup(PQgetvalue(res,i,i_oprcode));
        oprinfo[i].oprleft = strdup(PQgetvalue(res,i,i_oprleft));
        oprinfo[i].oprright = strdup(PQgetvalue(res,i,i_oprright));
        oprinfo[i].oprcom = strdup(PQgetvalue(res,i,i_oprcom));
        oprinfo[i].oprnegate = strdup(PQgetvalue(res,i,i_oprnegate));
        oprinfo[i].oprrest = strdup(PQgetvalue(res,i,i_oprrest));
        oprinfo[i].oprjoin = strdup(PQgetvalue(res,i,i_oprjoin));
        oprinfo[i].oprcanhash = strdup(PQgetvalue(res,i,i_oprcanhash));
        oprinfo[i].oprlsortop = strdup(PQgetvalue(res,i,i_oprlsortop));
        oprinfo[i].oprrsortop = strdup(PQgetvalue(res,i,i_oprrsortop));
700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742
    }

    PQclear(res);
    res = PQexec(g_conn, "end");
    PQclear(res);

    return oprinfo;
}


/*
 * getAggregates:
 *    read all the user-defined aggregates in the system catalogs and
 * return them in the AggInfo* structure
 *
 * numAggs is set to the number of aggregates read in 
 *    
 *
 */
AggInfo*
getAggregates(int *numAggs)
{
    PGresult* res;
    int ntups;
    int i;
    char query[MAXQUERYLEN];
    AggInfo *agginfo;

    int i_oid;
    int i_aggname;
    int i_aggtransfn1;
    int i_aggtransfn2;
    int i_aggfinalfn;
    int i_aggtranstype1;
    int i_aggbasetype;
    int i_aggtranstype2;
    int i_agginitval1;
    int i_agginitval2;

    /* find all user-defined aggregates */

    res = PQexec(g_conn, "begin");
    if (!res || 
743 744 745
        PQresultStatus(res) != PGRES_COMMAND_OK) {
        fprintf(stderr,"BEGIN command failed\n");
        exit_nicely(g_conn);
746 747 748 749
    }
    PQclear(res);

    sprintf(query, 
750 751 752
            "SELECT oid, aggname, aggtransfn1, aggtransfn2, aggfinalfn, "
            "aggtranstype1, aggbasetype, aggtranstype2, agginitval1, "
            "agginitval2 from pg_aggregate;");
753 754 755

    res = PQexec(g_conn, query);
    if (!res || 
756 757 758
        PQresultStatus(res) != PGRES_TUPLES_OK) {
        fprintf(stderr,"getAggregates(): SELECT failed\n");
        exit_nicely(g_conn);
759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777
    }

    ntups = PQntuples(res);
    *numAggs = ntups;

    agginfo = (AggInfo*)malloc(ntups * sizeof(AggInfo));
    
    i_oid = PQfnumber(res,"oid");
    i_aggname = PQfnumber(res,"aggname");
    i_aggtransfn1 = PQfnumber(res,"aggtransfn1");
    i_aggtransfn2 = PQfnumber(res,"aggtransfn2");
    i_aggfinalfn = PQfnumber(res,"aggfinalfn");
    i_aggtranstype1 = PQfnumber(res,"aggtranstype1");
    i_aggbasetype = PQfnumber(res,"aggbasetype");
    i_aggtranstype2 = PQfnumber(res,"aggtranstype2");
    i_agginitval1 = PQfnumber(res,"agginitval1");
    i_agginitval2 = PQfnumber(res,"agginitval2");

    for (i=0;i<ntups;i++) {
778 779 780 781 782 783 784 785 786 787
        agginfo[i].oid = strdup(PQgetvalue(res,i,i_oid));
        agginfo[i].aggname = strdup(PQgetvalue(res,i,i_aggname));
        agginfo[i].aggtransfn1 = strdup(PQgetvalue(res,i,i_aggtransfn1));
        agginfo[i].aggtransfn2 = strdup(PQgetvalue(res,i,i_aggtransfn2));
        agginfo[i].aggfinalfn = strdup(PQgetvalue(res,i,i_aggfinalfn));
        agginfo[i].aggtranstype1 = strdup(PQgetvalue(res,i,i_aggtranstype1));
        agginfo[i].aggbasetype = strdup(PQgetvalue(res,i,i_aggbasetype));
        agginfo[i].aggtranstype2 = strdup(PQgetvalue(res,i,i_aggtranstype2));
        agginfo[i].agginitval1 = strdup(PQgetvalue(res,i,i_agginitval1));
        agginfo[i].agginitval2 = strdup(PQgetvalue(res,i,i_agginitval2));
788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829
    }

    PQclear(res);

    res = PQexec(g_conn, "end");
    PQclear(res);
    return agginfo;
}

/*
 * getFuncs:
 *    read all the user-defined functions in the system catalogs and
 * return them in the FuncInfo* structure
 *
 * numFuncs is set to the number of functions read in 
 *    
 *
 */
FuncInfo*
getFuncs(int *numFuncs)
{
    PGresult *res;
    int ntups;
    int i;
    char query[MAXQUERYLEN];
    FuncInfo *finfo;

    int i_oid;
    int i_proname;
    int i_proowner;
    int i_prolang;
    int i_pronargs;
    int i_proargtypes;
    int i_prorettype;
    int i_proretset;
    int i_prosrc;
    int i_probin;

   /* find all user-defined funcs */

    res = PQexec(g_conn, "begin");
    if (!res || 
830 831 832
        PQresultStatus(res) != PGRES_COMMAND_OK) {
        fprintf(stderr,"BEGIN command failed\n");
        exit_nicely(g_conn);
833 834 835 836
    }
    PQclear(res);

    sprintf(query, 
837 838 839 840
            "SELECT oid, proname, proowner, prolang, pronargs, prorettype, "
            "proretset, proargtypes, prosrc, probin from pg_proc "
            "where oid > '%d'::oid", 
            g_last_builtin_oid);
841 842 843

    res = PQexec(g_conn, query);
    if (!res || 
844 845 846
        PQresultStatus(res) != PGRES_TUPLES_OK) {
        fprintf(stderr,"getFuncs(): SELECT failed\n");
        exit_nicely(g_conn);
847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866
    }
    
    ntups = PQntuples(res);
    
    *numFuncs = ntups;

    finfo = (FuncInfo*)malloc(ntups * sizeof(FuncInfo));

    i_oid = PQfnumber(res,"oid");
    i_proname = PQfnumber(res,"proname");
    i_proowner = PQfnumber(res,"proowner");
    i_prolang = PQfnumber(res,"prolang");
    i_pronargs = PQfnumber(res,"pronargs");
    i_proargtypes = PQfnumber(res,"proargtypes");
    i_prorettype = PQfnumber(res,"prorettype");
    i_proretset = PQfnumber(res,"proretset");
    i_prosrc = PQfnumber(res,"prosrc");
    i_probin = PQfnumber(res,"probin");
    
    for (i=0;i<ntups;i++) {
867 868 869
        finfo[i].oid = strdup(PQgetvalue(res,i,i_oid));
        finfo[i].proname = strdup(PQgetvalue(res,i,i_proname));
        finfo[i].proowner = strdup(PQgetvalue(res,i,i_proowner));
870

871 872
        finfo[i].prosrc = checkForQuote(PQgetvalue(res,i,i_prosrc));
        finfo[i].probin = strdup(PQgetvalue(res,i,i_probin));
873

874 875 876 877
        finfo[i].prorettype = strdup(PQgetvalue(res,i,i_prorettype));
        finfo[i].retset = (strcmp(PQgetvalue(res,i,i_proretset),"t") == 0);
        finfo[i].nargs = atoi(PQgetvalue(res,i,i_pronargs));
        finfo[i].lang = (atoi(PQgetvalue(res,i,i_prolang)) == C_PROLANG_OID);
878

879
        parseArgTypes(finfo[i].argtypes, PQgetvalue(res,i,i_proargtypes));
880

881
        finfo[i].dumped = 0;
882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921
    }

    PQclear(res);
    res = PQexec(g_conn, "end");
    PQclear(res);

    return finfo;

}

/*
 * getTables
 *    read all the user-defined tables (no indices, no catalogs)
 * in the system catalogs return them in the TableInfo* structure
 *
 * numTables is set to the number of tables read in 
 *    
 *
 */
TableInfo*
getTables(int *numTables)
{
    PGresult *res;
    int ntups;
    int i;
    char query[MAXQUERYLEN];
    TableInfo *tblinfo;
    
    int i_oid;
    int i_relname;
    int i_relarch;

    /* find all the user-defined tables (no indices and no catalogs),
     ordering by oid is important so that we always process the parent
     tables before the child tables when traversing the tblinfo* 

      we ignore tables that start with Xinv */

    res = PQexec(g_conn, "begin");
    if (!res || 
922 923 924
        PQresultStatus(res) != PGRES_COMMAND_OK) {
        fprintf(stderr,"BEGIN command failed\n");
        exit_nicely(g_conn);
925 926 927 928
    }
    PQclear(res);

    sprintf(query, 
929 930 931
            "SELECT oid, relname, relarch from pg_class "
            "where relkind = 'r' and relname !~ '^pg_' "
            "and relname !~ '^Xinv' order by oid;");
932 933 934

    res = PQexec(g_conn, query);
    if (!res || 
935 936 937
        PQresultStatus(res) != PGRES_TUPLES_OK) {
        fprintf(stderr,"getTables(): SELECT failed\n");
        exit_nicely(g_conn);
938 939 940 941 942 943 944 945 946 947 948 949 950
    }

    ntups = PQntuples(res);

    *numTables = ntups;

    tblinfo = (TableInfo*)malloc(ntups * sizeof(TableInfo));

    i_oid = PQfnumber(res,"oid");
    i_relname = PQfnumber(res,"relname");
    i_relarch = PQfnumber(res,"relarch");

    for (i=0;i<ntups;i++) {
951 952 953
        tblinfo[i].oid = strdup(PQgetvalue(res,i,i_oid));
        tblinfo[i].relname = strdup(PQgetvalue(res,i,i_relname));
        tblinfo[i].relarch = strdup(PQgetvalue(res,i,i_relarch));
954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987
    }

    PQclear(res);
    res = PQexec(g_conn, "end");
    PQclear(res);

    return tblinfo;

}

/*
 * getInherits
 *    read all the inheritance information
 * from the system catalogs return them in the InhInfo* structure
 *
 * numInherits is set to the number of tables read in 
 *    
 *
 */
InhInfo*
getInherits(int *numInherits)
{
    PGresult *res;
    int ntups;
    int i;
    char query[MAXQUERYLEN];
    InhInfo *inhinfo;
    
    int i_inhrel;
    int i_inhparent;

    /* find all the inheritance information */
    res = PQexec(g_conn, "begin");
    if (!res || 
988 989 990
        PQresultStatus(res) != PGRES_COMMAND_OK) {
        fprintf(stderr,"BEGIN command failed\n");
        exit_nicely(g_conn);
991 992 993 994 995 996 997
    }
    PQclear(res);

    sprintf(query, "SELECT inhrel, inhparent from pg_inherits");

    res = PQexec(g_conn, query);
    if (!res || 
998 999 1000
        PQresultStatus(res) != PGRES_TUPLES_OK) {
        fprintf(stderr,"getInherits(): SELECT failed\n");
        exit_nicely(g_conn);
1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012
    }
    
    ntups = PQntuples(res);

    *numInherits = ntups;

    inhinfo = (InhInfo*)malloc(ntups * sizeof(InhInfo));

    i_inhrel = PQfnumber(res,"inhrel");
    i_inhparent = PQfnumber(res,"inhparent");

    for (i=0;i<ntups;i++) {
1013 1014
        inhinfo[i].inhrel = strdup(PQgetvalue(res,i,i_inhrel));
        inhinfo[i].inhparent = strdup(PQgetvalue(res,i,i_inhparent));
1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039
    }

    PQclear(res);
    res = PQexec(g_conn, "end");
    PQclear(res);
    return inhinfo;
}

/*
 * getTableAttrs -
 *    for each table in tblinfo, read its attributes types and names
 * 
 * this is implemented in a very inefficient way right now, looping
 * through the tblinfo and doing a join per table to find the attrs and their 
 * types
 *
 *  modifies tblinfo
 */
void
getTableAttrs(TableInfo* tblinfo, int numTables)
{
    int i,j;
    char q[MAXQUERYLEN];
    int i_attname;
    int i_typname;
1040
    int i_attlen;
1041 1042 1043 1044 1045
    PGresult *res;
    int ntups;

    for (i=0;i<numTables;i++)  {

1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093
        /* skip archive tables */
        if (isArchiveName(tblinfo[i].relname))
            continue;

        /* find all the user attributes and their types*/
        /* we must read the attribute names in attribute number order! */
        /* because we will use the attnum to index into the attnames array 
           later */
        if (g_verbose) 
            fprintf(stderr,"%s finding the attrs and types for table: %s %s\n",
                g_comment_start,
                tblinfo[i].relname,
                g_comment_end);

        sprintf(q,"SELECT a.attnum, a.attname, t.typname, a.attlen "
                "from pg_attribute a, pg_type t "
                "where a.attrelid = '%s'::oid and a.atttypid = t.oid "
                "and a.attnum > 0 order by attnum",
                tblinfo[i].oid);
        res = PQexec(g_conn, q);
        if (!res || 
            PQresultStatus(res) != PGRES_TUPLES_OK) {
            fprintf(stderr,"getTableAttrs(): SELECT failed\n");
            exit_nicely(g_conn);
        }
        
        ntups = PQntuples(res);

        i_attname = PQfnumber(res,"attname");
        i_typname = PQfnumber(res,"typname");
        i_attlen  = PQfnumber(res,"attlen");

        tblinfo[i].numatts = ntups;
        tblinfo[i].attnames = (char**) malloc( ntups * sizeof(char*));
        tblinfo[i].typnames = (char**) malloc( ntups * sizeof(char*));
        tblinfo[i].attlen   = (int*) malloc(ntups * sizeof(int));
        tblinfo[i].inhAttrs = (int*) malloc (ntups * sizeof(int));
        tblinfo[i].parentRels = NULL;
        tblinfo[i].numParents = 0;
        for (j=0;j<ntups;j++) {
            tblinfo[i].attnames[j] = strdup(PQgetvalue(res,j,i_attname));
            tblinfo[i].typnames[j] = strdup(PQgetvalue(res,j,i_typname));
            tblinfo[i].attlen[j] = atoi(PQgetvalue(res,j,i_attlen));
            if (tblinfo[i].attlen[j] > 0) 
              tblinfo[i].attlen[j] = tblinfo[i].attlen[j] - 4;
            tblinfo[i].inhAttrs[j] = 0; /* this flag is set in flagInhAttrs()*/
        }
        PQclear(res);
1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121
    } 
}


/*
 * getIndices
 *    read all the user-defined indices information
 * from the system catalogs return them in the InhInfo* structure
 *
 * numIndices is set to the number of indices read in 
 *    
 *
 */
IndInfo*
getIndices(int *numIndices)
{
    int i;
    char query[MAXQUERYLEN];
    PGresult *res;
    int ntups;
    IndInfo *indinfo;

    int i_indexrelname;
    int i_indrelname;
    int i_indamname;
    int i_indproc;
    int i_indkey;
    int i_indclassname;
M
Marc G. Fournier 已提交
1122
    int i_indisunique;
1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134
    
    /* find all the user-defined indices.
       We do not handle partial indices.
       We also assume that only single key indices 

       skip 'Xinx*' - indices on inversion objects

       this is a 5-way join !!
    */
       
    res = PQexec(g_conn, "begin");
    if (!res || 
1135 1136 1137
        PQresultStatus(res) != PGRES_COMMAND_OK) {
        fprintf(stderr,"BEGIN command failed\n");
        exit_nicely(g_conn);
1138 1139 1140 1141
    }
    PQclear(res);

    sprintf(query,
1142 1143
            "SELECT t1.relname as indexrelname, t2.relname as indrelname, "
            "i.indproc, i.indkey[0], o.opcname as indclassname, "
M
Marc G. Fournier 已提交
1144
            "a.amname as indamname, i.indisunique from pg_index i, pg_class t1, "
1145 1146 1147 1148 1149 1150
            "pg_class t2, pg_opclass o, pg_am a "
            "where t1.oid = i.indexrelid and t2.oid = i.indrelid "
            "and o.oid = i.indclass[0] and t1.relam = a.oid and "
            "i.indexrelid > '%d'::oid and t2.relname !~ '^pg_' "
            "and t1.relname !~ '^Xinx' ;",
            g_last_builtin_oid);
1151 1152 1153

    res = PQexec(g_conn, query);
    if (!res || 
1154 1155 1156
        PQresultStatus(res) != PGRES_TUPLES_OK) {
        fprintf(stderr,"getIndices(): SELECT failed\n");
        exit_nicely(g_conn);
1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170
    }

    ntups = PQntuples(res);

    *numIndices = ntups;

    indinfo = (IndInfo*)malloc(ntups * sizeof (IndInfo));

    i_indexrelname = PQfnumber(res,"indexrelname");
    i_indrelname = PQfnumber(res,"indrelname");
    i_indamname = PQfnumber(res,"indamname");
    i_indproc = PQfnumber(res,"indproc");
    i_indkey = PQfnumber(res,"indkey");
    i_indclassname = PQfnumber(res,"indclassname");
M
Marc G. Fournier 已提交
1171
    i_indisunique = PQfnumber(res,"indisunique");
1172 1173

    for (i=0;i<ntups;i++) {
1174 1175 1176 1177 1178 1179
        indinfo[i].indexrelname = strdup(PQgetvalue(res,i,i_indexrelname));
        indinfo[i].indrelname = strdup(PQgetvalue(res,i,i_indrelname));
        indinfo[i].indamname = strdup(PQgetvalue(res,i,i_indamname));
        indinfo[i].indproc = strdup(PQgetvalue(res,i,i_indproc));
        indinfo[i].indkey = strdup(PQgetvalue(res,i,i_indkey));
        indinfo[i].indclassname = strdup(PQgetvalue(res,i,i_indclassname));
M
Marc G. Fournier 已提交
1180
        indinfo[i].indisunique = strdup(PQgetvalue(res,i,i_indisunique));
1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194
    }
    PQclear(res);
    res = PQexec(g_conn,"end");

    return indinfo;
}

/*
 * dumpTypes
 *    writes out to fout the queries to recreate all the user-defined types
 *
 */
void
dumpTypes(FILE* fout, FuncInfo* finfo, int numFuncs,
1195
          TypeInfo* tinfo, int numTypes)
1196 1197 1198 1199 1200 1201 1202
{
    int i;
    char q[MAXQUERYLEN];
    int funcInd;

    for (i=0;i<numTypes;i++) {

1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252
        /* skip all the builtin types */
        if (atoi(tinfo[i].oid) < g_last_builtin_oid)
            continue;

        /* skip relation types */
        if (atoi(tinfo[i].typrelid) != 0)
            continue;

        /* skip all array types that start w/ underscore */
        if ( (tinfo[i].typname[0] == '_') &&
             (strcmp(tinfo[i].typinput, "array_in") == 0))
            continue;

        /* before we create a type, we need to create the input and
           output functions for it, if they haven't been created already */
        funcInd = findFuncByName(finfo, numFuncs, tinfo[i].typinput);
        if (funcInd !=  -1) 
            dumpOneFunc(fout,finfo,funcInd,tinfo,numTypes);

        funcInd = findFuncByName(finfo, numFuncs, tinfo[i].typoutput);
        if (funcInd !=  -1) 
            dumpOneFunc(fout,finfo,funcInd,tinfo,numTypes);

        sprintf(q,
                "CREATE TYPE %s "
                "( internallength = %s, externallength = %s, input = %s, "
                "output = %s, send = %s, receive = %s, default = '%s'",
                tinfo[i].typname,
                tinfo[i].typlen,
                tinfo[i].typprtlen,
                tinfo[i].typinput,
                tinfo[i].typoutput,
                tinfo[i].typsend,
                tinfo[i].typreceive,
                tinfo[i].typdefault);

        if (tinfo[i].isArray) {
            char* elemType;

            elemType = findTypeByOid(tinfo, numTypes, tinfo[i].typelem);
            
            sprintf(q,"%s, element = %s, delimiter = '%s'",
                    q, elemType,tinfo[i].typdelim);
        }
        if (tinfo[i].passedbyvalue)
            strcat(q,",passedbyvalue);\n");
        else
            strcat(q,");\n");
            
        fputs(q,fout);
1253 1254 1255 1256 1257 1258 1259 1260 1261 1262
    }
}

/*
 * dumpFuncs
 *    writes out to fout the queries to recreate all the user-defined functions
 *
 */
void
dumpFuncs(FILE* fout, FuncInfo* finfo, int numFuncs, 
1263
          TypeInfo *tinfo, int numTypes)
1264 1265 1266
{
    int i;
    for (i=0;i<numFuncs;i++)  {
1267
        dumpOneFunc(fout,finfo,i,tinfo,numTypes);
1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279
    }
}

/*
 * dumpOneFunc:
 *    dump out only one function,  the index of which is given in the third
 *  argument
 *
 */

void
dumpOneFunc(FILE* fout, FuncInfo* finfo, int i,
1280
            TypeInfo *tinfo, int numTypes)
1281 1282 1283 1284 1285
{
    char q[MAXQUERYLEN];
    int j;
    
    if (finfo[i].dumped)
1286
        return;
1287
    else
1288
        finfo[i].dumped = 1;
1289 1290 1291

    sprintf(q,"CREATE FUNCTION %s (",finfo[i].proname);
    for (j=0;j<finfo[i].nargs;j++) {
1292 1293 1294 1295 1296 1297
        char* typname;
        typname = findTypeByOid(tinfo, numTypes, finfo[i].argtypes[j]);
        sprintf(q, "%s%s%s",
                q,  
                (j > 0) ? "," : "",
                typname);
1298 1299
    }
    sprintf(q,"%s ) RETURNS %s%s AS '%s' LANGUAGE '%s';\n",
1300 1301 1302 1303 1304
                q, 
            finfo[i].retset ? " SETOF " : "",
            findTypeByOid(tinfo, numTypes, finfo[i].prorettype),
            (finfo[i].lang) ? finfo[i].probin : finfo[i].prosrc,
            (finfo[i].lang) ? "C" : "SQL");
1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316
    
    fputs(q,fout);

}

/*
 * dumpOprs
 *    writes out to fout the queries to recreate all the user-defined operators
 *
 */
void 
dumpOprs(FILE* fout, OprInfo* oprinfo, int numOperators,
1317
         TypeInfo *tinfo, int numTypes)
1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330
{
    int i;
    char q[MAXQUERYLEN];
    char leftarg[MAXQUERYLEN];
    char rightarg[MAXQUERYLEN];
    char commutator[MAXQUERYLEN];
    char negator[MAXQUERYLEN];
    char restrict[MAXQUERYLEN];
    char join[MAXQUERYLEN];
    char sortop[MAXQUERYLEN];

    for (i=0;i<numOperators;i++) {

1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399
        /* skip all the builtin oids */
        if (atoi(oprinfo[i].oid) < g_last_builtin_oid)
            continue;

        /* some operator are invalid because they were the result
           of user defining operators before commutators exist */
        if (strcmp(oprinfo[i].oprcode, "-") == 0)
            continue;

        leftarg[0] = '\0';
        rightarg[0] = '\0';
        /* right unary means there's a left arg
           and left unary means there's a right arg */
        if (strcmp(oprinfo[i].oprkind, "r") == 0 || 
            strcmp(oprinfo[i].oprkind, "b") == 0 ) {
            sprintf(leftarg, ", LEFTARG = %s ",
                    findTypeByOid(tinfo, numTypes, oprinfo[i].oprleft));
        } 
        if (strcmp(oprinfo[i].oprkind, "l") == 0 || 
            strcmp(oprinfo[i].oprkind, "b") == 0 ) {
            sprintf(rightarg, ", RIGHTARG = %s ",
                    findTypeByOid(tinfo, numTypes, oprinfo[i].oprright));
        }
        if (strcmp(oprinfo[i].oprcom, "0") == 0) 
            commutator[0] = '\0';
        else
            sprintf(commutator,", COMMUTATOR = %s ",
                    findOprByOid(oprinfo, numOperators, oprinfo[i].oprcom));

        if (strcmp(oprinfo[i].oprnegate, "0") == 0) 
            negator[0] = '\0';
        else
            sprintf(negator,", NEGATOR = %s ",
                    findOprByOid(oprinfo, numOperators, oprinfo[i].oprnegate));

        if (strcmp(oprinfo[i].oprrest, "-") == 0)
            restrict[0] = '\0';
        else
            sprintf(restrict,", RESTRICT = %s ", oprinfo[i].oprrest);
                    
        if (strcmp(oprinfo[i].oprjoin,"-") == 0)
            join[0] = '\0';
        else
            sprintf(join,", JOIN = %s ", oprinfo[i].oprjoin);
                    
        if (strcmp(oprinfo[i].oprlsortop, "0") == 0) 
            sortop[0] = '\0';
        else
            {
            sprintf(sortop,", SORT = %s ",
                    findOprByOid(oprinfo, numOperators,
                                 oprinfo[i].oprlsortop));
            if (strcmp(oprinfo[i].oprrsortop, "0") != 0)
                sprintf(sortop, "%s , %s", sortop, 
                        findOprByOid(oprinfo, numOperators,
                                     oprinfo[i].oprlsortop));
        }

        sprintf(q,
                "CREATE OPERATOR %s "
                "(PROCEDURE = %s %s %s %s %s %s %s %s %s);\n ",
                oprinfo[i].oprname,
                oprinfo[i].oprcode,
                leftarg,
                rightarg,
                commutator,
                negator,
                restrict,
                (strcmp(oprinfo[i].oprcanhash, "t")) ? ", HASHES" : "",
1400
                join,
1401
                sortop);
1402

1403
        fputs(q,fout);
1404 1405 1406 1407 1408 1409 1410 1411 1412 1413
    }
}

/*
 * dumpAggs
 *    writes out to fout the queries to create all the user-defined aggregates
 *
 */
void
dumpAggs(FILE* fout, AggInfo* agginfo, int numAggs,
1414
        TypeInfo *tinfo, int numTypes)
1415 1416 1417 1418 1419 1420 1421 1422 1423
{
    int i;
    char q[MAXQUERYLEN];
    char sfunc1[MAXQUERYLEN];
    char sfunc2[MAXQUERYLEN];
    char finalfunc[MAXQUERYLEN];
    char comma1[2], comma2[2];

    for (i=0;i<numAggs;i++) {
1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477
        /* skip all the builtin oids */
        if (atoi(agginfo[i].oid) < g_last_builtin_oid)
            continue;

        if ( strcmp(agginfo[i].aggtransfn1, "-") == 0) 
            sfunc1[0] = '\0';
        else {
            sprintf(sfunc1, 
                    "SFUNC1 = %s, BASETYPE = %s, STYPE1 = %s",
                    agginfo[i].aggtransfn1,
                    findTypeByOid(tinfo,numTypes,agginfo[i].aggbasetype),
                    findTypeByOid(tinfo,numTypes,agginfo[i].aggtranstype1));
            if (agginfo[i].agginitval1)
                sprintf(sfunc1, "%s ,INITCOND1 = '%s'",
                        sfunc1, agginfo[i].agginitval1);
            
        }

        if ( strcmp(agginfo[i].aggtransfn2, "-") == 0) 
            sfunc2[0] = '\0';
        else {
            sprintf(sfunc2, 
                    "SFUNC2 = %s, STYPE2 = %s",
                    agginfo[i].aggtransfn2,
                    findTypeByOid(tinfo,numTypes,agginfo[i].aggtranstype2));
            if (agginfo[i].agginitval2)
                sprintf(sfunc2,"%s ,INITCOND2 = '%s'",
                        sfunc2, agginfo[i].agginitval2);
        }
        
        if ( strcmp(agginfo[i].aggfinalfn, "-") == 0)
            finalfunc[0] = '\0';
        else {
            sprintf(finalfunc, "FINALFUNC = %s", agginfo[i].aggfinalfn);
        }
        if (sfunc1[0] != '\0' && sfunc2[0] != '\0') {
            comma1[0] = ','; comma1[1] = '\0';
        } else
            comma1[0] = '\0';

        if (finalfunc[0] != '\0' && (sfunc1[0] != '\0' || sfunc2[0] != '\0')) {
            comma2[0] = ',';comma2[1] = '\0';
        } else
            comma2[0] = '\0';

        sprintf(q,"CREATE AGGREGATE %s ( %s %s %s %s %s );\n",
                agginfo[i].aggname,
                sfunc1,
                comma1,
                sfunc2,
                comma2,
                finalfunc);

        fputs(q,fout);
1478 1479 1480 1481 1482 1483 1484
    }
}

/*
 * dumpTables:
 *    write out to fout all the user-define tables
 */
1485 1486

void dumpTables(FILE* fout, TableInfo *tblinfo, int numTables,
1487 1488
           InhInfo *inhinfo, int numInherits,
           TypeInfo *tinfo, int numTypes, const char *tablename)
1489 1490 1491 1492 1493 1494
{
    int i,j,k;
    char q[MAXQUERYLEN];
    char **parentRels;  /* list of names of parent relations */
    int numParents;
    int actual_atts; /* number of attrs in this CREATE statment */
1495
    const char *archiveMode;
1496 1497 1498

    for (i=0;i<numTables;i++) {

1499 1500
        if (!tablename || (!strcmp(tblinfo[i].relname,tablename))) {

M
Marc G. Fournier 已提交
1501 1502 1503 1504
	    /* Skip VIEW relations */
            if (isViewRule(tblinfo[i].relname))
                continue;

1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588
            /* skip archive names*/
            if (isArchiveName(tblinfo[i].relname))
                continue;

            parentRels = tblinfo[i].parentRels;
            numParents = tblinfo[i].numParents;

            sprintf(q, "CREATE TABLE %s (", tblinfo[i].relname);
            actual_atts = 0;
            for (j=0;j<tblinfo[i].numatts;j++) {
                if (tblinfo[i].inhAttrs[j] == 0) {
                
                    /* Show lengths on bpchar and varchar */
                    if (!strcmp(tblinfo[i].typnames[j],"bpchar")) {
                        sprintf(q, "%s%s%s char",
                                q,
                                (actual_atts > 0) ? ", " : "",
                                tblinfo[i].attnames[j]);

                        /* stored length can be -1 (variable) */
                        if (tblinfo[i].attlen[j] > 0)
                                sprintf(q, "%s(%d)",
                                        q,
                                        tblinfo[i].attlen[j]);
                        actual_atts++;
                    }
                    else if (!strcmp(tblinfo[i].typnames[j],"varchar")) {
                        sprintf(q, "%s%s%s %s",
                                q,
                                (actual_atts > 0) ? ", " : "",
                                tblinfo[i].attnames[j],
                                tblinfo[i].typnames[j]);

                        /* stored length can be -1 (variable) */
                        if (tblinfo[i].attlen[j] > 0)
                                sprintf(q, "%s(%d)",
                                        q,
                                        tblinfo[i].attlen[j]);
                        actual_atts++;
                    }
                    else {    
                        sprintf(q, "%s%s%s %s",
                                q,
                                (actual_atts > 0) ? ", " : "",
                                tblinfo[i].attnames[j],
                                tblinfo[i].typnames[j]);
                        actual_atts++;
                    }
                }
            }

            strcat(q,")");

            if (numParents > 0) {
                sprintf(q, "%s inherits ( ",q);
                for (k=0;k<numParents;k++){
                sprintf(q, "%s%s%s",
                            q,
                            (k>0) ? ", " : "",
                            parentRels[k]);
                }
                strcat(q,")");
            }

            switch(tblinfo[i].relarch[0]) {
            case 'n':
                archiveMode = "none";
                break;
            case 'h':
                archiveMode = "heavy";
                break;
            case 'l':
                archiveMode = "light";
                break;
            default:
                fprintf(stderr, "unknown archive mode\n");
                archiveMode = "none";
                break;
            }
            
            sprintf(q, "%s archive = %s;\n",
                    q,
                    archiveMode);
            fputs(q,fout);
1589
        }
1590 1591 1592 1593 1594 1595 1596 1597 1598
    }
}

/*
 * dumpIndices:
 *    write out to fout all the user-define indices
 */
void 
dumpIndices(FILE* fout, IndInfo* indinfo, int numIndices,
1599
            TableInfo* tblinfo, int numTables, const char *tablename)
1600 1601 1602
{
    int i;
    int tableInd;
1603
    const char *attname;  /* the name of the indexed attribute  */
1604
    char *funcname; /* the name of the function to comput the index key from*/
1605 1606 1607 1608 1609 1610
    int indkey;

    char q[MAXQUERYLEN];
    PGresult *res;

    for (i=0;i<numIndices;i++) {
1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635
        tableInd = findTableByName(tblinfo, numTables,
                                   indinfo[i].indrelname);
        indkey = atoi(indinfo[i].indkey) - 1; 
        if (indkey == ObjectIdAttributeNumber - 1)
            attname = "oid";
        else
            attname = tblinfo[tableInd].attnames[indkey];
        if (strcmp(indinfo[i].indproc,"0") == 0) {
            funcname = NULL;
        } else {
            /* the funcname is an oid which we use to 
               find the name of the pg_proc.  We need to do this
               because getFuncs() only reads in the user-defined funcs
               not all the funcs.  We might not find what we want
               by looking in FuncInfo**/
            sprintf(q,
                    "SELECT proname from pg_proc "
                    "where pg_proc.oid = '%s'::oid",
                    indinfo[i].indproc);
            res = PQexec(g_conn, q);
            funcname = strdup(PQgetvalue(res, 0,
                                         PQfnumber(res,"proname")));
            PQclear(res);
        }
        
1636
        if (!tablename || (!strcmp(indinfo[i].indrelname,tablename))) {
1637
        
M
Marc G. Fournier 已提交
1638 1639
            sprintf(q,"CREATE %s INDEX %s on %s using %s (",
		    (strcmp(indinfo[i].indisunique, "t") == 0) ? "UNIQUE" : "",
1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652
                    indinfo[i].indexrelname,
                    indinfo[i].indrelname,
                    indinfo[i].indamname);
            if (funcname) {
                sprintf(q, "%s %s(%s) %s);\n",
                        q,funcname, attname, indinfo[i].indclassname);
                free(funcname); 
            } else
                sprintf(q, "%s %s %s);\n",
                        q,attname,indinfo[i].indclassname);

            fputs(q,fout);
        }    
1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678
    }

}
/*
 * dumpTuples --
 *    prints out the tuples in ASCII representation. The output is a valid
 *    input to COPY FROM stdin.
 *
 *    We only need to do this for POSTGRES 4.2 databases since the
 *    COPY TO statment doesn't escape newlines properly. It's been fixed
 *    in Postgres95.
 * 
 * the attrmap passed in tells how to map the attributes copied in to the
 * attributes copied out
 */
void
dumpTuples(PGresult *res, FILE *fout, int* attrmap)
{
    int j, k;
    int m, n;
    char **outVals = NULL; /* values to copy out */

    n = PQntuples(res);
    m = PQnfields(res);
    
    if ( m > 0 ) {
1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707
        /*
         * Print out the tuples but only print tuples with at least
         * 1 field.
         */
        outVals = (char**)malloc(m * sizeof(char*));

        for (j = 0; j < n; j++) {
            for (k = 0; k < m; k++) {
                outVals[attrmap[k]] = PQgetvalue(res, j, k);
            }
            for (k = 0; k < m; k++) {
                char *pval = outVals[k];

                if (k!=0)
                    fputc('\t', fout);  /* delimiter for attribute */

                if (pval) {
                    while (*pval != '\0') {
                        /* escape tabs, newlines and backslashes */
                        if (*pval=='\t' || *pval=='\n' || *pval=='\\')
                            fputc('\\', fout);
                        fputc(*pval, fout);
                        pval++;
                    }
                }
            }
            fputc('\n', fout);  /* delimiter for a tuple */
        }
        free (outVals);
1708 1709 1710
    }
}

1711 1712 1713 1714
/*
 * setMaxOid -
 * find the maximum oid and generate a COPY statement to set it
*/
1715

1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749
void
setMaxOid(FILE *fout)
{
    PGresult *res;
    Oid max_oid;
    
    res = PQexec(g_conn, "CREATE TABLE pgdump_oid (dummy int4)");
    if (!res || 
        PQresultStatus(res) != PGRES_COMMAND_OK) {
        fprintf(stderr,"Can not create pgdump_oid table\n");
        exit_nicely(g_conn);
    }
    PQclear(res);
    res = PQexec(g_conn, "INSERT INTO pgdump_oid VALUES (0)");
    if (!res || 
        PQresultStatus(res) != PGRES_COMMAND_OK) {
        fprintf(stderr,"Can not insert into pgdump_oid table\n");
        exit_nicely(g_conn);
    }
    max_oid = atol(PQoidStatus(res));
    if (max_oid == 0) {
        fprintf(stderr,"Invalid max id in setMaxOid\n");
        exit_nicely(g_conn);
    }
    PQclear(res);
    res = PQexec(g_conn, "DROP TABLE pgdump_oid;");
    if (!res || 
        PQresultStatus(res) != PGRES_COMMAND_OK) {
        fprintf(stderr,"Can not drop pgdump_oid table\n");
        exit_nicely(g_conn);
    }
    PQclear(res);
    if (g_verbose) 
        fprintf(stderr, "%s maximum system oid is %d %s\n",
1750
            g_comment_start,  max_oid, g_comment_end);
1751 1752
    fprintf(fout, "CREATE TABLE pgdump_oid (dummy int4);\n");
    fprintf(fout, "COPY pgdump_oid WITH OIDS FROM stdin;\n");
B
Bruce Momjian 已提交
1753
    fprintf(fout, "%-d\t0\n", max_oid);
1754 1755
    fprintf(fout, "\\.\n");
    fprintf(fout, "DROP TABLE pgdump_oid;\n");
1756
}       
1757 1758 1759 1760 1761 1762 1763 1764 1765

/*
 * findLastBuiltInOid -
 * find the last built in oid 
 * we do this by looking up the oid of 'template1' in pg_database,
 * this is probably not foolproof but comes close 
*/

int
1766
findLastBuiltinOid(void)
1767
{
1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787
    PGresult* res;
    int ntups;
    int last_oid;

    res = PQexec(g_conn, 
                 "SELECT oid from pg_database where datname = 'template1';");
    if (res == NULL ||
        PQresultStatus(res) != PGRES_TUPLES_OK) {
        fprintf(stderr,"pg_dump error in finding the template1 database\n");
        exit_nicely(g_conn);
    }
    ntups = PQntuples(res);
    if (ntups != 1) {
        fprintf(stderr,"pg_dump: couldn't find the template1 database.  "
                "You are really hosed.\nGiving up.\n");
        exit_nicely(g_conn);
    }
    last_oid = atoi(PQgetvalue(res, 0, PQfnumber(res, "oid")));
    PQclear(res);
    return last_oid;
1788 1789 1790 1791 1792 1793 1794 1795
}


/*
 * checkForQuote:
 *    checks a string for quote characters and quotes them
 */
char*
1796
checkForQuote(const char* s)
1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807
{
    char *r;
    char c;
    char *result;

    int j = 0;

    r = malloc(strlen(s)*3 + 1);  /* definitely long enough */

    while ( (c = *s) != '\0') {

1808 1809 1810 1811 1812
        if (c == '\'') {
            r[j++] = '\''; /* quote the single quotes */
        }
        r[j++] = c;
        s++;
1813 1814 1815
    }
    r[j] = '\0';

1816
    result = strdup(r);
1817 1818 1819 1820 1821
    free(r);

    return result;
    
}