initdb.sh 27.2 KB
Newer Older
1
#!@SHELL@
M
 
Marc G. Fournier 已提交
2 3
#-------------------------------------------------------------------------
#
P
Peter Eisentraut 已提交
4
# initdb creates (initializes) a PostgreSQL database cluster (site,
5
# instance, installation, whatever).  A database cluster is a
P
Peter Eisentraut 已提交
6
# collection of PostgreSQL databases all managed by the same postmaster.
M
 
Marc G. Fournier 已提交
7
#
8 9
# To create the database cluster, we create the directory that contains
# all its data, create the files that hold the global tables, create
10 11
# a few other control files for it, and create two databases: the
# template0 and template1 databases.
M
 
Marc G. Fournier 已提交
12
#
13 14 15 16
# The template databases are ordinary PostgreSQL databases.  template0
# is never supposed to change after initdb, whereas template1 can be
# changed to add site-local standard data.  Either one can be copied
# to produce a new database.
M
 
Marc G. Fournier 已提交
17
#
18 19 20 21 22 23 24
# To create template1, we run the postgres (backend) program in bootstrap
# mode and feed it data from the postgres.bki library file.  After this
# initial bootstrap phase, some additional stuff is created by normal
# SQL commands fed to a standalone backend.  Those commands are just
# embedded into this script (yeah, it's ugly).
#
# template0 is made just by copying the completed template1.
M
 
Marc G. Fournier 已提交
25 26
#
#
27 28
# Portions Copyright (c) 1996-2001, PostgreSQL Global Development Group
# Portions Copyright (c) 1994, Regents of the University of California
M
 
Marc G. Fournier 已提交
29
#
30
# $Header: /cvsroot/pgsql/src/bin/initdb/Attic/initdb.sh,v 1.144 2002/03/01 22:45:16 petere Exp $
B
Bruce Momjian 已提交
31 32 33
#
#-------------------------------------------------------------------------

34 35 36 37 38

##########################################################################
#
# INITIALIZATION

39
exit_nicely(){
B
Bruce Momjian 已提交
40
    stty echo > /dev/null 2>&1
41 42
    echo 1>&2
    echo "$CMDNAME failed." 1>&2
43
    if [ "$noclean" != yes ]; then
44
        if [ "$made_new_pgdata" = yes ]; then
45 46
            echo "Removing $PGDATA." 1>&2
            rm -rf "$PGDATA" || echo "Failed." 1>&2
47
        fi
B
Bruce Momjian 已提交
48
    else
49
        echo "Data directory $PGDATA will not be removed at user's request." 1>&2
B
Bruce Momjian 已提交
50 51 52 53 54 55 56
    fi
    exit 1
}


CMDNAME=`basename $0`

57
# Placed here during build
58 59
VERSION='@VERSION@'
bindir='@bindir@'
60 61
# Note that "datadir" is not the directory we're initializing, it's
# merely how Autoconf names PREFIX/share.
62
datadir='@datadir@'
63
# as set by configure --enable-multibyte[=XXX].
64
MULTIBYTE='@MULTIBYTE@'
65

P
Peter Eisentraut 已提交
66 67 68 69 70 71 72 73 74 75 76 77

# Check for echo -n vs echo \c
if echo '\c' | grep -s c >/dev/null 2>&1
then
    ECHO_N="echo -n"
    ECHO_C=""
else
    ECHO_N="echo"
    ECHO_C='\c'
fi


B
Bruce Momjian 已提交
78 79 80
#
# Find out where we're located
#
81 82
if echo "$0" | grep '/' > /dev/null 2>&1 
then
B
Bruce Momjian 已提交
83
        # explicit dir name given
P
Peter Eisentraut 已提交
84
        self_path=`echo $0 | sed 's,/[^/]*$,,'`       # (dirname command is not portable)
B
Bruce Momjian 已提交
85 86
else
        # look for it in PATH ('which' command is not portable)
B
Bruce Momjian 已提交
87 88
        for dir in `echo "$PATH" | sed 's/:/ /g'`
	do
B
Bruce Momjian 已提交
89 90
                # empty entry in path means current dir
                [ -z "$dir" ] && dir='.'
91
                if [ -f "$dir/$CMDNAME" ]
B
Bruce Momjian 已提交
92
		then
P
Peter Eisentraut 已提交
93
                        self_path="$dir"
B
Bruce Momjian 已提交
94 95 96 97 98
                        break
                fi
        done
fi

P
Peter Eisentraut 已提交
99 100 101 102 103 104 105 106 107

# Check for right version of backend.  First we check for an
# executable in the same directory is this initdb script (presuming
# the above code worked).  Then we fall back to the hard-wired bindir.
# We do it in this order because during upgrades users might move
# their trees to backup places, so $bindir might be inaccurate.

if [ x"$self_path" != x"" ] \
  && [ -x "$self_path/postgres" ] \
108
  && [ x"`$self_path/postgres -V 2>/dev/null`" = x"postgres (PostgreSQL) $VERSION" ]
P
Peter Eisentraut 已提交
109 110 111
then
    PGPATH=$self_path
elif [ -x "$bindir/postgres" ]; then
112
    if [ x"`$bindir/postgres -V 2>/dev/null`" = x"postgres (PostgreSQL) $VERSION" ]
P
Peter Eisentraut 已提交
113 114 115
    then
        PGPATH=$bindir
    else
116 117 118 119 120 121 122 123 124 125 126 127 128
        # Maybe there was an error message?
        errormsg=`$bindir/postgres -V 2>&1 >/dev/null`
      (
        echo "The program "
        echo "    '$bindir/postgres'"
        echo "needed by $CMDNAME does not belong to PostgreSQL version $VERSION, or"
        echo "there may be a configuration problem."
        if test x"$errormsg" != x""; then
            echo
            echo "This was the error message issued by that program:"
            echo "$errormsg"
        fi
      ) 1>&2
P
Peter Eisentraut 已提交
129 130 131
        exit 1
    fi
else
132 133
    echo "The program 'postgres' is needed by $CMDNAME but was not found in" 1>&2
    echo "the directory '$bindir'.  Check your installation." 1>&2
P
Peter Eisentraut 已提交
134
    exit 1
135 136
fi

P
Peter Eisentraut 已提交
137 138 139 140

# Now we can assume that 'pg_id' belongs to the same version as the
# verified 'postgres' in the same directory.
if [ ! -x "$PGPATH/pg_id" ]; then
141 142
    echo "The program 'pg_id' is needed by $CMDNAME but was not found in" 1>&2
    echo "the directory '$PGPATH'.  Check your installation." 1>&2
P
Peter Eisentraut 已提交
143 144
    exit 1
fi
B
Bruce Momjian 已提交
145

146 147 148

EffectiveUser=`$PGPATH/pg_id -n -u`
if [ -z "$EffectiveUser" ]; then
149
    echo "$CMDNAME: could not determine current user name" 1>&2
150 151 152 153 154
    exit 1
fi

if [ `$PGPATH/pg_id -u` -eq 0 ]
then
155 156
    echo "You cannot run $CMDNAME as root. Please log in (using, e.g., 'su')" 1>&2
    echo "as the (unprivileged) user that will own the server process." 1>&2
157 158 159
    exit 1
fi

160

161 162
short_version=`echo $VERSION | sed -e 's!^\([0-9][0-9]*\.[0-9][0-9]*\).*!\1!'`
if [ x"$short_version" = x"" ] ; then
163
  echo "$CMDNAME: bug: version number has wrong format" 1>&2
164 165
  exit 1
fi
166

167 168 169 170 171

##########################################################################
#
# COMMAND LINE OPTIONS

B
Bruce Momjian 已提交
172 173 174 175
# 0 is the default (non-)encoding
MULTIBYTEID=0

# Set defaults:
176 177 178
debug=
noclean=
show_setting=
B
Bruce Momjian 已提交
179 180 181 182 183

# Note: There is a single compelling reason that the name of the database
#       superuser be the same as the Unix user owning the server process:
#       The single user postgres backend will only connect as the database
#       user with the same name as the Unix user running it. That's
184
#       a security measure.
185
POSTGRES_SUPERUSERNAME="$EffectiveUser"
B
Bruce Momjian 已提交
186

187
while [ "$#" -gt 0 ]
B
Bruce Momjian 已提交
188 189 190 191 192 193
do
    case "$1" in
        --help|-\?)
                usage=t
                break
                ;;
194
        --version|-V)
195 196 197
                echo "initdb (PostgreSQL) $VERSION"
                exit 0
                ;;
B
Bruce Momjian 已提交
198
        --debug|-d)
199
                debug=yes
B
Bruce Momjian 已提交
200 201
                echo "Running with debug mode on."
                ;;
202
        --show|-s)
203
        	show_setting=yes
204
        	;;        
B
Bruce Momjian 已提交
205
        --noclean|-n)
206
                noclean=yes
B
Bruce Momjian 已提交
207 208
                echo "Running with noclean mode on. Mistakes will not be cleaned up."
                ;;
209 210 211
# The name of the database superuser. Can be freely changed.
        --username|-U)
                POSTGRES_SUPERUSERNAME="$2"
B
Bruce Momjian 已提交
212
                shift;;
213 214
        --username=*)
                POSTGRES_SUPERUSERNAME=`echo $1 | sed 's/^--username=//'`
B
Bruce Momjian 已提交
215
                ;;
216 217
        -U*)
                POSTGRES_SUPERUSERNAME=`echo $1 | sed 's/^-U//'`
B
Bruce Momjian 已提交
218 219
                ;;
# The default password of the database superuser.
P
Peter Eisentraut 已提交
220 221 222
# Make initdb prompt for the default password of the database superuser.
        --pwprompt|-W)
                PwPrompt=1
B
Bruce Momjian 已提交
223 224 225 226 227 228 229 230 231 232 233 234
                ;;
# Directory where to install the data. No default, unless the environment
# variable PGDATA is set.
        --pgdata|-D)
                PGDATA="$2"
                shift;;
        --pgdata=*)
                PGDATA=`echo $1 | sed 's/^--pgdata=//'`
                ;;
        -D*)
                PGDATA=`echo $1 | sed 's/^-D//'`
                ;;
235
# The directory where the .bki input files are stored. Normally
236 237 238
# they are in PREFIX/share and this option should be unnecessary.
        -L)
                datadir="$2"
B
Bruce Momjian 已提交
239 240
                shift;;
        -L*)
241
                datadir=`echo $1 | sed 's/^-L//'`
B
Bruce Momjian 已提交
242 243 244
                ;;
# The encoding of the template1 database. Defaults to what you chose
# at configure time. (see above)
245
        --encoding|-E)
B
Bruce Momjian 已提交
246 247
                MULTIBYTE="$2"
                shift;;
P
Peter Eisentraut 已提交
248 249
        --encoding=*)
                MULTIBYTE=`echo $1 | sed 's/^--encoding=//'`
B
Bruce Momjian 已提交
250
                ;;
251 252
        -E*)
                MULTIBYTE=`echo $1 | sed 's/^-E//'`
B
Bruce Momjian 已提交
253
                ;;
P
Peter Eisentraut 已提交
254 255
	-*)
		echo "$CMDNAME: invalid option: $1"
256
		echo "Try '$CMDNAME --help' for more information."
P
Peter Eisentraut 已提交
257 258
		exit 1
		;;
B
Bruce Momjian 已提交
259
        *)
P
Peter Eisentraut 已提交
260
                PGDATA=$1
B
Bruce Momjian 已提交
261 262 263 264 265
                ;;
    esac
    shift
done

P
Peter Eisentraut 已提交
266
if [ "$usage" ]; then
267
    echo "$CMDNAME initializes a PostgreSQL database cluster."
268 269 270 271 272
    echo
    echo "Usage:"
    echo "  $CMDNAME [options] datadir"
    echo
    echo "Options:"
273
    echo " [-D, --pgdata] DATADIR       Location for this database cluster"
274 275
    echo "  -W, --pwprompt              Prompt for a password for the new superuser"
    if [ -n "$MULTIBYTE" ] ; then 
276
        echo "  -E, --encoding ENCODING     Set default encoding for new databases"
277
    fi
278
    echo "  -U, --username NAME         Database superuser name"
279
    echo "Less commonly used options: "
280
    echo "  -L DIRECTORY                Where to find the input files"
281 282 283 284 285
    echo "  -d, --debug                 Generate lots of debugging output"
    echo "  -n, --noclean               Do not clean up after errors"
    echo
    echo "Report bugs to <pgsql-bugs@postgresql.org>."
    exit 0
B
Bruce Momjian 已提交
286 287 288 289 290 291
fi

#-------------------------------------------------------------------------
# Resolve the multibyte encoding name
#-------------------------------------------------------------------------

292 293
if [ "$MULTIBYTE" ]
then
T
Tatsuo Ishii 已提交
294
	MULTIBYTEID=`$PGPATH/pg_encoding -b $MULTIBYTE`
295
        if [ "$?" -ne 0 ]
B
Bruce Momjian 已提交
296
	then
297
              (
P
Peter Eisentraut 已提交
298 299 300 301
                echo "$CMDNAME: pg_encoding failed"
                echo
                echo "Perhaps you did not configure PostgreSQL for multibyte support or"
                echo "the program was not successfully installed."
302
              ) 1>&2
B
Bruce Momjian 已提交
303 304
                exit 1
        fi
305 306
	if [ -z "$MULTIBYTEID" ]
	then
T
Tatsuo Ishii 已提交
307
		echo "$CMDNAME: $MULTIBYTE is not a valid backend encoding name" 1>&2
308
		exit 1
B
Bruce Momjian 已提交
309 310 311 312 313 314 315 316
	fi
fi


#-------------------------------------------------------------------------
# Make sure he told us where to build the database system
#-------------------------------------------------------------------------

317 318
if [ -z "$PGDATA" ]
then
319
  (
B
Bruce Momjian 已提交
320
    echo "$CMDNAME: You must identify where the the data for this database"
321
    echo "system will reside.  Do this with either a -D invocation"
B
Bruce Momjian 已提交
322
    echo "option or a PGDATA environment variable."
323
  ) 1>&2
B
Bruce Momjian 已提交
324 325 326 327 328 329 330 331
    exit 1
fi


#-------------------------------------------------------------------------
# Find the input files
#-------------------------------------------------------------------------

332 333
POSTGRES_BKI="$datadir"/postgres.bki
POSTGRES_DESCR="$datadir"/postgres.description
B
Bruce Momjian 已提交
334

335
PG_HBA_SAMPLE="$datadir"/pg_hba.conf.sample
336
PG_IDENT_SAMPLE="$datadir"/pg_ident.conf.sample
337
POSTGRESQL_CONF_SAMPLE="$datadir"/postgresql.conf.sample
B
Bruce Momjian 已提交
338

339
if [ "$show_setting" = yes ] || [ "$debug" = yes ]
340
then
341
  (
342
    echo
343
    echo "initdb variables:"
344
    for var in PGDATA datadir PGPATH MULTIBYTE MULTIBYTEID \
345
        POSTGRES_SUPERUSERNAME POSTGRES_BKI \
346
        POSTGRES_DESCR POSTGRESQL_CONF_SAMPLE \
347
	PG_HBA_SAMPLE PG_IDENT_SAMPLE ; do
348 349
        eval "echo '  '$var=\$$var"
    done
350
  ) 1>&2
351 352 353 354
fi

if [ "$show_setting" = yes ] ; then
    exit 0
355 356
fi

357 358
for PREREQ_FILE in "$POSTGRES_BKI" "$POSTGRES_DESCR" \
    "$PG_HBA_SAMPLE" "$PG_IDENT_SAMPLE" "$POSTGRESQL_CONF_SAMPLE"
B
Bruce Momjian 已提交
359
do
360
    if [ ! -f "$PREREQ_FILE" ] ; then
361
      (
B
Bruce Momjian 已提交
362 363
        echo "$CMDNAME does not find the file '$PREREQ_FILE'."
        echo "This means you have a corrupted installation or identified the"
364
        echo "wrong directory with the -L invocation option."
365
      ) 1>&2
B
Bruce Momjian 已提交
366 367 368 369
        exit 1
    fi
done

370 371
for file in "$POSTGRES_BKI"
do
P
Peter Eisentraut 已提交
372
     if [ x"`sed 1q $file`" != x"# PostgreSQL $short_version" ]; then
373
       (
P
Peter Eisentraut 已提交
374 375 376
         echo "The input file '$file' needed by $CMDNAME does not"
         echo "belong to PostgreSQL $VERSION.  Check your installation or specify the"
         echo "correct path using the -L option."
377
       ) 1>&2
P
Peter Eisentraut 已提交
378 379 380 381
         exit 1
     fi
done

B
Bruce Momjian 已提交
382

B
Bruce Momjian 已提交
383
trap 'echo "Caught signal." ; exit_nicely' 1 2 3 15
B
Bruce Momjian 已提交
384

385
# Let's go
386 387
echo "The files belonging to this database system will be owned by user \"$EffectiveUser\"."
echo "This user must also own the server process."
388
echo
B
Bruce Momjian 已提交
389

390 391 392
##########################################################################
#
# CREATE DATABASE DIRECTORY
M
 
Marc G. Fournier 已提交
393 394 395 396

# umask must disallow access to group, other for files and dirs
umask 077

397 398 399
# find out if directory is empty
pgdata_contents=`ls -A "$PGDATA" 2>/dev/null`
if [ x"$pgdata_contents" != x ]
400
then
401 402 403 404 405 406 407
    (
      echo "$CMDNAME: The directory $PGDATA exists but is not empty."
      echo "If you want to create a new database system, either remove or empty"
      echo "the directory $PGDATA or run initdb with"
      echo "an argument other than $PGDATA."
    ) 1>&2
    exit 1
M
 
Marc G. Fournier 已提交
408
else
409
    if [ ! -d "$PGDATA" ]; then
410
        $ECHO_N "creating directory $PGDATA... "$ECHO_C
411
        mkdir -p "$PGDATA" >/dev/null 2>&1 || mkdir "$PGDATA" || exit_nicely
412
        made_new_pgdata=yes
413
    else
414
        $ECHO_N "Fixing permissions on existing directory $PGDATA... "$ECHO_C
415
	chmod go-rwx "$PGDATA" || exit_nicely
M
 
Marc G. Fournier 已提交
416
    fi
417
    echo "ok"
418

419 420
    if [ ! -d "$PGDATA"/base ]
	then
421
        $ECHO_N "creating directory $PGDATA/base... "$ECHO_C
422
        mkdir "$PGDATA"/base || exit_nicely
423
	echo "ok"
M
 
Marc G. Fournier 已提交
424
    fi
425 426
    if [ ! -d "$PGDATA"/global ]
    then
427
        $ECHO_N "creating directory $PGDATA/global... "$ECHO_C
428
        mkdir "$PGDATA"/global || exit_nicely
429
	echo "ok"
430
    fi
431
    if [ ! -d "$PGDATA"/pg_xlog ]
B
Bruce Momjian 已提交
432
    then
433
        $ECHO_N "creating directory $PGDATA/pg_xlog... "$ECHO_C
434
        mkdir "$PGDATA"/pg_xlog || exit_nicely
435
	echo "ok"
436
    fi
437 438 439 440 441 442
    if [ ! -d "$PGDATA"/pg_clog ]
    then
        $ECHO_N "creating directory $PGDATA/pg_clog... "$ECHO_C
        mkdir "$PGDATA"/pg_clog || exit_nicely
	echo "ok"
    fi
M
 
Marc G. Fournier 已提交
443 444
fi

445 446 447

##########################################################################
#
448
# RUN BKI SCRIPT IN BOOTSTRAP MODE TO CREATE TEMPLATE1
M
 
Marc G. Fournier 已提交
449

450 451
# common backend options
PGSQL_OPT="-F -D$PGDATA"
M
 
Marc G. Fournier 已提交
452

453
if [ "$debug" = yes ]
454
then
M
 
Marc G. Fournier 已提交
455
    BACKEND_TALK_ARG="-d"
456 457
else
    PGSQL_OPT="$PGSQL_OPT -o /dev/null"
M
 
Marc G. Fournier 已提交
458 459 460
fi


461 462 463 464
$ECHO_N "creating template1 database in $PGDATA/base/1... "$ECHO_C

rm -rf "$PGDATA"/base/1 || exit_nicely
mkdir "$PGDATA"/base/1 || exit_nicely
M
 
Marc G. Fournier 已提交
465

466 467 468
# Top level PG_VERSION is checked by bootstrapper, so make it first
echo "$short_version" > "$PGDATA/PG_VERSION" || exit_nicely

469 470 471
cat "$POSTGRES_BKI" \
| sed -e "s/POSTGRES/$POSTGRES_SUPERUSERNAME/g" \
      -e "s/ENCODING/$MULTIBYTEID/g" \
472
| "$PGPATH"/postgres -boot -x1 $PGSQL_OPT $BACKEND_TALK_ARG template1 \
473
|| exit_nicely
M
 
Marc G. Fournier 已提交
474

475 476
# Make the per-database PGVERSION for template1 only after init'ing it
echo "$short_version" > "$PGDATA/base/1/PG_VERSION" || exit_nicely
M
 
Marc G. Fournier 已提交
477

478 479
echo "ok"

480 481
##########################################################################
#
482
# CREATE CONFIG FILES
483

484 485
$ECHO_N "creating configuration files... "$ECHO_C

486 487 488 489 490
cp "$PG_HBA_SAMPLE" "$PGDATA"/pg_hba.conf              || exit_nicely
cp "$PG_IDENT_SAMPLE" "$PGDATA"/pg_ident.conf          || exit_nicely
cp "$POSTGRESQL_CONF_SAMPLE" "$PGDATA"/postgresql.conf || exit_nicely
chmod 0600 "$PGDATA"/pg_hba.conf "$PGDATA"/pg_ident.conf \
	"$PGDATA"/postgresql.conf
M
 
Marc G. Fournier 已提交
491

492 493
echo "ok"

494 495 496
##########################################################################
#
# CREATE VIEWS and other things
497 498 499 500 501
#
# NOTE: because here we are driving a standalone backend (not psql), we must
# follow the standalone backend's convention that commands end at a newline.
# To break an SQL command across lines in this script, backslash-escape all
# internal newlines in the command.
502

503
PGSQL_OPT="$PGSQL_OPT -O"
M
 
Marc G. Fournier 已提交
504

505
$ECHO_N "initializing pg_shadow... "$ECHO_C
M
 
Marc G. Fournier 已提交
506

507 508 509 510 511 512 513 514 515 516 517 518
"$PGPATH"/postgres $PGSQL_OPT template1 >/dev/null <<EOF
-- Create a trigger so that direct updates to pg_shadow will be written
-- to the flat password file pg_pwd
CREATE TRIGGER pg_sync_pg_pwd AFTER INSERT OR UPDATE OR DELETE ON pg_shadow \
FOR EACH ROW EXECUTE PROCEDURE update_pg_pwd();
-- needs to be done before alter user, because alter user checks that
-- pg_shadow is secure ...
REVOKE ALL on pg_shadow FROM public;
EOF
if [ "$?" -ne 0 ]; then
    exit_nicely
fi
519
echo "ok"
520

P
Peter Eisentraut 已提交
521 522 523
# set up password
if [ "$PwPrompt" ]; then
    $ECHO_N "Enter new superuser password: "$ECHO_C
B
Bruce Momjian 已提交
524
    stty -echo > /dev/null 2>&1
P
Peter Eisentraut 已提交
525
    read FirstPw
B
Bruce Momjian 已提交
526
    stty echo > /dev/null 2>&1
P
Peter Eisentraut 已提交
527 528
    echo
    $ECHO_N "Enter it again: "$ECHO_C
B
Bruce Momjian 已提交
529
    stty -echo > /dev/null 2>&1
P
Peter Eisentraut 已提交
530
    read SecondPw
B
Bruce Momjian 已提交
531
    stty echo > /dev/null 2>&1
P
Peter Eisentraut 已提交
532 533
    echo
    if [ "$FirstPw" != "$SecondPw" ]; then
534
        echo "Passwords didn't match." 1>&2
P
Peter Eisentraut 已提交
535 536
        exit_nicely
    fi
537
    $ECHO_N "setting password... "$ECHO_C
538 539 540 541 542 543
    "$PGPATH"/postgres $PGSQL_OPT template1 >/dev/null <<EOF
	ALTER USER "$POSTGRES_SUPERUSERNAME" WITH PASSWORD '$FirstPw';
EOF
    if [ "$?" -ne 0 ]; then
	exit_nicely
    fi
544
    if [ ! -f "$PGDATA"/global/pg_pwd ]; then
545
        echo
546
        echo "The password file wasn't generated. Please report this problem." 1>&2
P
Peter Eisentraut 已提交
547 548
        exit_nicely
    fi
549
    echo "ok"
P
Peter Eisentraut 已提交
550 551
fi

552

553
$ECHO_N "enabling unlimited row size for system tables... "$ECHO_C
554

555 556 557 558 559 560 561 562 563 564 565
"$PGPATH"/postgres $PGSQL_OPT template1 >/dev/null <<EOF
ALTER TABLE pg_attrdef CREATE TOAST TABLE;
ALTER TABLE pg_description CREATE TOAST TABLE;
ALTER TABLE pg_proc CREATE TOAST TABLE;
ALTER TABLE pg_relcheck CREATE TOAST TABLE;
ALTER TABLE pg_rewrite CREATE TOAST TABLE;
ALTER TABLE pg_statistic CREATE TOAST TABLE;
EOF
if [ "$?" -ne 0 ]; then
    exit_nicely
fi
566
echo "ok"
567 568


569
$ECHO_N "creating system views... "$ECHO_C
570

571 572 573 574 575 576 577 578 579 580 581
"$PGPATH"/postgres $PGSQL_OPT template1 >/dev/null <<EOF

CREATE VIEW pg_user AS \
    SELECT \
        usename, \
        usesysid, \
        usecreatedb, \
        usetrace, \
        usesuper, \
        usecatupd, \
        '********'::text as passwd, \
582 583
        valuntil, \
        useconfig \
584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 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 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673
    FROM pg_shadow;

CREATE VIEW pg_rules AS \
    SELECT \
        C.relname AS tablename, \
        R.rulename AS rulename, \
        pg_get_ruledef(R.rulename) AS definition \
    FROM pg_rewrite R, pg_class C \
    WHERE R.rulename !~ '^_RET' \
        AND C.oid = R.ev_class;

CREATE VIEW pg_views AS \
    SELECT \
        C.relname AS viewname, \
        pg_get_userbyid(C.relowner) AS viewowner, \
        pg_get_viewdef(C.relname) AS definition \
    FROM pg_class C \
    WHERE C.relkind = 'v';

-- XXX why does pg_tables include sequences?

CREATE VIEW pg_tables AS \
    SELECT \
        C.relname AS tablename, \
        pg_get_userbyid(C.relowner) AS tableowner, \
        C.relhasindex AS hasindexes, \
        C.relhasrules AS hasrules, \
        (C.reltriggers > 0) AS hastriggers \
    FROM pg_class C \
    WHERE C.relkind IN ('r', 's');

CREATE VIEW pg_indexes AS \
    SELECT \
        C.relname AS tablename, \
        I.relname AS indexname, \
        pg_get_indexdef(X.indexrelid) AS indexdef \
    FROM pg_index X, pg_class C, pg_class I \
    WHERE C.relkind = 'r' AND I.relkind = 'i' \
        AND C.oid = X.indrelid \
        AND I.oid = X.indexrelid;

CREATE VIEW pg_stats AS \
    SELECT \
        relname AS tablename, \
        attname AS attname, \
        stanullfrac AS null_frac, \
        stawidth AS avg_width, \
        stadistinct AS n_distinct, \
        CASE 1 \
            WHEN stakind1 THEN stavalues1 \
            WHEN stakind2 THEN stavalues2 \
            WHEN stakind3 THEN stavalues3 \
            WHEN stakind4 THEN stavalues4 \
        END AS most_common_vals, \
        CASE 1 \
            WHEN stakind1 THEN stanumbers1 \
            WHEN stakind2 THEN stanumbers2 \
            WHEN stakind3 THEN stanumbers3 \
            WHEN stakind4 THEN stanumbers4 \
        END AS most_common_freqs, \
        CASE 2 \
            WHEN stakind1 THEN stavalues1 \
            WHEN stakind2 THEN stavalues2 \
            WHEN stakind3 THEN stavalues3 \
            WHEN stakind4 THEN stavalues4 \
        END AS histogram_bounds, \
        CASE 3 \
            WHEN stakind1 THEN stanumbers1[1] \
            WHEN stakind2 THEN stanumbers2[1] \
            WHEN stakind3 THEN stanumbers3[1] \
            WHEN stakind4 THEN stanumbers4[1] \
        END AS correlation \
    FROM pg_class c, pg_attribute a, pg_statistic s \
    WHERE c.oid = s.starelid AND c.oid = a.attrelid \
        AND a.attnum = s.staattnum \
        AND has_table_privilege(c.oid, 'select');

REVOKE ALL on pg_statistic FROM public;

CREATE VIEW pg_stat_all_tables AS \
    SELECT \
            C.oid AS relid, \
            C.relname AS relname, \
            pg_stat_get_numscans(C.oid) AS seq_scan, \
            pg_stat_get_tuples_returned(C.oid) AS seq_tup_read, \
            sum(pg_stat_get_numscans(I.indexrelid)) AS idx_scan, \
            sum(pg_stat_get_tuples_fetched(I.indexrelid)) AS idx_tup_fetch, \
            pg_stat_get_tuples_inserted(C.oid) AS n_tup_ins, \
            pg_stat_get_tuples_updated(C.oid) AS n_tup_upd, \
            pg_stat_get_tuples_deleted(C.oid) AS n_tup_del \
674
    FROM pg_class C LEFT OUTER JOIN \
675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702
         pg_index I ON C.oid = I.indrelid \
    WHERE C.relkind = 'r' \
    GROUP BY C.oid, C.relname;

CREATE VIEW pg_stat_sys_tables AS \
    SELECT * FROM pg_stat_all_tables \
    WHERE relname ~ '^pg_';

CREATE VIEW pg_stat_user_tables AS \
    SELECT * FROM pg_stat_all_tables \
    WHERE relname !~ '^pg_';

CREATE VIEW pg_statio_all_tables AS \
    SELECT \
            C.oid AS relid, \
            C.relname AS relname, \
            pg_stat_get_blocks_fetched(C.oid) - \
                    pg_stat_get_blocks_hit(C.oid) AS heap_blks_read, \
            pg_stat_get_blocks_hit(C.oid) AS heap_blks_hit, \
            sum(pg_stat_get_blocks_fetched(I.indexrelid) - \
                    pg_stat_get_blocks_hit(I.indexrelid)) AS idx_blks_read, \
            sum(pg_stat_get_blocks_hit(I.indexrelid)) AS idx_blks_hit, \
            pg_stat_get_blocks_fetched(T.oid) - \
                    pg_stat_get_blocks_hit(T.oid) AS toast_blks_read, \
            pg_stat_get_blocks_hit(T.oid) AS toast_blks_hit, \
            pg_stat_get_blocks_fetched(X.oid) - \
                    pg_stat_get_blocks_hit(X.oid) AS tidx_blks_read, \
            pg_stat_get_blocks_hit(X.oid) AS tidx_blks_hit \
703 704 705
    FROM pg_class C LEFT OUTER JOIN \
            pg_index I ON C.oid = I.indrelid LEFT OUTER JOIN \
            pg_class T ON C.reltoastrelid = T.oid LEFT OUTER JOIN \
706
            pg_class X ON T.reltoastidxid = X.oid \
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 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 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
    WHERE C.relkind = 'r' \
    GROUP BY C.oid, C.relname, T.oid, X.oid;

CREATE VIEW pg_statio_sys_tables AS \
    SELECT * FROM pg_statio_all_tables \
    WHERE relname ~ '^pg_';

CREATE VIEW pg_statio_user_tables AS \
    SELECT * FROM pg_statio_all_tables \
    WHERE relname !~ '^pg_';

CREATE VIEW pg_stat_all_indexes AS \
    SELECT \
            C.oid AS relid, \
            I.oid AS indexrelid, \
            C.relname AS relname, \
            I.relname AS indexrelname, \
            pg_stat_get_numscans(I.oid) AS idx_scan, \
            pg_stat_get_tuples_returned(I.oid) AS idx_tup_read, \
            pg_stat_get_tuples_fetched(I.oid) AS idx_tup_fetch \
    FROM pg_class C, \
            pg_class I, \
            pg_index X \
    WHERE C.relkind = 'r' AND \
            X.indrelid = C.oid AND \
            X.indexrelid = I.oid;

CREATE VIEW pg_stat_sys_indexes AS \
    SELECT * FROM pg_stat_all_indexes \
    WHERE relname ~ '^pg_';

CREATE VIEW pg_stat_user_indexes AS \
    SELECT * FROM pg_stat_all_indexes \
    WHERE relname !~ '^pg_';

CREATE VIEW pg_statio_all_indexes AS \
    SELECT \
            C.oid AS relid, \
            I.oid AS indexrelid, \
            C.relname AS relname, \
            I.relname AS indexrelname, \
            pg_stat_get_blocks_fetched(I.oid) - \
                    pg_stat_get_blocks_hit(I.oid) AS idx_blks_read, \
            pg_stat_get_blocks_hit(I.oid) AS idx_blks_hit \
    FROM pg_class C, \
            pg_class I, \
            pg_index X \
    WHERE C.relkind = 'r' AND \
            X.indrelid = C.oid AND \
            X.indexrelid = I.oid;

CREATE VIEW pg_statio_sys_indexes AS \
    SELECT * FROM pg_statio_all_indexes \
    WHERE relname ~ '^pg_';

CREATE VIEW pg_statio_user_indexes AS \
    SELECT * FROM pg_statio_all_indexes \
    WHERE relname !~ '^pg_';

CREATE VIEW pg_statio_all_sequences AS \
    SELECT \
            C.oid AS relid, \
            C.relname AS relname, \
            pg_stat_get_blocks_fetched(C.oid) - \
                    pg_stat_get_blocks_hit(C.oid) AS blks_read, \
            pg_stat_get_blocks_hit(C.oid) AS blks_hit \
    FROM pg_class C \
    WHERE C.relkind = 'S';

CREATE VIEW pg_statio_sys_sequences AS \
    SELECT * FROM pg_statio_all_sequences \
    WHERE relname ~ '^pg_';

CREATE VIEW pg_statio_user_sequences AS \
    SELECT * FROM pg_statio_all_sequences \
    WHERE relname !~ '^pg_';

CREATE VIEW pg_stat_activity AS \
    SELECT \
            D.oid AS datid, \
            D.datname AS datname, \
            pg_stat_get_backend_pid(S.backendid) AS procpid, \
            pg_stat_get_backend_userid(S.backendid) AS usesysid, \
            U.usename AS usename, \
            pg_stat_get_backend_activity(S.backendid) AS current_query \
    FROM pg_database D, \
            (SELECT pg_stat_get_backend_idset() AS backendid) AS S, \
            pg_shadow U \
    WHERE pg_stat_get_backend_dbid(S.backendid) = D.oid AND \
            pg_stat_get_backend_userid(S.backendid) = U.usesysid;

CREATE VIEW pg_stat_database AS \
    SELECT \
            D.oid AS datid, \
            D.datname AS datname, \
            pg_stat_get_db_numbackends(D.oid) AS numbackends, \
            pg_stat_get_db_xact_commit(D.oid) AS xact_commit, \
            pg_stat_get_db_xact_rollback(D.oid) AS xact_rollback, \
            pg_stat_get_db_blocks_fetched(D.oid) - \
                    pg_stat_get_db_blocks_hit(D.oid) AS blks_read, \
            pg_stat_get_db_blocks_hit(D.oid) AS blks_hit \
    FROM pg_database D;

EOF
if [ "$?" -ne 0 ]; then
    exit_nicely
fi
814
echo "ok"
815

816
$ECHO_N "loading pg_description... "$ECHO_C
817
(
818 819 820 821 822 823 824 825
  cat <<EOF
    CREATE TEMP TABLE tmp_pg_description ( \
	objoid oid, \
	classname name, \
	objsubid int4, \
	description text) WITHOUT OIDS;
    COPY tmp_pg_description FROM STDIN;
EOF
826
  cat "$POSTGRES_DESCR"
827 828 829 830 831 832
  cat <<EOF
\.
    INSERT INTO pg_description SELECT \
	t.objoid, c.oid, t.objsubid, t.description \
    FROM tmp_pg_description t, pg_class c WHERE c.relname = t.classname;
EOF
833
) \
834
	| "$PGPATH"/postgres $PGSQL_OPT template1 > /dev/null || exit_nicely
835
echo "ok"
836

837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854
# Set most system catalogs and built-in functions as world-accessible.
# Some objects may require different permissions by default, so we
# make sure we don't overwrite privilege sets that have already been
# set (NOT NULL).
$ECHO_N "setting privileges on built-in objects... "$ECHO_C
(
  cat <<EOF
    UPDATE pg_class SET relacl = '{"=r"}' \
        WHERE relkind IN ('r', 'v', 'S') AND relacl IS NULL;
    UPDATE pg_proc SET proacl = '{"=r"}' \
        WHERE proacl IS NULL;
    UPDATE pg_language SET lanacl = '{"=r"}' \
        WHERE lanpltrusted;
EOF
) \
	| "$PGPATH"/postgres $PGSQL_OPT template1 > /dev/null || exit_nicely
echo "ok"

855
$ECHO_N "vacuuming database template1... "$ECHO_C
856 857

"$PGPATH"/postgres $PGSQL_OPT template1 >/dev/null <<EOF
858
VACUUM FULL FREEZE;
859 860 861 862
EOF
if [ "$?" -ne 0 ]; then
    exit_nicely
fi
863
echo "ok"
864

865
$ECHO_N "copying template1 to template0... "$ECHO_C
866 867 868

"$PGPATH"/postgres $PGSQL_OPT template1 >/dev/null <<EOF
CREATE DATABASE template0;
869

870
UPDATE pg_database SET \
871 872
	datistemplate = 't', \
	datallowconn = 'f' \
873
    WHERE datname = 'template0';
874 875 876 877 878 879

-- We use the OID of template0 to determine lastsysoid

UPDATE pg_database SET datlastsysoid = \
    (SELECT oid - 1 FROM pg_database WHERE datname = 'template0');

880 881 882 883 884
VACUUM FULL pg_database;
EOF
if [ "$?" -ne 0 ]; then
    exit_nicely
fi
885
echo "ok"
886

887 888 889 890 891

##########################################################################
#
# FINISHED

892
echo
893
echo "Success. You can now start the database server using:"
894
echo ""
895
echo "    $PGPATH/postmaster -D $PGDATA"
896
echo "or"
897 898 899
# (Advertise -l option here, otherwise we have a background
#  process writing to the terminal.)
echo "    $PGPATH/pg_ctl -D $PGDATA -l logfile start"
900 901 902
echo

exit 0