OSDN Git Service

547f3fb2f3f0691abca3cf8502010afae54665ce
[pg-rex/syncrep.git] / src / backend / commands / dbcommands.c
1 /*-------------------------------------------------------------------------
2  *
3  * dbcommands.c
4  *              Database management commands (create/drop database).
5  *
6  *
7  * Portions Copyright (c) 1996-2002, PostgreSQL Global Development Group
8  * Portions Copyright (c) 1994, Regents of the University of California
9  *
10  *
11  * IDENTIFICATION
12  *        $Header: /cvsroot/pgsql/src/backend/commands/dbcommands.c,v 1.120 2003/08/04 00:43:16 momjian Exp $
13  *
14  *-------------------------------------------------------------------------
15  */
16 #include "postgres.h"
17
18 #include <errno.h>
19 #include <fcntl.h>
20 #include <unistd.h>
21 #include <sys/stat.h>
22
23 #include "access/genam.h"
24 #include "access/heapam.h"
25 #include "catalog/catname.h"
26 #include "catalog/catalog.h"
27 #include "catalog/pg_database.h"
28 #include "catalog/pg_shadow.h"
29 #include "catalog/indexing.h"
30 #include "commands/comment.h"
31 #include "commands/dbcommands.h"
32 #include "miscadmin.h"
33 #include "storage/freespace.h"
34 #include "storage/sinval.h"
35 #include "utils/acl.h"
36 #include "utils/array.h"
37 #include "utils/builtins.h"
38 #include "utils/fmgroids.h"
39 #include "utils/guc.h"
40 #include "utils/lsyscache.h"
41 #include "utils/syscache.h"
42
43 #include "mb/pg_wchar.h"                /* encoding check */
44
45
46 /* non-export function prototypes */
47 static bool get_db_info(const char *name, Oid *dbIdP, int4 *ownerIdP,
48                         int *encodingP, bool *dbIsTemplateP, Oid *dbLastSysOidP,
49                         TransactionId *dbVacuumXidP, TransactionId *dbFrozenXidP,
50                         char *dbpath);
51 static bool have_createdb_privilege(void);
52 static char *resolve_alt_dbpath(const char *dbpath, Oid dboid);
53 static bool remove_dbdirs(const char *real_loc, const char *altloc);
54
55 /*
56  * CREATE DATABASE
57  */
58
59 void
60 createdb(const CreatedbStmt *stmt)
61 {
62         char       *nominal_loc;
63         char       *alt_loc;
64         char       *target_dir;
65         char            src_loc[MAXPGPATH];
66         char            buf[2 * MAXPGPATH + 100];
67         Oid                     src_dboid;
68         AclId           src_owner;
69         int                     src_encoding;
70         bool            src_istemplate;
71         Oid                     src_lastsysoid;
72         TransactionId src_vacuumxid;
73         TransactionId src_frozenxid;
74         char            src_dbpath[MAXPGPATH];
75         Relation        pg_database_rel;
76         HeapTuple       tuple;
77         TupleDesc       pg_database_dsc;
78         Datum           new_record[Natts_pg_database];
79         char            new_record_nulls[Natts_pg_database];
80         Oid                     dboid;
81         AclId           datdba;
82         List       *option;
83         DefElem    *downer = NULL;
84         DefElem    *dpath = NULL;
85         DefElem    *dtemplate = NULL;
86         DefElem    *dencoding = NULL;
87         char       *dbname = stmt->dbname;
88         char       *dbowner = NULL;
89         char       *dbpath = NULL;
90         char       *dbtemplate = NULL;
91         int                     encoding = -1;
92
93         /* Extract options from the statement node tree */
94         foreach(option, stmt->options)
95         {
96                 DefElem    *defel = (DefElem *) lfirst(option);
97
98                 if (strcmp(defel->defname, "owner") == 0)
99                 {
100                         if (downer)
101                                 ereport(ERROR,
102                                                 (errcode(ERRCODE_SYNTAX_ERROR),
103                                                  errmsg("conflicting or redundant options")));
104                         downer = defel;
105                 }
106                 else if (strcmp(defel->defname, "location") == 0)
107                 {
108                         if (dpath)
109                                 ereport(ERROR,
110                                                 (errcode(ERRCODE_SYNTAX_ERROR),
111                                                  errmsg("conflicting or redundant options")));
112                         dpath = defel;
113                 }
114                 else if (strcmp(defel->defname, "template") == 0)
115                 {
116                         if (dtemplate)
117                                 ereport(ERROR,
118                                                 (errcode(ERRCODE_SYNTAX_ERROR),
119                                                  errmsg("conflicting or redundant options")));
120                         dtemplate = defel;
121                 }
122                 else if (strcmp(defel->defname, "encoding") == 0)
123                 {
124                         if (dencoding)
125                                 ereport(ERROR,
126                                                 (errcode(ERRCODE_SYNTAX_ERROR),
127                                                  errmsg("conflicting or redundant options")));
128                         dencoding = defel;
129                 }
130                 else
131                         elog(ERROR, "option \"%s\" not recognized",
132                                  defel->defname);
133         }
134
135         if (downer && downer->arg)
136                 dbowner = strVal(downer->arg);
137         if (dpath && dpath->arg)
138                 dbpath = strVal(dpath->arg);
139         if (dtemplate && dtemplate->arg)
140                 dbtemplate = strVal(dtemplate->arg);
141         if (dencoding && dencoding->arg)
142         {
143                 const char *encoding_name;
144
145                 if (IsA(dencoding->arg, Integer))
146                 {
147                         encoding = intVal(dencoding->arg);
148                         encoding_name = pg_encoding_to_char(encoding);
149                         if (strcmp(encoding_name, "") == 0 ||
150                                 pg_valid_server_encoding(encoding_name) < 0)
151                                 ereport(ERROR,
152                                                 (errcode(ERRCODE_UNDEFINED_OBJECT),
153                                                  errmsg("%d is not a valid encoding code",
154                                                                 encoding)));
155                 }
156                 else if (IsA(dencoding->arg, String))
157                 {
158                         encoding_name = strVal(dencoding->arg);
159                         if (pg_valid_server_encoding(encoding_name) < 0)
160                                 ereport(ERROR,
161                                                 (errcode(ERRCODE_UNDEFINED_OBJECT),
162                                                  errmsg("%s is not a valid encoding name",
163                                                                 encoding_name)));
164                         encoding = pg_char_to_encoding(encoding_name);
165                 }
166                 else
167                         elog(ERROR, "unrecognized node type: %d",
168                                  nodeTag(dencoding->arg));
169         }
170
171         /* obtain sysid of proposed owner */
172         if (dbowner)
173                 datdba = get_usesysid(dbowner); /* will ereport if no such user */
174         else
175                 datdba = GetUserId();
176
177         if (datdba == GetUserId())
178         {
179                 /* creating database for self: can be superuser or createdb */
180                 if (!superuser() && !have_createdb_privilege())
181                         ereport(ERROR,
182                                         (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
183                                          errmsg("permission denied to create database")));
184         }
185         else
186         {
187                 /* creating database for someone else: must be superuser */
188                 /* note that the someone else need not have any permissions */
189                 if (!superuser())
190                         ereport(ERROR,
191                                         (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
192                                          errmsg("must be superuser to create database for another user")));
193         }
194
195         /* don't call this in a transaction block */
196         PreventTransactionChain((void *) stmt, "CREATE DATABASE");
197
198         /* alternate location requires symlinks */
199 #ifndef HAVE_SYMLINK
200         if (dbpath != NULL)
201                 ereport(ERROR,
202                                 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
203                    errmsg("cannot use an alternate location on this platform")));
204 #endif
205
206         /*
207          * Check for db name conflict.  There is a race condition here, since
208          * another backend could create the same DB name before we commit.
209          * However, holding an exclusive lock on pg_database for the whole
210          * time we are copying the source database doesn't seem like a good
211          * idea, so accept possibility of race to create.  We will check again
212          * after we grab the exclusive lock.
213          */
214         if (get_db_info(dbname, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL))
215                 ereport(ERROR,
216                                 (errcode(ERRCODE_DUPLICATE_DATABASE),
217                                  errmsg("database \"%s\" already exists", dbname)));
218
219         /*
220          * Lookup database (template) to be cloned.
221          */
222         if (!dbtemplate)
223                 dbtemplate = "template1";               /* Default template database name */
224
225         if (!get_db_info(dbtemplate, &src_dboid, &src_owner, &src_encoding,
226                                          &src_istemplate, &src_lastsysoid,
227                                          &src_vacuumxid, &src_frozenxid,
228                                          src_dbpath))
229                 ereport(ERROR,
230                                 (errcode(ERRCODE_UNDEFINED_DATABASE),
231                                  errmsg("template \"%s\" does not exist", dbtemplate)));
232
233         /*
234          * Permission check: to copy a DB that's not marked datistemplate, you
235          * must be superuser or the owner thereof.
236          */
237         if (!src_istemplate)
238         {
239                 if (!superuser() && GetUserId() != src_owner)
240                         ereport(ERROR,
241                                         (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
242                                          errmsg("permission denied to copy database \"%s\"",
243                                                         dbtemplate)));
244         }
245
246         /*
247          * Determine physical path of source database
248          */
249         alt_loc = resolve_alt_dbpath(src_dbpath, src_dboid);
250         if (!alt_loc)
251                 alt_loc = GetDatabasePath(src_dboid);
252         strcpy(src_loc, alt_loc);
253
254         /*
255          * The source DB can't have any active backends, except this one
256          * (exception is to allow CREATE DB while connected to template1).
257          * Otherwise we might copy inconsistent data.  This check is not
258          * bulletproof, since someone might connect while we are copying...
259          */
260         if (DatabaseHasActiveBackends(src_dboid, true))
261                 ereport(ERROR,
262                                 (errcode(ERRCODE_OBJECT_IN_USE),
263                 errmsg("source database \"%s\" is being accessed by other users",
264                            dbtemplate)));
265
266         /* If encoding is defaulted, use source's encoding */
267         if (encoding < 0)
268                 encoding = src_encoding;
269
270         /* Some encodings are client only */
271         if (!PG_VALID_BE_ENCODING(encoding))
272                 ereport(ERROR,
273                                 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
274                                  errmsg("invalid backend encoding %d", encoding)));
275
276         /*
277          * Preassign OID for pg_database tuple, so that we can compute db
278          * path.
279          */
280         dboid = newoid();
281
282         /*
283          * Compute nominal location (where we will try to access the
284          * database), and resolve alternate physical location if one is
285          * specified.
286          *
287          * If an alternate location is specified but is the same as the normal
288          * path, just drop the alternate-location spec (this seems friendlier
289          * than erroring out).  We must test this case to avoid creating a
290          * circular symlink below.
291          */
292         nominal_loc = GetDatabasePath(dboid);
293         alt_loc = resolve_alt_dbpath(dbpath, dboid);
294
295         if (alt_loc && strcmp(alt_loc, nominal_loc) == 0)
296         {
297                 alt_loc = NULL;
298                 dbpath = NULL;
299         }
300
301         if (strchr(nominal_loc, '\''))
302                 ereport(ERROR,
303                                 (errcode(ERRCODE_INVALID_NAME),
304                                  errmsg("database path may not contain single quotes")));
305         if (alt_loc && strchr(alt_loc, '\''))
306                 ereport(ERROR,
307                                 (errcode(ERRCODE_INVALID_NAME),
308                                  errmsg("database path may not contain single quotes")));
309         if (strchr(src_loc, '\''))
310                 ereport(ERROR,
311                                 (errcode(ERRCODE_INVALID_NAME),
312                                  errmsg("database path may not contain single quotes")));
313         /* ... otherwise we'd be open to shell exploits below */
314
315         /*
316          * Force dirty buffers out to disk, to ensure source database is
317          * up-to-date for the copy.  (We really only need to flush buffers for
318          * the source database...)
319          */
320         BufferSync();
321
322         /*
323          * Close virtual file descriptors so the kernel has more available for
324          * the mkdir() and system() calls below.
325          */
326         closeAllVfds();
327
328         /*
329          * Check we can create the target directory --- but then remove it
330          * because we rely on cp(1) to create it for real.
331          */
332         target_dir = alt_loc ? alt_loc : nominal_loc;
333
334         if (mkdir(target_dir, S_IRWXU) != 0)
335                 ereport(ERROR,
336                                 (errcode_for_file_access(),
337                                  errmsg("could not create database directory \"%s\": %m",
338                                                 target_dir)));
339         if (rmdir(target_dir) != 0)
340                 ereport(ERROR,
341                                 (errcode_for_file_access(),
342                                  errmsg("could not remove temp directory \"%s\": %m",
343                                                 target_dir)));
344
345         /* Make the symlink, if needed */
346         if (alt_loc)
347         {
348 #ifdef HAVE_SYMLINK                             /* already throws error above */
349                 if (symlink(alt_loc, nominal_loc) != 0)
350 #endif
351                         ereport(ERROR,
352                                         (errcode_for_file_access(),
353                                          errmsg("could not link \"%s\" to \"%s\": %m",
354                                                         nominal_loc, alt_loc)));
355         }
356
357         /* Copy the template database to the new location */
358 #ifndef WIN32
359         snprintf(buf, sizeof(buf), "cp -r '%s' '%s'", src_loc, target_dir);
360         if (system(buf) != 0)
361 #else
362         if (copydir(src_loc, target_dir) != 0)
363 #endif
364         {
365                 if (remove_dbdirs(nominal_loc, alt_loc))
366                         elog(ERROR, "could not initialize database directory");
367                 else
368                         elog(ERROR, "could not initialize database directory; delete failed as well");
369         }
370
371         /*
372          * Now OK to grab exclusive lock on pg_database.
373          */
374         pg_database_rel = heap_openr(DatabaseRelationName, AccessExclusiveLock);
375
376         /* Check to see if someone else created same DB name meanwhile. */
377         if (get_db_info(dbname, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL))
378         {
379                 /* Don't hold lock while doing recursive remove */
380                 heap_close(pg_database_rel, AccessExclusiveLock);
381                 remove_dbdirs(nominal_loc, alt_loc);
382                 ereport(ERROR,
383                                 (errcode(ERRCODE_DUPLICATE_DATABASE),
384                                  errmsg("database \"%s\" already exists", dbname)));
385         }
386
387         /*
388          * Insert a new tuple into pg_database
389          */
390         pg_database_dsc = RelationGetDescr(pg_database_rel);
391
392         /* Form tuple */
393         MemSet(new_record, 0, sizeof(new_record));
394         MemSet(new_record_nulls, ' ', sizeof(new_record_nulls));
395
396         new_record[Anum_pg_database_datname - 1] =
397                 DirectFunctionCall1(namein, CStringGetDatum(dbname));
398         new_record[Anum_pg_database_datdba - 1] = Int32GetDatum(datdba);
399         new_record[Anum_pg_database_encoding - 1] = Int32GetDatum(encoding);
400         new_record[Anum_pg_database_datistemplate - 1] = BoolGetDatum(false);
401         new_record[Anum_pg_database_datallowconn - 1] = BoolGetDatum(true);
402         new_record[Anum_pg_database_datlastsysoid - 1] = ObjectIdGetDatum(src_lastsysoid);
403         new_record[Anum_pg_database_datvacuumxid - 1] = TransactionIdGetDatum(src_vacuumxid);
404         new_record[Anum_pg_database_datfrozenxid - 1] = TransactionIdGetDatum(src_frozenxid);
405         /* do not set datpath to null, GetRawDatabaseInfo won't cope */
406         new_record[Anum_pg_database_datpath - 1] =
407                 DirectFunctionCall1(textin, CStringGetDatum(dbpath ? dbpath : ""));
408
409         /*
410          * We deliberately set datconfig and datacl to defaults (NULL), rather
411          * than copying them from the template database.  Copying datacl would
412          * be a bad idea when the owner is not the same as the template's
413          * owner. It's more debatable whether datconfig should be copied.
414          */
415         new_record_nulls[Anum_pg_database_datconfig - 1] = 'n';
416         new_record_nulls[Anum_pg_database_datacl - 1] = 'n';
417
418         tuple = heap_formtuple(pg_database_dsc, new_record, new_record_nulls);
419
420         HeapTupleSetOid(tuple, dboid);          /* override heap_insert's OID
421                                                                                  * selection */
422
423         simple_heap_insert(pg_database_rel, tuple);
424
425         /* Update indexes */
426         CatalogUpdateIndexes(pg_database_rel, tuple);
427
428         /* Close pg_database, but keep lock till commit */
429         heap_close(pg_database_rel, NoLock);
430
431         /*
432          * Force dirty buffers out to disk, so that newly-connecting backends
433          * will see the new database in pg_database right away.  (They'll see
434          * an uncommitted tuple, but they don't care; see GetRawDatabaseInfo.)
435          */
436         BufferSync();
437 }
438
439
440 /*
441  * DROP DATABASE
442  */
443 void
444 dropdb(const char *dbname)
445 {
446         int4            db_owner;
447         bool            db_istemplate;
448         Oid                     db_id;
449         char       *alt_loc;
450         char       *nominal_loc;
451         char            dbpath[MAXPGPATH];
452         Relation        pgdbrel;
453         SysScanDesc pgdbscan;
454         ScanKeyData key;
455         HeapTuple       tup;
456
457         AssertArg(dbname);
458
459         if (strcmp(dbname, get_database_name(MyDatabaseId)) == 0)
460                 ereport(ERROR,
461                                 (errcode(ERRCODE_OBJECT_IN_USE),
462                                  errmsg("cannot drop the currently open database")));
463
464         PreventTransactionChain((void *) dbname, "DROP DATABASE");
465
466         /*
467          * Obtain exclusive lock on pg_database.  We need this to ensure that
468          * no new backend starts up in the target database while we are
469          * deleting it.  (Actually, a new backend might still manage to start
470          * up, because it will read pg_database without any locking to
471          * discover the database's OID.  But it will detect its error in
472          * ReverifyMyDatabase and shut down before any serious damage is done.
473          * See postinit.c.)
474          */
475         pgdbrel = heap_openr(DatabaseRelationName, AccessExclusiveLock);
476
477         if (!get_db_info(dbname, &db_id, &db_owner, NULL,
478                                          &db_istemplate, NULL, NULL, NULL, dbpath))
479                 ereport(ERROR,
480                                 (errcode(ERRCODE_UNDEFINED_DATABASE),
481                                  errmsg("database \"%s\" does not exist", dbname)));
482
483         if (GetUserId() != db_owner && !superuser())
484                 aclcheck_error(ACLCHECK_NOT_OWNER, ACL_KIND_DATABASE,
485                                            dbname);
486
487         /*
488          * Disallow dropping a DB that is marked istemplate.  This is just to
489          * prevent people from accidentally dropping template0 or template1;
490          * they can do so if they're really determined ...
491          */
492         if (db_istemplate)
493                 ereport(ERROR,
494                                 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
495                                  errmsg("cannot drop a template database")));
496
497         nominal_loc = GetDatabasePath(db_id);
498         alt_loc = resolve_alt_dbpath(dbpath, db_id);
499
500         /*
501          * Check for active backends in the target database.
502          */
503         if (DatabaseHasActiveBackends(db_id, false))
504                 ereport(ERROR,
505                                 (errcode(ERRCODE_OBJECT_IN_USE),
506                            errmsg("database \"%s\" is being accessed by other users",
507                                           dbname)));
508
509         /*
510          * Find the database's tuple by OID (should be unique).
511          */
512         ScanKeyEntryInitialize(&key, 0, ObjectIdAttributeNumber,
513                                                    F_OIDEQ, ObjectIdGetDatum(db_id));
514
515         pgdbscan = systable_beginscan(pgdbrel, DatabaseOidIndex, true, SnapshotNow, 1, &key);
516
517         tup = systable_getnext(pgdbscan);
518         if (!HeapTupleIsValid(tup))
519         {
520                 /*
521                  * This error should never come up since the existence of the
522                  * database is checked earlier
523                  */
524                 elog(ERROR, "database \"%s\" doesn't exist despite earlier reports to the contrary",
525                          dbname);
526         }
527
528         /* Remove the database's tuple from pg_database */
529         simple_heap_delete(pgdbrel, &tup->t_self);
530
531         systable_endscan(pgdbscan);
532
533         /*
534          * Delete any comments associated with the database
535          *
536          * NOTE: this is probably dead code since any such comments should have
537          * been in that database, not mine.
538          */
539         DeleteComments(db_id, RelationGetRelid(pgdbrel), 0);
540
541         /*
542          * Close pg_database, but keep exclusive lock till commit to ensure
543          * that any new backend scanning pg_database will see the tuple dead.
544          */
545         heap_close(pgdbrel, NoLock);
546
547         /*
548          * Drop pages for this database that are in the shared buffer cache.
549          * This is important to ensure that no remaining backend tries to
550          * write out a dirty buffer to the dead database later...
551          */
552         DropBuffers(db_id);
553
554         /*
555          * Also, clean out any entries in the shared free space map.
556          */
557         FreeSpaceMapForgetDatabase(db_id);
558
559         /*
560          * Remove the database's subdirectory and everything in it.
561          */
562         remove_dbdirs(nominal_loc, alt_loc);
563
564         /*
565          * Force dirty buffers out to disk, so that newly-connecting backends
566          * will see the database tuple marked dead in pg_database right away.
567          * (They'll see an uncommitted deletion, but they don't care; see
568          * GetRawDatabaseInfo.)
569          */
570         BufferSync();
571 }
572
573
574 /*
575  * Rename database
576  */
577 void
578 RenameDatabase(const char *oldname, const char *newname)
579 {
580         HeapTuple       tup,
581                                 newtup;
582         Relation        rel;
583         SysScanDesc scan,
584                                 scan2;
585         ScanKeyData key,
586                                 key2;
587
588         /*
589          * Obtain AccessExclusiveLock so that no new session gets started
590          * while the rename is in progress.
591          */
592         rel = heap_openr(DatabaseRelationName, AccessExclusiveLock);
593
594         ScanKeyEntryInitialize(&key, 0, Anum_pg_database_datname,
595                                                    F_NAMEEQ, NameGetDatum(oldname));
596         scan = systable_beginscan(rel, DatabaseNameIndex, true, SnapshotNow, 1, &key);
597
598         tup = systable_getnext(scan);
599         if (!HeapTupleIsValid(tup))
600                 ereport(ERROR,
601                                 (errcode(ERRCODE_UNDEFINED_DATABASE),
602                                  errmsg("database \"%s\" does not exist", oldname)));
603
604         /*
605          * XXX Client applications probably store the current database
606          * somewhere, so renaming it could cause confusion.  On the other
607          * hand, there may not be an actual problem besides a little
608          * confusion, so think about this and decide.
609          */
610         if (HeapTupleGetOid(tup) == MyDatabaseId)
611                 ereport(ERROR,
612                                 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
613                                  errmsg("current database may not be renamed")));
614
615         /*
616          * Make sure the database does not have active sessions.  Might not be
617          * necessary, but it's consistent with other database operations.
618          */
619         if (DatabaseHasActiveBackends(HeapTupleGetOid(tup), false))
620                 ereport(ERROR,
621                                 (errcode(ERRCODE_OBJECT_IN_USE),
622                            errmsg("database \"%s\" is being accessed by other users",
623                                           oldname)));
624
625         /* make sure the new name doesn't exist */
626         ScanKeyEntryInitialize(&key2, 0, Anum_pg_database_datname,
627                                                    F_NAMEEQ, NameGetDatum(newname));
628         scan2 = systable_beginscan(rel, DatabaseNameIndex, true, SnapshotNow, 1, &key2);
629         if (HeapTupleIsValid(systable_getnext(scan2)))
630                 ereport(ERROR,
631                                 (errcode(ERRCODE_DUPLICATE_DATABASE),
632                                  errmsg("database \"%s\" already exists", newname)));
633         systable_endscan(scan2);
634
635         /* must be owner */
636         if (!pg_database_ownercheck(HeapTupleGetOid(tup), GetUserId()))
637                 aclcheck_error(ACLCHECK_NOT_OWNER, ACL_KIND_DATABASE,
638                                            oldname);
639
640         /* must have createdb */
641         if (!have_createdb_privilege())
642                 ereport(ERROR,
643                                 (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
644                                  errmsg("permission denied to rename database")));
645
646         /* rename */
647         newtup = heap_copytuple(tup);
648         namestrcpy(&(((Form_pg_database) GETSTRUCT(newtup))->datname), newname);
649         simple_heap_update(rel, &tup->t_self, newtup);
650         CatalogUpdateIndexes(rel, newtup);
651
652         systable_endscan(scan);
653         heap_close(rel, NoLock);
654
655         /*
656          * Force dirty buffers out to disk, so that newly-connecting backends
657          * will see the renamed database in pg_database right away.  (They'll
658          * see an uncommitted tuple, but they don't care; see
659          * GetRawDatabaseInfo.)
660          */
661         BufferSync();
662 }
663
664
665 /*
666  * ALTER DATABASE name SET ...
667  */
668 void
669 AlterDatabaseSet(AlterDatabaseSetStmt *stmt)
670 {
671         char       *valuestr;
672         HeapTuple       tuple,
673                                 newtuple;
674         Relation        rel;
675         ScanKeyData scankey;
676         SysScanDesc scan;
677         Datum           repl_val[Natts_pg_database];
678         char            repl_null[Natts_pg_database];
679         char            repl_repl[Natts_pg_database];
680
681         valuestr = flatten_set_variable_args(stmt->variable, stmt->value);
682
683         rel = heap_openr(DatabaseRelationName, RowExclusiveLock);
684         ScanKeyEntryInitialize(&scankey, 0, Anum_pg_database_datname,
685                                                    F_NAMEEQ, NameGetDatum(stmt->dbname));
686         scan = systable_beginscan(rel, DatabaseNameIndex, true, SnapshotNow, 1, &scankey);
687         tuple = systable_getnext(scan);
688         if (!HeapTupleIsValid(tuple))
689                 ereport(ERROR,
690                                 (errcode(ERRCODE_UNDEFINED_DATABASE),
691                                  errmsg("database \"%s\" does not exist", stmt->dbname)));
692
693         if (!(superuser()
694                 || ((Form_pg_database) GETSTRUCT(tuple))->datdba == GetUserId()))
695                 aclcheck_error(ACLCHECK_NOT_OWNER, ACL_KIND_DATABASE,
696                                            stmt->dbname);
697
698         MemSet(repl_repl, ' ', sizeof(repl_repl));
699         repl_repl[Anum_pg_database_datconfig - 1] = 'r';
700
701         if (strcmp(stmt->variable, "all") == 0 && valuestr == NULL)
702         {
703                 /* RESET ALL */
704                 repl_null[Anum_pg_database_datconfig - 1] = 'n';
705                 repl_val[Anum_pg_database_datconfig - 1] = (Datum) 0;
706         }
707         else
708         {
709                 Datum           datum;
710                 bool            isnull;
711                 ArrayType  *a;
712
713                 repl_null[Anum_pg_database_datconfig - 1] = ' ';
714
715                 datum = heap_getattr(tuple, Anum_pg_database_datconfig,
716                                                          RelationGetDescr(rel), &isnull);
717
718                 a = isnull ? ((ArrayType *) NULL) : DatumGetArrayTypeP(datum);
719
720                 if (valuestr)
721                         a = GUCArrayAdd(a, stmt->variable, valuestr);
722                 else
723                         a = GUCArrayDelete(a, stmt->variable);
724
725                 if (a)
726                         repl_val[Anum_pg_database_datconfig - 1] = PointerGetDatum(a);
727                 else
728                         repl_null[Anum_pg_database_datconfig - 1] = 'n';
729         }
730
731         newtuple = heap_modifytuple(tuple, rel, repl_val, repl_null, repl_repl);
732         simple_heap_update(rel, &tuple->t_self, newtuple);
733
734         /* Update indexes */
735         CatalogUpdateIndexes(rel, newtuple);
736
737         systable_endscan(scan);
738         heap_close(rel, RowExclusiveLock);
739 }
740
741
742
743 /*
744  * Helper functions
745  */
746
747 static bool
748 get_db_info(const char *name, Oid *dbIdP, int4 *ownerIdP,
749                         int *encodingP, bool *dbIsTemplateP, Oid *dbLastSysOidP,
750                         TransactionId *dbVacuumXidP, TransactionId *dbFrozenXidP,
751                         char *dbpath)
752 {
753         Relation        relation;
754         ScanKeyData scanKey;
755         SysScanDesc scan;
756         HeapTuple       tuple;
757         bool            gottuple;
758
759         AssertArg(name);
760
761         /* Caller may wish to grab a better lock on pg_database beforehand... */
762         relation = heap_openr(DatabaseRelationName, AccessShareLock);
763
764         ScanKeyEntryInitialize(&scanKey, 0, Anum_pg_database_datname,
765                                                    F_NAMEEQ, NameGetDatum(name));
766
767         scan = systable_beginscan(relation, DatabaseNameIndex, true, SnapshotNow, 1, &scanKey);
768
769         tuple = systable_getnext(scan);
770
771         gottuple = HeapTupleIsValid(tuple);
772         if (gottuple)
773         {
774                 Form_pg_database dbform = (Form_pg_database) GETSTRUCT(tuple);
775
776                 /* oid of the database */
777                 if (dbIdP)
778                         *dbIdP = HeapTupleGetOid(tuple);
779                 /* sysid of the owner */
780                 if (ownerIdP)
781                         *ownerIdP = dbform->datdba;
782                 /* character encoding */
783                 if (encodingP)
784                         *encodingP = dbform->encoding;
785                 /* allowed as template? */
786                 if (dbIsTemplateP)
787                         *dbIsTemplateP = dbform->datistemplate;
788                 /* last system OID used in database */
789                 if (dbLastSysOidP)
790                         *dbLastSysOidP = dbform->datlastsysoid;
791                 /* limit of vacuumed XIDs */
792                 if (dbVacuumXidP)
793                         *dbVacuumXidP = dbform->datvacuumxid;
794                 /* limit of frozen XIDs */
795                 if (dbFrozenXidP)
796                         *dbFrozenXidP = dbform->datfrozenxid;
797                 /* database path (as registered in pg_database) */
798                 if (dbpath)
799                 {
800                         Datum           datum;
801                         bool            isnull;
802
803                         datum = heap_getattr(tuple,
804                                                                  Anum_pg_database_datpath,
805                                                                  RelationGetDescr(relation),
806                                                                  &isnull);
807                         if (!isnull)
808                         {
809                                 text       *pathtext = DatumGetTextP(datum);
810                                 int                     pathlen = VARSIZE(pathtext) - VARHDRSZ;
811
812                                 Assert(pathlen >= 0 && pathlen < MAXPGPATH);
813                                 strncpy(dbpath, VARDATA(pathtext), pathlen);
814                                 *(dbpath + pathlen) = '\0';
815                         }
816                         else
817                                 strcpy(dbpath, "");
818                 }
819         }
820
821         systable_endscan(scan);
822         heap_close(relation, AccessShareLock);
823
824         return gottuple;
825 }
826
827 static bool
828 have_createdb_privilege(void)
829 {
830         HeapTuple       utup;
831         bool            retval;
832
833         utup = SearchSysCache(SHADOWSYSID,
834                                                   Int32GetDatum(GetUserId()),
835                                                   0, 0, 0);
836
837         if (!HeapTupleIsValid(utup))
838                 retval = false;
839         else
840                 retval = ((Form_pg_shadow) GETSTRUCT(utup))->usecreatedb;
841
842         ReleaseSysCache(utup);
843
844         return retval;
845 }
846
847
848 static char *
849 resolve_alt_dbpath(const char *dbpath, Oid dboid)
850 {
851         const char *prefix;
852         char       *ret;
853         size_t          len;
854
855         if (dbpath == NULL || dbpath[0] == '\0')
856                 return NULL;
857
858         if (first_path_separator(dbpath))
859         {
860                 if (!is_absolute_path(dbpath))
861                         ereport(ERROR,
862                                         (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
863                                          errmsg("relative paths are not allowed as database locations")));
864 #ifndef ALLOW_ABSOLUTE_DBPATHS
865                 ereport(ERROR,
866                                 (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
867                 errmsg("absolute paths are not allowed as database locations")));
868 #endif
869                 prefix = dbpath;
870         }
871         else
872         {
873                 /* must be environment variable */
874                 char       *var = getenv(dbpath);
875
876                 if (!var)
877                         ereport(ERROR,
878                                         (errcode(ERRCODE_UNDEFINED_OBJECT),
879                            errmsg("postmaster environment variable \"%s\" not found",
880                                           dbpath)));
881                 if (!is_absolute_path(var))
882                         ereport(ERROR,
883                                         (errcode(ERRCODE_INVALID_NAME),
884                                          errmsg("postmaster environment variable \"%s\" must be absolute path",
885                                                         dbpath)));
886                 prefix = var;
887         }
888
889         len = strlen(prefix) + 6 + sizeof(Oid) * 8 + 1;
890         if (len >= MAXPGPATH - 100)
891                 ereport(ERROR,
892                                 (errcode(ERRCODE_INVALID_NAME),
893                                  errmsg("alternate path is too long")));
894
895         ret = palloc(len);
896         snprintf(ret, len, "%s/base/%u", prefix, dboid);
897
898         return ret;
899 }
900
901
902 static bool
903 remove_dbdirs(const char *nominal_loc, const char *alt_loc)
904 {
905         const char *target_dir;
906         char            buf[MAXPGPATH + 100];
907         bool            success = true;
908
909         target_dir = alt_loc ? alt_loc : nominal_loc;
910
911         /*
912          * Close virtual file descriptors so the kernel has more available for
913          * the system() call below.
914          */
915         closeAllVfds();
916
917         if (alt_loc)
918         {
919                 /* remove symlink */
920                 if (unlink(nominal_loc) != 0)
921                 {
922                         ereport(WARNING,
923                                         (errcode_for_file_access(),
924                                          errmsg("could not remove \"%s\": %m", nominal_loc)));
925                         success = false;
926                 }
927         }
928
929 #ifndef WIN32
930         snprintf(buf, sizeof(buf), "rm -rf '%s'", target_dir);
931 #else
932         snprintf(buf, sizeof(buf), "rmdir /s /q \"%s\"", target_dir);
933 #endif
934
935         if (system(buf) != 0)
936         {
937                 ereport(WARNING,
938                                 (errcode_for_file_access(),
939                                  errmsg("could not remove database directory \"%s\": %m",
940                                                 target_dir)));
941                 success = false;
942         }
943
944         return success;
945 }
946
947
948 /*
949  * get_database_oid - given a database name, look up the OID
950  *
951  * Returns InvalidOid if database name not found.
952  *
953  * This is not actually used in this file, but is exported for use elsewhere.
954  */
955 Oid
956 get_database_oid(const char *dbname)
957 {
958         Relation        pg_database;
959         ScanKeyData entry[1];
960         SysScanDesc scan;
961         HeapTuple       dbtuple;
962         Oid                     oid;
963
964         /* There's no syscache for pg_database, so must look the hard way */
965         pg_database = heap_openr(DatabaseRelationName, AccessShareLock);
966         ScanKeyEntryInitialize(&entry[0], 0x0,
967                                                    Anum_pg_database_datname, F_NAMEEQ,
968                                                    CStringGetDatum(dbname));
969         scan = systable_beginscan(pg_database, DatabaseNameIndex, true, SnapshotNow, 1, entry);
970
971         dbtuple = systable_getnext(scan);
972
973         /* We assume that there can be at most one matching tuple */
974         if (HeapTupleIsValid(dbtuple))
975                 oid = HeapTupleGetOid(dbtuple);
976         else
977                 oid = InvalidOid;
978
979         systable_endscan(scan);
980         heap_close(pg_database, AccessShareLock);
981
982         return oid;
983 }
984
985
986 /*
987  * get_database_name - given a database OID, look up the name
988  *
989  * Returns InvalidOid if database name not found.
990  *
991  * This is not actually used in this file, but is exported for use elsewhere.
992  */
993 char *
994 get_database_name(Oid dbid)
995 {
996         Relation        pg_database;
997         ScanKeyData entry[1];
998         SysScanDesc scan;
999         HeapTuple       dbtuple;
1000         char       *result;
1001
1002         /* There's no syscache for pg_database, so must look the hard way */
1003         pg_database = heap_openr(DatabaseRelationName, AccessShareLock);
1004         ScanKeyEntryInitialize(&entry[0], 0x0,
1005                                                    ObjectIdAttributeNumber, F_OIDEQ,
1006                                                    ObjectIdGetDatum(dbid));
1007         scan = systable_beginscan(pg_database, DatabaseOidIndex, true, SnapshotNow, 1, entry);
1008
1009         dbtuple = systable_getnext(scan);
1010
1011         /* We assume that there can be at most one matching tuple */
1012         if (HeapTupleIsValid(dbtuple))
1013                 result = pstrdup(NameStr(((Form_pg_database) GETSTRUCT(dbtuple))->datname));
1014         else
1015                 result = NULL;
1016
1017         systable_endscan(scan);
1018         heap_close(pg_database, AccessShareLock);
1019
1020         return result;
1021 }