1 /*-------------------------------------------------------------------------
4 * Database management commands (create/drop database).
6 * Note: database creation/destruction commands take ExclusiveLock on
7 * pg_database to ensure that no two proceed in parallel. We must use
8 * at least this level of locking to ensure that no two backends try to
9 * write the flat-file copy of pg_database at once. We avoid using
10 * AccessExclusiveLock since there's no need to lock out ordinary readers
13 * Portions Copyright (c) 1996-2005, PostgreSQL Global Development Group
14 * Portions Copyright (c) 1994, Regents of the University of California
18 * $PostgreSQL: pgsql/src/backend/commands/dbcommands.c,v 1.161 2005/06/25 22:47:29 tgl Exp $
20 *-------------------------------------------------------------------------
28 #include "access/genam.h"
29 #include "access/heapam.h"
30 #include "catalog/catalog.h"
31 #include "catalog/pg_database.h"
32 #include "catalog/pg_shadow.h"
33 #include "catalog/pg_tablespace.h"
34 #include "catalog/indexing.h"
35 #include "commands/comment.h"
36 #include "commands/dbcommands.h"
37 #include "commands/tablespace.h"
38 #include "mb/pg_wchar.h"
39 #include "miscadmin.h"
40 #include "postmaster/bgwriter.h"
41 #include "storage/fd.h"
42 #include "storage/freespace.h"
43 #include "storage/procarray.h"
44 #include "utils/acl.h"
45 #include "utils/array.h"
46 #include "utils/builtins.h"
47 #include "utils/flatfiles.h"
48 #include "utils/fmgroids.h"
49 #include "utils/guc.h"
50 #include "utils/lsyscache.h"
51 #include "utils/syscache.h"
54 /* non-export function prototypes */
55 static bool get_db_info(const char *name, Oid *dbIdP, int4 *ownerIdP,
56 int *encodingP, bool *dbIsTemplateP, bool *dbAllowConnP,
58 TransactionId *dbVacuumXidP, TransactionId *dbFrozenXidP,
60 static bool have_createdb_privilege(void);
61 static void remove_dbtablespaces(Oid db_id);
68 createdb(const CreatedbStmt *stmt)
78 TransactionId src_vacuumxid;
79 TransactionId src_frozenxid;
80 Oid src_deftablespace;
81 Oid dst_deftablespace;
82 Relation pg_database_rel;
84 TupleDesc pg_database_dsc;
85 Datum new_record[Natts_pg_database];
86 char new_record_nulls[Natts_pg_database];
90 DefElem *dtablespacename = NULL;
91 DefElem *downer = NULL;
92 DefElem *dtemplate = NULL;
93 DefElem *dencoding = NULL;
94 char *dbname = stmt->dbname;
96 const char *dbtemplate = NULL;
100 char buf[2 * MAXPGPATH + 100];
103 /* don't call this in a transaction block */
104 PreventTransactionChain((void *) stmt, "CREATE DATABASE");
106 /* Extract options from the statement node tree */
107 foreach(option, stmt->options)
109 DefElem *defel = (DefElem *) lfirst(option);
111 if (strcmp(defel->defname, "tablespace") == 0)
115 (errcode(ERRCODE_SYNTAX_ERROR),
116 errmsg("conflicting or redundant options")));
117 dtablespacename = defel;
119 else if (strcmp(defel->defname, "owner") == 0)
123 (errcode(ERRCODE_SYNTAX_ERROR),
124 errmsg("conflicting or redundant options")));
127 else if (strcmp(defel->defname, "template") == 0)
131 (errcode(ERRCODE_SYNTAX_ERROR),
132 errmsg("conflicting or redundant options")));
135 else if (strcmp(defel->defname, "encoding") == 0)
139 (errcode(ERRCODE_SYNTAX_ERROR),
140 errmsg("conflicting or redundant options")));
143 else if (strcmp(defel->defname, "location") == 0)
146 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
147 errmsg("LOCATION is not supported anymore"),
148 errhint("Consider using tablespaces instead.")));
151 elog(ERROR, "option \"%s\" not recognized",
155 if (downer && downer->arg)
156 dbowner = strVal(downer->arg);
157 if (dtemplate && dtemplate->arg)
158 dbtemplate = strVal(dtemplate->arg);
159 if (dencoding && dencoding->arg)
161 const char *encoding_name;
163 if (IsA(dencoding->arg, Integer))
165 encoding = intVal(dencoding->arg);
166 encoding_name = pg_encoding_to_char(encoding);
167 if (strcmp(encoding_name, "") == 0 ||
168 pg_valid_server_encoding(encoding_name) < 0)
170 (errcode(ERRCODE_UNDEFINED_OBJECT),
171 errmsg("%d is not a valid encoding code",
174 else if (IsA(dencoding->arg, String))
176 encoding_name = strVal(dencoding->arg);
177 if (pg_valid_server_encoding(encoding_name) < 0)
179 (errcode(ERRCODE_UNDEFINED_OBJECT),
180 errmsg("%s is not a valid encoding name",
182 encoding = pg_char_to_encoding(encoding_name);
185 elog(ERROR, "unrecognized node type: %d",
186 nodeTag(dencoding->arg));
189 /* obtain sysid of proposed owner */
191 datdba = get_usesysid(dbowner); /* will ereport if no such user */
193 datdba = GetUserId();
195 if (datdba == GetUserId())
197 /* creating database for self: can be superuser or createdb */
198 if (!superuser() && !have_createdb_privilege())
200 (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
201 errmsg("permission denied to create database")));
205 /* creating database for someone else: must be superuser */
206 /* note that the someone else need not have any permissions */
209 (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
210 errmsg("must be superuser to create database for another user")));
214 * Check for db name conflict. There is a race condition here, since
215 * another backend could create the same DB name before we commit.
216 * However, holding an exclusive lock on pg_database for the whole
217 * time we are copying the source database doesn't seem like a good
218 * idea, so accept possibility of race to create. We will check again
219 * after we grab the exclusive lock.
221 if (get_db_info(dbname, NULL, NULL, NULL,
222 NULL, NULL, NULL, NULL, NULL, NULL))
224 (errcode(ERRCODE_DUPLICATE_DATABASE),
225 errmsg("database \"%s\" already exists", dbname)));
228 * Lookup database (template) to be cloned.
231 dbtemplate = "template1"; /* Default template database name */
233 if (!get_db_info(dbtemplate, &src_dboid, &src_owner, &src_encoding,
234 &src_istemplate, &src_allowconn, &src_lastsysoid,
235 &src_vacuumxid, &src_frozenxid, &src_deftablespace))
237 (errcode(ERRCODE_UNDEFINED_DATABASE),
238 errmsg("template database \"%s\" does not exist", dbtemplate)));
241 * Permission check: to copy a DB that's not marked datistemplate, you
242 * must be superuser or the owner thereof.
246 if (!superuser() && GetUserId() != src_owner)
248 (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
249 errmsg("permission denied to copy database \"%s\"",
254 * The source DB can't have any active backends, except this one
255 * (exception is to allow CREATE DB while connected to template1).
256 * Otherwise we might copy inconsistent data. This check is not
257 * bulletproof, since someone might connect while we are copying...
259 if (DatabaseHasActiveBackends(src_dboid, true))
261 (errcode(ERRCODE_OBJECT_IN_USE),
262 errmsg("source database \"%s\" is being accessed by other users",
265 /* If encoding is defaulted, use source's encoding */
267 encoding = src_encoding;
269 /* Some encodings are client only */
270 if (!PG_VALID_BE_ENCODING(encoding))
272 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
273 errmsg("invalid server encoding %d", encoding)));
275 /* Resolve default tablespace for new database */
276 if (dtablespacename && dtablespacename->arg)
278 char *tablespacename;
281 tablespacename = strVal(dtablespacename->arg);
282 dst_deftablespace = get_tablespace_oid(tablespacename);
283 if (!OidIsValid(dst_deftablespace))
285 (errcode(ERRCODE_UNDEFINED_OBJECT),
286 errmsg("tablespace \"%s\" does not exist",
288 /* check permissions */
289 aclresult = pg_tablespace_aclcheck(dst_deftablespace, GetUserId(),
291 if (aclresult != ACLCHECK_OK)
292 aclcheck_error(aclresult, ACL_KIND_TABLESPACE,
296 * If we are trying to change the default tablespace of the template,
297 * we require that the template not have any files in the new default
298 * tablespace. This is necessary because otherwise the copied
299 * database would contain pg_class rows that refer to its default
300 * tablespace both explicitly (by OID) and implicitly (as zero), which
301 * would cause problems. For example another CREATE DATABASE using
302 * the copied database as template, and trying to change its default
303 * tablespace again, would yield outright incorrect results (it would
304 * improperly move tables to the new default tablespace that should
305 * stay in the same tablespace).
307 if (dst_deftablespace != src_deftablespace)
312 srcpath = GetDatabasePath(src_dboid, dst_deftablespace);
314 if (stat(srcpath, &st) == 0 &&
315 S_ISDIR(st.st_mode) &&
316 !directory_is_empty(srcpath))
318 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
319 errmsg("cannot assign new default tablespace \"%s\"",
321 errdetail("There is a conflict because database \"%s\" already has some tables in this tablespace.",
328 /* Use template database's default tablespace */
329 dst_deftablespace = src_deftablespace;
330 /* Note there is no additional permission check in this path */
334 * Normally we mark the new database with the same datvacuumxid and
335 * datfrozenxid as the source. However, if the source is not allowing
336 * connections then we assume it is fully frozen, and we can set the
337 * current transaction ID as the xid limits. This avoids immediately
338 * starting to generate warnings after cloning template0.
341 src_vacuumxid = src_frozenxid = GetCurrentTransactionId();
344 * Preassign OID for pg_database tuple, so that we can compute db
350 * Force dirty buffers out to disk, to ensure source database is
351 * up-to-date for the copy. (We really only need to flush buffers for
352 * the source database, but bufmgr.c provides no API for that.)
357 * Close virtual file descriptors so the kernel has more available for
358 * the system() calls below.
363 * Iterate through all tablespaces of the template database, and copy
364 * each one to the new database.
366 rel = heap_open(TableSpaceRelationId, AccessShareLock);
367 scan = heap_beginscan(rel, SnapshotNow, 0, NULL);
368 while ((tuple = heap_getnext(scan, ForwardScanDirection)) != NULL)
370 Oid srctablespace = HeapTupleGetOid(tuple);
376 /* No need to copy global tablespace */
377 if (srctablespace == GLOBALTABLESPACE_OID)
380 srcpath = GetDatabasePath(src_dboid, srctablespace);
382 if (stat(srcpath, &st) < 0 || !S_ISDIR(st.st_mode) ||
383 directory_is_empty(srcpath))
385 /* Assume we can ignore it */
390 if (srctablespace == src_deftablespace)
391 dsttablespace = dst_deftablespace;
393 dsttablespace = srctablespace;
395 dstpath = GetDatabasePath(dboid, dsttablespace);
397 if (stat(dstpath, &st) == 0 || errno != ENOENT)
399 remove_dbtablespaces(dboid);
401 (errmsg("could not initialize database directory"),
402 errdetail("Directory \"%s\" already exists.",
409 * Copy this subdirectory to the new location
411 * XXX use of cp really makes this code pretty grotty, particularly
412 * with respect to lack of ability to report errors well. Someday
413 * rewrite to do it for ourselves.
416 /* We might need to use cp -R one day for portability */
417 snprintf(buf, sizeof(buf), "cp -r '%s' '%s'",
419 if (system(buf) != 0)
421 remove_dbtablespaces(dboid);
423 (errmsg("could not initialize database directory"),
424 errdetail("Failing system command was: %s", buf),
425 errhint("Look in the postmaster's stderr log for more information.")));
428 if (copydir(srcpath, dstpath) != 0)
430 /* copydir should already have given details of its troubles */
431 remove_dbtablespaces(dboid);
433 (errmsg("could not initialize database directory")));
437 /* Record the filesystem change in XLOG */
439 xl_dbase_create_rec xlrec;
440 XLogRecData rdata[1];
443 xlrec.tablespace_id = dsttablespace;
444 xlrec.src_db_id = src_dboid;
445 xlrec.src_tablespace_id = srctablespace;
447 rdata[0].data = (char *) &xlrec;
448 rdata[0].len = sizeof(xl_dbase_create_rec);
449 rdata[0].buffer = InvalidBuffer;
450 rdata[0].next = NULL;
452 (void) XLogInsert(RM_DBASE_ID, XLOG_DBASE_CREATE, rdata);
456 heap_close(rel, AccessShareLock);
459 * Now OK to grab exclusive lock on pg_database.
461 pg_database_rel = heap_open(DatabaseRelationId, ExclusiveLock);
463 /* Check to see if someone else created same DB name meanwhile. */
464 if (get_db_info(dbname, NULL, NULL, NULL,
465 NULL, NULL, NULL, NULL, NULL, NULL))
467 /* Don't hold lock while doing recursive remove */
468 heap_close(pg_database_rel, ExclusiveLock);
469 remove_dbtablespaces(dboid);
471 (errcode(ERRCODE_DUPLICATE_DATABASE),
472 errmsg("database \"%s\" already exists", dbname)));
476 * Insert a new tuple into pg_database
478 pg_database_dsc = RelationGetDescr(pg_database_rel);
481 MemSet(new_record, 0, sizeof(new_record));
482 MemSet(new_record_nulls, ' ', sizeof(new_record_nulls));
484 new_record[Anum_pg_database_datname - 1] =
485 DirectFunctionCall1(namein, CStringGetDatum(dbname));
486 new_record[Anum_pg_database_datdba - 1] = Int32GetDatum(datdba);
487 new_record[Anum_pg_database_encoding - 1] = Int32GetDatum(encoding);
488 new_record[Anum_pg_database_datistemplate - 1] = BoolGetDatum(false);
489 new_record[Anum_pg_database_datallowconn - 1] = BoolGetDatum(true);
490 new_record[Anum_pg_database_datlastsysoid - 1] = ObjectIdGetDatum(src_lastsysoid);
491 new_record[Anum_pg_database_datvacuumxid - 1] = TransactionIdGetDatum(src_vacuumxid);
492 new_record[Anum_pg_database_datfrozenxid - 1] = TransactionIdGetDatum(src_frozenxid);
493 new_record[Anum_pg_database_dattablespace - 1] = ObjectIdGetDatum(dst_deftablespace);
496 * We deliberately set datconfig and datacl to defaults (NULL), rather
497 * than copying them from the template database. Copying datacl would
498 * be a bad idea when the owner is not the same as the template's
499 * owner. It's more debatable whether datconfig should be copied.
501 new_record_nulls[Anum_pg_database_datconfig - 1] = 'n';
502 new_record_nulls[Anum_pg_database_datacl - 1] = 'n';
504 tuple = heap_formtuple(pg_database_dsc, new_record, new_record_nulls);
506 HeapTupleSetOid(tuple, dboid); /* override heap_insert's OID
509 simple_heap_insert(pg_database_rel, tuple);
512 CatalogUpdateIndexes(pg_database_rel, tuple);
514 /* Close pg_database, but keep exclusive lock till commit */
515 heap_close(pg_database_rel, NoLock);
518 * We force a checkpoint before committing. This effectively means
519 * that committed XLOG_DBASE_CREATE operations will never need to be
520 * replayed (at least not in ordinary crash recovery; we still have
521 * to make the XLOG entry for the benefit of PITR operations).
522 * This avoids two nasty scenarios:
524 * #1: When PITR is off, we don't XLOG the contents of newly created
525 * indexes; therefore the drop-and-recreate-whole-directory behavior
526 * of DBASE_CREATE replay would lose such indexes.
528 * #2: Since we have to recopy the source database during DBASE_CREATE
529 * replay, we run the risk of copying changes in it that were committed
530 * after the original CREATE DATABASE command but before the system
531 * crash that led to the replay. This is at least unexpected and at
532 * worst could lead to inconsistencies, eg duplicate table names.
534 * (Both of these were real bugs in releases 8.0 through 8.0.3.)
536 * In PITR replay, the first of these isn't an issue, and the second
537 * is only a risk if the CREATE DATABASE and subsequent template
538 * database change both occur while a base backup is being taken.
539 * There doesn't seem to be much we can do about that except document
540 * it as a limitation.
542 * Perhaps if we ever implement CREATE DATABASE in a less cheesy
543 * way, we can avoid this.
545 RequestCheckpoint(true);
548 * Set flag to update flat database file at commit.
550 database_file_update_needed();
558 dropdb(const char *dbname)
564 SysScanDesc pgdbscan;
568 PreventTransactionChain((void *) dbname, "DROP DATABASE");
572 if (strcmp(dbname, get_database_name(MyDatabaseId)) == 0)
574 (errcode(ERRCODE_OBJECT_IN_USE),
575 errmsg("cannot drop the currently open database")));
578 * Obtain exclusive lock on pg_database. We need this to ensure that
579 * no new backend starts up in the target database while we are
580 * deleting it. (Actually, a new backend might still manage to start
581 * up, because it isn't able to lock pg_database while starting. But
582 * it will detect its error in ReverifyMyDatabase and shut down before
583 * any serious damage is done. See postinit.c.)
585 * An ExclusiveLock, rather than AccessExclusiveLock, is sufficient
586 * since ReverifyMyDatabase takes RowShareLock. This allows ordinary
587 * readers of pg_database to proceed in parallel.
589 pgdbrel = heap_open(DatabaseRelationId, ExclusiveLock);
591 if (!get_db_info(dbname, &db_id, &db_owner, NULL,
592 &db_istemplate, NULL, NULL, NULL, NULL, NULL))
594 (errcode(ERRCODE_UNDEFINED_DATABASE),
595 errmsg("database \"%s\" does not exist", dbname)));
597 if (GetUserId() != db_owner && !superuser())
598 aclcheck_error(ACLCHECK_NOT_OWNER, ACL_KIND_DATABASE,
602 * Disallow dropping a DB that is marked istemplate. This is just to
603 * prevent people from accidentally dropping template0 or template1;
604 * they can do so if they're really determined ...
608 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
609 errmsg("cannot drop a template database")));
612 * Check for active backends in the target database.
614 if (DatabaseHasActiveBackends(db_id, false))
616 (errcode(ERRCODE_OBJECT_IN_USE),
617 errmsg("database \"%s\" is being accessed by other users",
621 * Find the database's tuple by OID (should be unique).
624 ObjectIdAttributeNumber,
625 BTEqualStrategyNumber, F_OIDEQ,
626 ObjectIdGetDatum(db_id));
628 pgdbscan = systable_beginscan(pgdbrel, DatabaseOidIndexId, true,
629 SnapshotNow, 1, &key);
631 tup = systable_getnext(pgdbscan);
632 if (!HeapTupleIsValid(tup))
635 * This error should never come up since the existence of the
636 * database is checked earlier
638 elog(ERROR, "database \"%s\" doesn't exist despite earlier reports to the contrary",
642 /* Remove the database's tuple from pg_database */
643 simple_heap_delete(pgdbrel, &tup->t_self);
645 systable_endscan(pgdbscan);
648 * Delete any comments associated with the database
650 * NOTE: this is probably dead code since any such comments should have
651 * been in that database, not mine.
653 DeleteComments(db_id, DatabaseRelationId, 0);
656 * Drop pages for this database that are in the shared buffer cache.
657 * This is important to ensure that no remaining backend tries to
658 * write out a dirty buffer to the dead database later...
663 * Also, clean out any entries in the shared free space map.
665 FreeSpaceMapForgetDatabase(db_id);
668 * On Windows, force a checkpoint so that the bgwriter doesn't hold any
669 * open files, which would cause rmdir() to fail.
672 RequestCheckpoint(true);
676 * Remove all tablespace subdirs belonging to the database.
678 remove_dbtablespaces(db_id);
680 /* Close pg_database, but keep exclusive lock till commit */
681 heap_close(pgdbrel, NoLock);
684 * Set flag to update flat database file at commit.
686 database_file_update_needed();
694 RenameDatabase(const char *oldname, const char *newname)
705 * Obtain ExclusiveLock so that no new session gets started
706 * while the rename is in progress.
708 rel = heap_open(DatabaseRelationId, ExclusiveLock);
711 Anum_pg_database_datname,
712 BTEqualStrategyNumber, F_NAMEEQ,
713 NameGetDatum(oldname));
714 scan = systable_beginscan(rel, DatabaseNameIndexId, true,
715 SnapshotNow, 1, &key);
717 tup = systable_getnext(scan);
718 if (!HeapTupleIsValid(tup))
720 (errcode(ERRCODE_UNDEFINED_DATABASE),
721 errmsg("database \"%s\" does not exist", oldname)));
724 * XXX Client applications probably store the current database
725 * somewhere, so renaming it could cause confusion. On the other
726 * hand, there may not be an actual problem besides a little
727 * confusion, so think about this and decide.
729 if (HeapTupleGetOid(tup) == MyDatabaseId)
731 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
732 errmsg("current database may not be renamed")));
735 * Make sure the database does not have active sessions. Might not be
736 * necessary, but it's consistent with other database operations.
738 if (DatabaseHasActiveBackends(HeapTupleGetOid(tup), false))
740 (errcode(ERRCODE_OBJECT_IN_USE),
741 errmsg("database \"%s\" is being accessed by other users",
744 /* make sure the new name doesn't exist */
746 Anum_pg_database_datname,
747 BTEqualStrategyNumber, F_NAMEEQ,
748 NameGetDatum(newname));
749 scan2 = systable_beginscan(rel, DatabaseNameIndexId, true,
750 SnapshotNow, 1, &key2);
751 if (HeapTupleIsValid(systable_getnext(scan2)))
753 (errcode(ERRCODE_DUPLICATE_DATABASE),
754 errmsg("database \"%s\" already exists", newname)));
755 systable_endscan(scan2);
758 if (!pg_database_ownercheck(HeapTupleGetOid(tup), GetUserId()))
759 aclcheck_error(ACLCHECK_NOT_OWNER, ACL_KIND_DATABASE,
762 /* must have createdb rights */
763 if (!superuser() && !have_createdb_privilege())
765 (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
766 errmsg("permission denied to rename database")));
769 newtup = heap_copytuple(tup);
770 namestrcpy(&(((Form_pg_database) GETSTRUCT(newtup))->datname), newname);
771 simple_heap_update(rel, &newtup->t_self, newtup);
772 CatalogUpdateIndexes(rel, newtup);
774 systable_endscan(scan);
776 /* Close pg_database, but keep exclusive lock till commit */
777 heap_close(rel, NoLock);
780 * Set flag to update flat database file at commit.
782 database_file_update_needed();
787 * ALTER DATABASE name SET ...
790 AlterDatabaseSet(AlterDatabaseSetStmt *stmt)
798 Datum repl_val[Natts_pg_database];
799 char repl_null[Natts_pg_database];
800 char repl_repl[Natts_pg_database];
802 valuestr = flatten_set_variable_args(stmt->variable, stmt->value);
805 * We don't need ExclusiveLock since we aren't updating the
808 rel = heap_open(DatabaseRelationId, RowExclusiveLock);
809 ScanKeyInit(&scankey,
810 Anum_pg_database_datname,
811 BTEqualStrategyNumber, F_NAMEEQ,
812 NameGetDatum(stmt->dbname));
813 scan = systable_beginscan(rel, DatabaseNameIndexId, true,
814 SnapshotNow, 1, &scankey);
815 tuple = systable_getnext(scan);
816 if (!HeapTupleIsValid(tuple))
818 (errcode(ERRCODE_UNDEFINED_DATABASE),
819 errmsg("database \"%s\" does not exist", stmt->dbname)));
822 || ((Form_pg_database) GETSTRUCT(tuple))->datdba == GetUserId()))
823 aclcheck_error(ACLCHECK_NOT_OWNER, ACL_KIND_DATABASE,
826 MemSet(repl_repl, ' ', sizeof(repl_repl));
827 repl_repl[Anum_pg_database_datconfig - 1] = 'r';
829 if (strcmp(stmt->variable, "all") == 0 && valuestr == NULL)
832 repl_null[Anum_pg_database_datconfig - 1] = 'n';
833 repl_val[Anum_pg_database_datconfig - 1] = (Datum) 0;
841 repl_null[Anum_pg_database_datconfig - 1] = ' ';
843 datum = heap_getattr(tuple, Anum_pg_database_datconfig,
844 RelationGetDescr(rel), &isnull);
846 a = isnull ? NULL : DatumGetArrayTypeP(datum);
849 a = GUCArrayAdd(a, stmt->variable, valuestr);
851 a = GUCArrayDelete(a, stmt->variable);
854 repl_val[Anum_pg_database_datconfig - 1] = PointerGetDatum(a);
856 repl_null[Anum_pg_database_datconfig - 1] = 'n';
859 newtuple = heap_modifytuple(tuple, RelationGetDescr(rel), repl_val, repl_null, repl_repl);
860 simple_heap_update(rel, &tuple->t_self, newtuple);
863 CatalogUpdateIndexes(rel, newtuple);
865 systable_endscan(scan);
867 /* Close pg_database, but keep lock till commit */
868 heap_close(rel, NoLock);
871 * We don't bother updating the flat file since ALTER DATABASE SET
878 * ALTER DATABASE name OWNER TO newowner
881 AlterDatabaseOwner(const char *dbname, AclId newOwnerSysId)
887 Form_pg_database datForm;
890 * We don't need ExclusiveLock since we aren't updating the
893 rel = heap_open(DatabaseRelationId, RowExclusiveLock);
894 ScanKeyInit(&scankey,
895 Anum_pg_database_datname,
896 BTEqualStrategyNumber, F_NAMEEQ,
897 NameGetDatum(dbname));
898 scan = systable_beginscan(rel, DatabaseNameIndexId, true,
899 SnapshotNow, 1, &scankey);
900 tuple = systable_getnext(scan);
901 if (!HeapTupleIsValid(tuple))
903 (errcode(ERRCODE_UNDEFINED_DATABASE),
904 errmsg("database \"%s\" does not exist", dbname)));
906 datForm = (Form_pg_database) GETSTRUCT(tuple);
909 * If the new owner is the same as the existing owner, consider the
910 * command to have succeeded. This is to be consistent with other
913 if (datForm->datdba != newOwnerSysId)
915 Datum repl_val[Natts_pg_database];
916 char repl_null[Natts_pg_database];
917 char repl_repl[Natts_pg_database];
923 /* must be superuser to change ownership */
926 (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
927 errmsg("must be superuser to change owner")));
929 memset(repl_null, ' ', sizeof(repl_null));
930 memset(repl_repl, ' ', sizeof(repl_repl));
932 repl_repl[Anum_pg_database_datdba - 1] = 'r';
933 repl_val[Anum_pg_database_datdba - 1] = Int32GetDatum(newOwnerSysId);
936 * Determine the modified ACL for the new owner. This is only
937 * necessary when the ACL is non-null.
939 aclDatum = heap_getattr(tuple,
940 Anum_pg_database_datacl,
941 RelationGetDescr(rel),
945 newAcl = aclnewowner(DatumGetAclP(aclDatum),
946 datForm->datdba, newOwnerSysId);
947 repl_repl[Anum_pg_database_datacl - 1] = 'r';
948 repl_val[Anum_pg_database_datacl - 1] = PointerGetDatum(newAcl);
951 newtuple = heap_modifytuple(tuple, RelationGetDescr(rel), repl_val, repl_null, repl_repl);
952 simple_heap_update(rel, &newtuple->t_self, newtuple);
953 CatalogUpdateIndexes(rel, newtuple);
955 heap_freetuple(newtuple);
958 systable_endscan(scan);
960 /* Close pg_database, but keep lock till commit */
961 heap_close(rel, NoLock);
964 * We don't bother updating the flat file since ALTER DATABASE OWNER
975 get_db_info(const char *name, Oid *dbIdP, int4 *ownerIdP,
976 int *encodingP, bool *dbIsTemplateP, bool *dbAllowConnP,
978 TransactionId *dbVacuumXidP, TransactionId *dbFrozenXidP,
989 /* Caller may wish to grab a better lock on pg_database beforehand... */
990 relation = heap_open(DatabaseRelationId, AccessShareLock);
992 ScanKeyInit(&scanKey,
993 Anum_pg_database_datname,
994 BTEqualStrategyNumber, F_NAMEEQ,
997 scan = systable_beginscan(relation, DatabaseNameIndexId, true,
998 SnapshotNow, 1, &scanKey);
1000 tuple = systable_getnext(scan);
1002 gottuple = HeapTupleIsValid(tuple);
1005 Form_pg_database dbform = (Form_pg_database) GETSTRUCT(tuple);
1007 /* oid of the database */
1009 *dbIdP = HeapTupleGetOid(tuple);
1010 /* sysid of the owner */
1012 *ownerIdP = dbform->datdba;
1013 /* character encoding */
1015 *encodingP = dbform->encoding;
1016 /* allowed as template? */
1018 *dbIsTemplateP = dbform->datistemplate;
1019 /* allowing connections? */
1021 *dbAllowConnP = dbform->datallowconn;
1022 /* last system OID used in database */
1024 *dbLastSysOidP = dbform->datlastsysoid;
1025 /* limit of vacuumed XIDs */
1027 *dbVacuumXidP = dbform->datvacuumxid;
1028 /* limit of frozen XIDs */
1030 *dbFrozenXidP = dbform->datfrozenxid;
1031 /* default tablespace for this database */
1033 *dbTablespace = dbform->dattablespace;
1036 systable_endscan(scan);
1037 heap_close(relation, AccessShareLock);
1042 /* Check if current user has createdb privileges */
1044 have_createdb_privilege(void)
1046 bool result = false;
1049 utup = SearchSysCache(SHADOWSYSID,
1050 Int32GetDatum(GetUserId()),
1052 if (HeapTupleIsValid(utup))
1054 result = ((Form_pg_shadow) GETSTRUCT(utup))->usecreatedb;
1055 ReleaseSysCache(utup);
1061 * Remove tablespace directories
1063 * We don't know what tablespaces db_id is using, so iterate through all
1064 * tablespaces removing <tablespace>/db_id
1067 remove_dbtablespaces(Oid db_id)
1073 rel = heap_open(TableSpaceRelationId, AccessShareLock);
1074 scan = heap_beginscan(rel, SnapshotNow, 0, NULL);
1075 while ((tuple = heap_getnext(scan, ForwardScanDirection)) != NULL)
1077 Oid dsttablespace = HeapTupleGetOid(tuple);
1081 /* Don't mess with the global tablespace */
1082 if (dsttablespace == GLOBALTABLESPACE_OID)
1085 dstpath = GetDatabasePath(db_id, dsttablespace);
1087 if (stat(dstpath, &st) < 0 || !S_ISDIR(st.st_mode))
1089 /* Assume we can ignore it */
1094 if (!rmtree(dstpath, true))
1096 (errmsg("could not remove database directory \"%s\"",
1099 /* Record the filesystem change in XLOG */
1101 xl_dbase_drop_rec xlrec;
1102 XLogRecData rdata[1];
1104 xlrec.db_id = db_id;
1105 xlrec.tablespace_id = dsttablespace;
1107 rdata[0].data = (char *) &xlrec;
1108 rdata[0].len = sizeof(xl_dbase_drop_rec);
1109 rdata[0].buffer = InvalidBuffer;
1110 rdata[0].next = NULL;
1112 (void) XLogInsert(RM_DBASE_ID, XLOG_DBASE_DROP, rdata);
1119 heap_close(rel, AccessShareLock);
1124 * get_database_oid - given a database name, look up the OID
1126 * Returns InvalidOid if database name not found.
1128 * This is not actually used in this file, but is exported for use elsewhere.
1131 get_database_oid(const char *dbname)
1133 Relation pg_database;
1134 ScanKeyData entry[1];
1139 /* There's no syscache for pg_database, so must look the hard way */
1140 pg_database = heap_open(DatabaseRelationId, AccessShareLock);
1141 ScanKeyInit(&entry[0],
1142 Anum_pg_database_datname,
1143 BTEqualStrategyNumber, F_NAMEEQ,
1144 CStringGetDatum(dbname));
1145 scan = systable_beginscan(pg_database, DatabaseNameIndexId, true,
1146 SnapshotNow, 1, entry);
1148 dbtuple = systable_getnext(scan);
1150 /* We assume that there can be at most one matching tuple */
1151 if (HeapTupleIsValid(dbtuple))
1152 oid = HeapTupleGetOid(dbtuple);
1156 systable_endscan(scan);
1157 heap_close(pg_database, AccessShareLock);
1164 * get_database_name - given a database OID, look up the name
1166 * Returns a palloc'd string, or NULL if no such database.
1168 * This is not actually used in this file, but is exported for use elsewhere.
1171 get_database_name(Oid dbid)
1173 Relation pg_database;
1174 ScanKeyData entry[1];
1179 /* There's no syscache for pg_database, so must look the hard way */
1180 pg_database = heap_open(DatabaseRelationId, AccessShareLock);
1181 ScanKeyInit(&entry[0],
1182 ObjectIdAttributeNumber,
1183 BTEqualStrategyNumber, F_OIDEQ,
1184 ObjectIdGetDatum(dbid));
1185 scan = systable_beginscan(pg_database, DatabaseOidIndexId, true,
1186 SnapshotNow, 1, entry);
1188 dbtuple = systable_getnext(scan);
1190 /* We assume that there can be at most one matching tuple */
1191 if (HeapTupleIsValid(dbtuple))
1192 result = pstrdup(NameStr(((Form_pg_database) GETSTRUCT(dbtuple))->datname));
1196 systable_endscan(scan);
1197 heap_close(pg_database, AccessShareLock);
1203 * DATABASE resource manager's routines
1206 dbase_redo(XLogRecPtr lsn, XLogRecord *record)
1208 uint8 info = record->xl_info & ~XLR_INFO_MASK;
1210 if (info == XLOG_DBASE_CREATE)
1212 xl_dbase_create_rec *xlrec = (xl_dbase_create_rec *) XLogRecGetData(record);
1218 char buf[2 * MAXPGPATH + 100];
1221 src_path = GetDatabasePath(xlrec->src_db_id, xlrec->src_tablespace_id);
1222 dst_path = GetDatabasePath(xlrec->db_id, xlrec->tablespace_id);
1225 * Our theory for replaying a CREATE is to forcibly drop the
1226 * target subdirectory if present, then re-copy the source data.
1227 * This may be more work than needed, but it is simple to
1230 if (stat(dst_path, &st) == 0 && S_ISDIR(st.st_mode))
1232 if (!rmtree(dst_path, true))
1234 (errmsg("could not remove database directory \"%s\"",
1239 * Force dirty buffers out to disk, to ensure source database is
1240 * up-to-date for the copy. (We really only need to flush buffers for
1241 * the source database, but bufmgr.c provides no API for that.)
1248 * Copy this subdirectory to the new location
1250 * XXX use of cp really makes this code pretty grotty, particularly
1251 * with respect to lack of ability to report errors well. Someday
1252 * rewrite to do it for ourselves.
1255 /* We might need to use cp -R one day for portability */
1256 snprintf(buf, sizeof(buf), "cp -r '%s' '%s'",
1257 src_path, dst_path);
1258 if (system(buf) != 0)
1260 (errmsg("could not initialize database directory"),
1261 errdetail("Failing system command was: %s", buf),
1262 errhint("Look in the postmaster's stderr log for more information.")));
1264 if (copydir(src_path, dst_path) != 0)
1266 /* copydir should already have given details of its troubles */
1268 (errmsg("could not initialize database directory")));
1272 else if (info == XLOG_DBASE_DROP)
1274 xl_dbase_drop_rec *xlrec = (xl_dbase_drop_rec *) XLogRecGetData(record);
1277 dst_path = GetDatabasePath(xlrec->db_id, xlrec->tablespace_id);
1280 * Drop pages for this database that are in the shared buffer
1283 DropBuffers(xlrec->db_id);
1285 if (!rmtree(dst_path, true))
1287 (errmsg("could not remove database directory \"%s\"",
1290 else if (info == XLOG_DBASE_CREATE_OLD)
1292 xl_dbase_create_rec_old *xlrec = (xl_dbase_create_rec_old *) XLogRecGetData(record);
1293 char *dst_path = xlrec->src_path + strlen(xlrec->src_path) + 1;
1297 char buf[2 * MAXPGPATH + 100];
1301 * Our theory for replaying a CREATE is to forcibly drop the
1302 * target subdirectory if present, then re-copy the source data.
1303 * This may be more work than needed, but it is simple to
1306 if (stat(dst_path, &st) == 0 && S_ISDIR(st.st_mode))
1308 if (!rmtree(dst_path, true))
1310 (errmsg("could not remove database directory \"%s\"",
1315 * Force dirty buffers out to disk, to ensure source database is
1316 * up-to-date for the copy. (We really only need to flush buffers for
1317 * the source database, but bufmgr.c provides no API for that.)
1324 * Copy this subdirectory to the new location
1326 * XXX use of cp really makes this code pretty grotty, particularly
1327 * with respect to lack of ability to report errors well. Someday
1328 * rewrite to do it for ourselves.
1331 /* We might need to use cp -R one day for portability */
1332 snprintf(buf, sizeof(buf), "cp -r '%s' '%s'",
1333 xlrec->src_path, dst_path);
1334 if (system(buf) != 0)
1336 (errmsg("could not initialize database directory"),
1337 errdetail("Failing system command was: %s", buf),
1338 errhint("Look in the postmaster's stderr log for more information.")));
1340 if (copydir(xlrec->src_path, dst_path) != 0)
1342 /* copydir should already have given details of its troubles */
1344 (errmsg("could not initialize database directory")));
1348 else if (info == XLOG_DBASE_DROP_OLD)
1350 xl_dbase_drop_rec_old *xlrec = (xl_dbase_drop_rec_old *) XLogRecGetData(record);
1353 * Drop pages for this database that are in the shared buffer
1356 DropBuffers(xlrec->db_id);
1358 if (!rmtree(xlrec->dir_path, true))
1360 (errmsg("could not remove database directory \"%s\"",
1364 elog(PANIC, "dbase_redo: unknown op code %u", info);
1368 dbase_desc(char *buf, uint8 xl_info, char *rec)
1370 uint8 info = xl_info & ~XLR_INFO_MASK;
1372 if (info == XLOG_DBASE_CREATE)
1374 xl_dbase_create_rec *xlrec = (xl_dbase_create_rec *) rec;
1376 sprintf(buf + strlen(buf), "create db: copy dir %u/%u to %u/%u",
1377 xlrec->src_db_id, xlrec->src_tablespace_id,
1378 xlrec->db_id, xlrec->tablespace_id);
1380 else if (info == XLOG_DBASE_DROP)
1382 xl_dbase_drop_rec *xlrec = (xl_dbase_drop_rec *) rec;
1384 sprintf(buf + strlen(buf), "drop db: dir %u/%u",
1385 xlrec->db_id, xlrec->tablespace_id);
1387 else if (info == XLOG_DBASE_CREATE_OLD)
1389 xl_dbase_create_rec_old *xlrec = (xl_dbase_create_rec_old *) rec;
1390 char *dst_path = xlrec->src_path + strlen(xlrec->src_path) + 1;
1392 sprintf(buf + strlen(buf), "create db: %u copy \"%s\" to \"%s\"",
1393 xlrec->db_id, xlrec->src_path, dst_path);
1395 else if (info == XLOG_DBASE_DROP_OLD)
1397 xl_dbase_drop_rec_old *xlrec = (xl_dbase_drop_rec_old *) rec;
1399 sprintf(buf + strlen(buf), "drop db: %u directory: \"%s\"",
1400 xlrec->db_id, xlrec->dir_path);
1403 strcat(buf, "UNKNOWN");