1 /*-------------------------------------------------------------------------
4 * Database management commands (create/drop database).
7 * Portions Copyright (c) 1996-2002, PostgreSQL Global Development Group
8 * Portions Copyright (c) 1994, Regents of the University of California
12 * $Header: /cvsroot/pgsql/src/backend/commands/dbcommands.c,v 1.105 2002/09/04 20:31:15 momjian Exp $
14 *-------------------------------------------------------------------------
23 #include "access/heapam.h"
24 #include "catalog/catname.h"
25 #include "catalog/catalog.h"
26 #include "catalog/pg_database.h"
27 #include "catalog/pg_shadow.h"
28 #include "catalog/indexing.h"
29 #include "commands/comment.h"
30 #include "commands/dbcommands.h"
31 #include "miscadmin.h"
32 #include "storage/freespace.h"
33 #include "storage/sinval.h"
34 #include "utils/array.h"
35 #include "utils/builtins.h"
36 #include "utils/fmgroids.h"
37 #include "utils/guc.h"
38 #include "utils/lsyscache.h"
39 #include "utils/syscache.h"
41 #include "mb/pg_wchar.h" /* encoding check */
44 /* non-export function prototypes */
45 static bool get_db_info(const char *name, Oid *dbIdP, int4 *ownerIdP,
46 int *encodingP, bool *dbIsTemplateP, Oid *dbLastSysOidP,
47 TransactionId *dbVacuumXidP, TransactionId *dbFrozenXidP,
49 static bool have_createdb_privilege(void);
50 static char *resolve_alt_dbpath(const char *dbpath, Oid dboid);
51 static bool remove_dbdirs(const char *real_loc, const char *altloc);
58 createdb(const CreatedbStmt *stmt)
63 char src_loc[MAXPGPATH];
64 char buf[2 * MAXPGPATH + 100];
70 TransactionId src_vacuumxid;
71 TransactionId src_frozenxid;
72 char src_dbpath[MAXPGPATH];
73 Relation pg_database_rel;
75 TupleDesc pg_database_dsc;
76 Datum new_record[Natts_pg_database];
77 char new_record_nulls[Natts_pg_database];
81 DefElem *downer = NULL;
82 DefElem *dpath = NULL;
83 DefElem *dtemplate = NULL;
84 DefElem *dencoding = NULL;
85 char *dbname = stmt->dbname;
88 char *dbtemplate = NULL;
91 /* Extract options from the statement node tree */
92 foreach(option, stmt->options)
94 DefElem *defel = (DefElem *) lfirst(option);
96 if (strcmp(defel->defname, "owner") == 0)
99 elog(ERROR, "CREATE DATABASE: conflicting options");
102 else if (strcmp(defel->defname, "location") == 0)
105 elog(ERROR, "CREATE DATABASE: conflicting options");
108 else if (strcmp(defel->defname, "template") == 0)
111 elog(ERROR, "CREATE DATABASE: conflicting options");
114 else if (strcmp(defel->defname, "encoding") == 0)
117 elog(ERROR, "CREATE DATABASE: conflicting options");
121 elog(ERROR, "CREATE DATABASE: option \"%s\" not recognized",
126 dbowner = strVal(downer->arg);
128 dbpath = strVal(dpath->arg);
130 dbtemplate = strVal(dtemplate->arg);
132 encoding = intVal(dencoding->arg);
134 /* obtain sysid of proposed owner */
136 datdba = get_usesysid(dbowner); /* will elog if no such user */
138 datdba = GetUserId();
140 if (datdba == (int32) GetUserId())
142 /* creating database for self: can be superuser or createdb */
143 if (!superuser() && !have_createdb_privilege())
144 elog(ERROR, "CREATE DATABASE: permission denied");
148 /* creating database for someone else: must be superuser */
149 /* note that the someone else need not have any permissions */
151 elog(ERROR, "CREATE DATABASE: permission denied");
154 /* don't call this in a transaction block */
155 if (IsTransactionBlock())
156 elog(ERROR, "CREATE DATABASE: may not be called in a transaction block");
159 * Check for db name conflict. There is a race condition here, since
160 * another backend could create the same DB name before we commit.
161 * However, holding an exclusive lock on pg_database for the whole
162 * time we are copying the source database doesn't seem like a good
163 * idea, so accept possibility of race to create. We will check again
164 * after we grab the exclusive lock.
166 if (get_db_info(dbname, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL))
167 elog(ERROR, "CREATE DATABASE: database \"%s\" already exists", dbname);
170 * Lookup database (template) to be cloned.
173 dbtemplate = "template1"; /* Default template database name */
175 if (!get_db_info(dbtemplate, &src_dboid, &src_owner, &src_encoding,
176 &src_istemplate, &src_lastsysoid,
177 &src_vacuumxid, &src_frozenxid,
179 elog(ERROR, "CREATE DATABASE: template \"%s\" does not exist",
183 * Permission check: to copy a DB that's not marked datistemplate, you
184 * must be superuser or the owner thereof.
188 if (!superuser() && GetUserId() != src_owner)
189 elog(ERROR, "CREATE DATABASE: permission to copy \"%s\" denied",
194 * Determine physical path of source database
196 alt_loc = resolve_alt_dbpath(src_dbpath, src_dboid);
198 alt_loc = GetDatabasePath(src_dboid);
199 strcpy(src_loc, alt_loc);
202 * The source DB can't have any active backends, except this one
203 * (exception is to allow CREATE DB while connected to template1).
204 * Otherwise we might copy inconsistent data. This check is not
205 * bulletproof, since someone might connect while we are copying...
207 if (DatabaseHasActiveBackends(src_dboid, true))
208 elog(ERROR, "CREATE DATABASE: source database \"%s\" is being accessed by other users", dbtemplate);
210 /* If encoding is defaulted, use source's encoding */
212 encoding = src_encoding;
214 /* Some encodings are client only */
215 if (!PG_VALID_BE_ENCODING(encoding))
216 elog(ERROR, "CREATE DATABASE: invalid backend encoding");
219 * Preassign OID for pg_database tuple, so that we can compute db
225 * Compute nominal location (where we will try to access the
226 * database), and resolve alternate physical location if one is
229 * If an alternate location is specified but is the same as the normal
230 * path, just drop the alternate-location spec (this seems friendlier
231 * than erroring out). We must test this case to avoid creating a
232 * circular symlink below.
234 nominal_loc = GetDatabasePath(dboid);
235 alt_loc = resolve_alt_dbpath(dbpath, dboid);
237 if (alt_loc && strcmp(alt_loc, nominal_loc) == 0)
243 if (strchr(nominal_loc, '\''))
244 elog(ERROR, "database path may not contain single quotes");
245 if (alt_loc && strchr(alt_loc, '\''))
246 elog(ERROR, "database path may not contain single quotes");
247 if (strchr(src_loc, '\''))
248 elog(ERROR, "database path may not contain single quotes");
249 /* ... otherwise we'd be open to shell exploits below */
252 * Force dirty buffers out to disk, to ensure source database is
253 * up-to-date for the copy. (We really only need to flush buffers for
254 * the source database...)
259 * Close virtual file descriptors so the kernel has more available for
260 * the mkdir() and system() calls below.
265 * Check we can create the target directory --- but then remove it
266 * because we rely on cp(1) to create it for real.
268 target_dir = alt_loc ? alt_loc : nominal_loc;
270 if (mkdir(target_dir, S_IRWXU) != 0)
271 elog(ERROR, "CREATE DATABASE: unable to create database directory '%s': %m",
273 if (rmdir(target_dir) != 0)
274 elog(ERROR, "CREATE DATABASE: unable to remove temp directory '%s': %m",
277 /* Make the symlink, if needed */
280 if (symlink(alt_loc, nominal_loc) != 0)
281 elog(ERROR, "CREATE DATABASE: could not link '%s' to '%s': %m",
282 nominal_loc, alt_loc);
285 /* Copy the template database to the new location */
286 snprintf(buf, sizeof(buf), "cp -r '%s' '%s'", src_loc, target_dir);
288 if (system(buf) != 0)
290 if (remove_dbdirs(nominal_loc, alt_loc))
291 elog(ERROR, "CREATE DATABASE: could not initialize database directory");
293 elog(ERROR, "CREATE DATABASE: could not initialize database directory; delete failed as well");
297 * Now OK to grab exclusive lock on pg_database.
299 pg_database_rel = heap_openr(DatabaseRelationName, AccessExclusiveLock);
301 /* Check to see if someone else created same DB name meanwhile. */
302 if (get_db_info(dbname, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL))
304 /* Don't hold lock while doing recursive remove */
305 heap_close(pg_database_rel, AccessExclusiveLock);
306 remove_dbdirs(nominal_loc, alt_loc);
307 elog(ERROR, "CREATE DATABASE: database \"%s\" already exists", dbname);
311 * Insert a new tuple into pg_database
313 pg_database_dsc = RelationGetDescr(pg_database_rel);
316 MemSet(new_record, 0, sizeof(new_record));
317 MemSet(new_record_nulls, ' ', sizeof(new_record_nulls));
319 new_record[Anum_pg_database_datname - 1] =
320 DirectFunctionCall1(namein, CStringGetDatum(dbname));
321 new_record[Anum_pg_database_datdba - 1] = Int32GetDatum(datdba);
322 new_record[Anum_pg_database_encoding - 1] = Int32GetDatum(encoding);
323 new_record[Anum_pg_database_datistemplate - 1] = BoolGetDatum(false);
324 new_record[Anum_pg_database_datallowconn - 1] = BoolGetDatum(true);
325 new_record[Anum_pg_database_datlastsysoid - 1] = ObjectIdGetDatum(src_lastsysoid);
326 new_record[Anum_pg_database_datvacuumxid - 1] = TransactionIdGetDatum(src_vacuumxid);
327 new_record[Anum_pg_database_datfrozenxid - 1] = TransactionIdGetDatum(src_frozenxid);
328 /* do not set datpath to null, GetRawDatabaseInfo won't cope */
329 new_record[Anum_pg_database_datpath - 1] =
330 DirectFunctionCall1(textin, CStringGetDatum(dbpath ? dbpath : ""));
333 * We deliberately set datconfig and datacl to defaults (NULL), rather
334 * than copying them from the template database. Copying datacl would
335 * be a bad idea when the owner is not the same as the template's
336 * owner. It's more debatable whether datconfig should be copied.
338 new_record_nulls[Anum_pg_database_datconfig - 1] = 'n';
339 new_record_nulls[Anum_pg_database_datacl - 1] = 'n';
341 tuple = heap_formtuple(pg_database_dsc, new_record, new_record_nulls);
343 HeapTupleSetOid(tuple, dboid); /* override heap_insert's OID
346 simple_heap_insert(pg_database_rel, tuple);
349 CatalogUpdateIndexes(pg_database_rel, tuple);
351 /* Close pg_database, but keep lock till commit */
352 heap_close(pg_database_rel, NoLock);
355 * Force dirty buffers out to disk, so that newly-connecting backends
356 * will see the new database in pg_database right away. (They'll see
357 * an uncommitted tuple, but they don't care; see GetRawDatabaseInfo.)
367 dropdb(const char *dbname)
374 char dbpath[MAXPGPATH];
376 HeapScanDesc pgdbscan;
382 if (strcmp(dbname, DatabaseName) == 0)
383 elog(ERROR, "DROP DATABASE: cannot be executed on the currently open database");
385 if (IsTransactionBlock())
386 elog(ERROR, "DROP DATABASE: may not be called in a transaction block");
389 * Obtain exclusive lock on pg_database. We need this to ensure that
390 * no new backend starts up in the target database while we are
391 * deleting it. (Actually, a new backend might still manage to start
392 * up, because it will read pg_database without any locking to
393 * discover the database's OID. But it will detect its error in
394 * ReverifyMyDatabase and shut down before any serious damage is done.
397 pgdbrel = heap_openr(DatabaseRelationName, AccessExclusiveLock);
399 if (!get_db_info(dbname, &db_id, &db_owner, NULL,
400 &db_istemplate, NULL, NULL, NULL, dbpath))
401 elog(ERROR, "DROP DATABASE: database \"%s\" does not exist", dbname);
403 if (GetUserId() != db_owner && !superuser())
404 elog(ERROR, "DROP DATABASE: permission denied");
407 * Disallow dropping a DB that is marked istemplate. This is just to
408 * prevent people from accidentally dropping template0 or template1;
409 * they can do so if they're really determined ...
412 elog(ERROR, "DROP DATABASE: database is marked as a template");
414 nominal_loc = GetDatabasePath(db_id);
415 alt_loc = resolve_alt_dbpath(dbpath, db_id);
418 * Check for active backends in the target database.
420 if (DatabaseHasActiveBackends(db_id, false))
421 elog(ERROR, "DROP DATABASE: database \"%s\" is being accessed by other users", dbname);
424 * Find the database's tuple by OID (should be unique).
426 ScanKeyEntryInitialize(&key, 0, ObjectIdAttributeNumber,
427 F_OIDEQ, ObjectIdGetDatum(db_id));
429 pgdbscan = heap_beginscan(pgdbrel, SnapshotNow, 1, &key);
431 tup = heap_getnext(pgdbscan, ForwardScanDirection);
432 if (!HeapTupleIsValid(tup))
435 * This error should never come up since the existence of the
436 * database is checked earlier
438 elog(ERROR, "DROP DATABASE: Database \"%s\" doesn't exist despite earlier reports to the contrary",
442 /* Remove the database's tuple from pg_database */
443 simple_heap_delete(pgdbrel, &tup->t_self);
445 heap_endscan(pgdbscan);
448 * Delete any comments associated with the database
450 * NOTE: this is probably dead code since any such comments should have
451 * been in that database, not mine.
453 DeleteComments(db_id, RelationGetRelid(pgdbrel), 0);
456 * Close pg_database, but keep exclusive lock till commit to ensure
457 * that any new backend scanning pg_database will see the tuple dead.
459 heap_close(pgdbrel, NoLock);
462 * Drop pages for this database that are in the shared buffer cache.
463 * This is important to ensure that no remaining backend tries to
464 * write out a dirty buffer to the dead database later...
469 * Also, clean out any entries in the shared free space map.
471 FreeSpaceMapForgetDatabase(db_id);
474 * Remove the database's subdirectory and everything in it.
476 remove_dbdirs(nominal_loc, alt_loc);
479 * Force dirty buffers out to disk, so that newly-connecting backends
480 * will see the database tuple marked dead in pg_database right away.
481 * (They'll see an uncommitted deletion, but they don't care; see
482 * GetRawDatabaseInfo.)
490 * ALTER DATABASE name SET ...
493 AlterDatabaseSet(AlterDatabaseSetStmt *stmt)
501 Datum repl_val[Natts_pg_database];
502 char repl_null[Natts_pg_database];
503 char repl_repl[Natts_pg_database];
505 valuestr = flatten_set_variable_args(stmt->variable, stmt->value);
507 rel = heap_openr(DatabaseRelationName, RowExclusiveLock);
508 ScanKeyEntryInitialize(&scankey, 0, Anum_pg_database_datname,
509 F_NAMEEQ, NameGetDatum(stmt->dbname));
510 scan = heap_beginscan(rel, SnapshotNow, 1, &scankey);
511 tuple = heap_getnext(scan, ForwardScanDirection);
512 if (!HeapTupleIsValid(tuple))
513 elog(ERROR, "database \"%s\" does not exist", stmt->dbname);
516 || ((Form_pg_database) GETSTRUCT(tuple))->datdba == GetUserId()))
517 elog(ERROR, "permission denied");
519 MemSet(repl_repl, ' ', sizeof(repl_repl));
520 repl_repl[Anum_pg_database_datconfig - 1] = 'r';
522 if (strcmp(stmt->variable, "all") == 0 && valuestr == NULL)
525 repl_null[Anum_pg_database_datconfig - 1] = 'n';
526 repl_val[Anum_pg_database_datconfig - 1] = (Datum) 0;
534 repl_null[Anum_pg_database_datconfig - 1] = ' ';
536 datum = heap_getattr(tuple, Anum_pg_database_datconfig,
537 RelationGetDescr(rel), &isnull);
539 a = isnull ? ((ArrayType *) NULL) : DatumGetArrayTypeP(datum);
542 a = GUCArrayAdd(a, stmt->variable, valuestr);
544 a = GUCArrayDelete(a, stmt->variable);
546 repl_val[Anum_pg_database_datconfig - 1] = PointerGetDatum(a);
549 newtuple = heap_modifytuple(tuple, rel, repl_val, repl_null, repl_repl);
550 simple_heap_update(rel, &tuple->t_self, newtuple);
553 CatalogUpdateIndexes(rel, newtuple);
556 heap_close(rel, RowExclusiveLock);
566 get_db_info(const char *name, Oid *dbIdP, int4 *ownerIdP,
567 int *encodingP, bool *dbIsTemplateP, Oid *dbLastSysOidP,
568 TransactionId *dbVacuumXidP, TransactionId *dbFrozenXidP,
579 /* Caller may wish to grab a better lock on pg_database beforehand... */
580 relation = heap_openr(DatabaseRelationName, AccessShareLock);
582 ScanKeyEntryInitialize(&scanKey, 0, Anum_pg_database_datname,
583 F_NAMEEQ, NameGetDatum(name));
585 scan = heap_beginscan(relation, SnapshotNow, 1, &scanKey);
587 tuple = heap_getnext(scan, ForwardScanDirection);
589 gottuple = HeapTupleIsValid(tuple);
592 Form_pg_database dbform = (Form_pg_database) GETSTRUCT(tuple);
594 /* oid of the database */
596 *dbIdP = HeapTupleGetOid(tuple);
597 /* sysid of the owner */
599 *ownerIdP = dbform->datdba;
600 /* character encoding */
602 *encodingP = dbform->encoding;
603 /* allowed as template? */
605 *dbIsTemplateP = dbform->datistemplate;
606 /* last system OID used in database */
608 *dbLastSysOidP = dbform->datlastsysoid;
609 /* limit of vacuumed XIDs */
611 *dbVacuumXidP = dbform->datvacuumxid;
612 /* limit of frozen XIDs */
614 *dbFrozenXidP = dbform->datfrozenxid;
615 /* database path (as registered in pg_database) */
621 datum = heap_getattr(tuple,
622 Anum_pg_database_datpath,
623 RelationGetDescr(relation),
627 text *pathtext = DatumGetTextP(datum);
628 int pathlen = VARSIZE(pathtext) - VARHDRSZ;
630 Assert(pathlen >= 0 && pathlen < MAXPGPATH);
631 strncpy(dbpath, VARDATA(pathtext), pathlen);
632 *(dbpath + pathlen) = '\0';
640 heap_close(relation, AccessShareLock);
646 have_createdb_privilege(void)
651 utup = SearchSysCache(SHADOWSYSID,
652 ObjectIdGetDatum(GetUserId()),
655 if (!HeapTupleIsValid(utup))
658 retval = ((Form_pg_shadow) GETSTRUCT(utup))->usecreatedb;
660 ReleaseSysCache(utup);
667 resolve_alt_dbpath(const char *dbpath, Oid dboid)
673 if (dbpath == NULL || dbpath[0] == '\0')
676 if (strchr(dbpath, '/'))
678 if (dbpath[0] != '/')
679 elog(ERROR, "Relative paths are not allowed as database locations");
680 #ifndef ALLOW_ABSOLUTE_DBPATHS
681 elog(ERROR, "Absolute paths are not allowed as database locations");
687 /* must be environment variable */
688 char *var = getenv(dbpath);
691 elog(ERROR, "Postmaster environment variable '%s' not set", dbpath);
693 elog(ERROR, "Postmaster environment variable '%s' must be absolute path", dbpath);
697 len = strlen(prefix) + 6 + sizeof(Oid) * 8 + 1;
698 if (len >= MAXPGPATH - 100)
699 elog(ERROR, "Alternate path is too long");
702 snprintf(ret, len, "%s/base/%u", prefix, dboid);
709 remove_dbdirs(const char *nominal_loc, const char *alt_loc)
711 const char *target_dir;
712 char buf[MAXPGPATH + 100];
715 target_dir = alt_loc ? alt_loc : nominal_loc;
718 * Close virtual file descriptors so the kernel has more available for
719 * the system() call below.
726 if (unlink(nominal_loc) != 0)
728 elog(WARNING, "could not remove '%s': %m", nominal_loc);
733 snprintf(buf, sizeof(buf), "rm -rf '%s'", target_dir);
735 if (system(buf) != 0)
737 elog(WARNING, "database directory '%s' could not be removed",
747 * get_database_oid - given a database name, look up the OID
749 * Returns InvalidOid if database name not found.
751 * This is not actually used in this file, but is exported for use elsewhere.
754 get_database_oid(const char *dbname)
756 Relation pg_database;
757 ScanKeyData entry[1];
762 /* There's no syscache for pg_database, so must look the hard way */
763 pg_database = heap_openr(DatabaseRelationName, AccessShareLock);
764 ScanKeyEntryInitialize(&entry[0], 0x0,
765 Anum_pg_database_datname, F_NAMEEQ,
766 CStringGetDatum(dbname));
767 scan = heap_beginscan(pg_database, SnapshotNow, 1, entry);
769 dbtuple = heap_getnext(scan, ForwardScanDirection);
771 /* We assume that there can be at most one matching tuple */
772 if (HeapTupleIsValid(dbtuple))
773 oid = HeapTupleGetOid(dbtuple);
778 heap_close(pg_database, AccessShareLock);
784 * get_database_owner - given a database OID, fetch the owner's usesysid.
786 * Errors out if database not found.
788 * This is not actually used in this file, but is exported for use elsewhere.
791 get_database_owner(Oid dbid)
793 Relation pg_database;
794 ScanKeyData entry[1];
799 /* There's no syscache for pg_database, so must look the hard way */
800 pg_database = heap_openr(DatabaseRelationName, AccessShareLock);
801 ScanKeyEntryInitialize(&entry[0], 0x0,
802 ObjectIdAttributeNumber, F_OIDEQ,
803 ObjectIdGetDatum(dbid));
804 scan = heap_beginscan(pg_database, SnapshotNow, 1, entry);
806 dbtuple = heap_getnext(scan, ForwardScanDirection);
808 if (!HeapTupleIsValid(dbtuple))
809 elog(ERROR, "database %u does not exist", dbid);
811 dba = ((Form_pg_database) GETSTRUCT(dbtuple))->datdba;
814 heap_close(pg_database, AccessShareLock);
816 /* XXX some confusion about whether userids are OID or int4 ... */