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.156 2005/04/14 20:03:23 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/sinval.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 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].buffer = InvalidBuffer;
448 rdata[0].data = (char *) &xlrec;
449 rdata[0].len = sizeof(xl_dbase_create_rec);
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 * Set flag to update flat database file at commit.
520 database_file_update_needed();
528 dropdb(const char *dbname)
534 SysScanDesc pgdbscan;
538 PreventTransactionChain((void *) dbname, "DROP DATABASE");
542 if (strcmp(dbname, get_database_name(MyDatabaseId)) == 0)
544 (errcode(ERRCODE_OBJECT_IN_USE),
545 errmsg("cannot drop the currently open database")));
548 * Obtain exclusive lock on pg_database. We need this to ensure that
549 * no new backend starts up in the target database while we are
550 * deleting it. (Actually, a new backend might still manage to start
551 * up, because it isn't able to lock pg_database while starting. But
552 * it will detect its error in ReverifyMyDatabase and shut down before
553 * any serious damage is done. See postinit.c.)
555 * An ExclusiveLock, rather than AccessExclusiveLock, is sufficient
556 * since ReverifyMyDatabase takes RowShareLock. This allows ordinary
557 * readers of pg_database to proceed in parallel.
559 pgdbrel = heap_open(DatabaseRelationId, ExclusiveLock);
561 if (!get_db_info(dbname, &db_id, &db_owner, NULL,
562 &db_istemplate, NULL, NULL, NULL, NULL, NULL))
564 (errcode(ERRCODE_UNDEFINED_DATABASE),
565 errmsg("database \"%s\" does not exist", dbname)));
567 if (GetUserId() != db_owner && !superuser())
568 aclcheck_error(ACLCHECK_NOT_OWNER, ACL_KIND_DATABASE,
572 * Disallow dropping a DB that is marked istemplate. This is just to
573 * prevent people from accidentally dropping template0 or template1;
574 * they can do so if they're really determined ...
578 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
579 errmsg("cannot drop a template database")));
582 * Check for active backends in the target database.
584 if (DatabaseHasActiveBackends(db_id, false))
586 (errcode(ERRCODE_OBJECT_IN_USE),
587 errmsg("database \"%s\" is being accessed by other users",
591 * Find the database's tuple by OID (should be unique).
594 ObjectIdAttributeNumber,
595 BTEqualStrategyNumber, F_OIDEQ,
596 ObjectIdGetDatum(db_id));
598 pgdbscan = systable_beginscan(pgdbrel, DatabaseOidIndexId, true,
599 SnapshotNow, 1, &key);
601 tup = systable_getnext(pgdbscan);
602 if (!HeapTupleIsValid(tup))
605 * This error should never come up since the existence of the
606 * database is checked earlier
608 elog(ERROR, "database \"%s\" doesn't exist despite earlier reports to the contrary",
612 /* Remove the database's tuple from pg_database */
613 simple_heap_delete(pgdbrel, &tup->t_self);
615 systable_endscan(pgdbscan);
618 * Delete any comments associated with the database
620 * NOTE: this is probably dead code since any such comments should have
621 * been in that database, not mine.
623 DeleteComments(db_id, DatabaseRelationId, 0);
626 * Drop pages for this database that are in the shared buffer cache.
627 * This is important to ensure that no remaining backend tries to
628 * write out a dirty buffer to the dead database later...
633 * Also, clean out any entries in the shared free space map.
635 FreeSpaceMapForgetDatabase(db_id);
638 * On Windows, force a checkpoint so that the bgwriter doesn't hold any
639 * open files, which would cause rmdir() to fail.
642 RequestCheckpoint(true);
646 * Remove all tablespace subdirs belonging to the database.
648 remove_dbtablespaces(db_id);
650 /* Close pg_database, but keep exclusive lock till commit */
651 heap_close(pgdbrel, NoLock);
654 * Set flag to update flat database file at commit.
656 database_file_update_needed();
664 RenameDatabase(const char *oldname, const char *newname)
675 * Obtain ExclusiveLock so that no new session gets started
676 * while the rename is in progress.
678 rel = heap_open(DatabaseRelationId, ExclusiveLock);
681 Anum_pg_database_datname,
682 BTEqualStrategyNumber, F_NAMEEQ,
683 NameGetDatum(oldname));
684 scan = systable_beginscan(rel, DatabaseNameIndexId, true,
685 SnapshotNow, 1, &key);
687 tup = systable_getnext(scan);
688 if (!HeapTupleIsValid(tup))
690 (errcode(ERRCODE_UNDEFINED_DATABASE),
691 errmsg("database \"%s\" does not exist", oldname)));
694 * XXX Client applications probably store the current database
695 * somewhere, so renaming it could cause confusion. On the other
696 * hand, there may not be an actual problem besides a little
697 * confusion, so think about this and decide.
699 if (HeapTupleGetOid(tup) == MyDatabaseId)
701 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
702 errmsg("current database may not be renamed")));
705 * Make sure the database does not have active sessions. Might not be
706 * necessary, but it's consistent with other database operations.
708 if (DatabaseHasActiveBackends(HeapTupleGetOid(tup), false))
710 (errcode(ERRCODE_OBJECT_IN_USE),
711 errmsg("database \"%s\" is being accessed by other users",
714 /* make sure the new name doesn't exist */
716 Anum_pg_database_datname,
717 BTEqualStrategyNumber, F_NAMEEQ,
718 NameGetDatum(newname));
719 scan2 = systable_beginscan(rel, DatabaseNameIndexId, true,
720 SnapshotNow, 1, &key2);
721 if (HeapTupleIsValid(systable_getnext(scan2)))
723 (errcode(ERRCODE_DUPLICATE_DATABASE),
724 errmsg("database \"%s\" already exists", newname)));
725 systable_endscan(scan2);
728 if (!pg_database_ownercheck(HeapTupleGetOid(tup), GetUserId()))
729 aclcheck_error(ACLCHECK_NOT_OWNER, ACL_KIND_DATABASE,
732 /* must have createdb rights */
733 if (!superuser() && !have_createdb_privilege())
735 (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
736 errmsg("permission denied to rename database")));
739 newtup = heap_copytuple(tup);
740 namestrcpy(&(((Form_pg_database) GETSTRUCT(newtup))->datname), newname);
741 simple_heap_update(rel, &newtup->t_self, newtup);
742 CatalogUpdateIndexes(rel, newtup);
744 systable_endscan(scan);
746 /* Close pg_database, but keep exclusive lock till commit */
747 heap_close(rel, NoLock);
750 * Set flag to update flat database file at commit.
752 database_file_update_needed();
757 * ALTER DATABASE name SET ...
760 AlterDatabaseSet(AlterDatabaseSetStmt *stmt)
768 Datum repl_val[Natts_pg_database];
769 char repl_null[Natts_pg_database];
770 char repl_repl[Natts_pg_database];
772 valuestr = flatten_set_variable_args(stmt->variable, stmt->value);
775 * We don't need ExclusiveLock since we aren't updating the
778 rel = heap_open(DatabaseRelationId, RowExclusiveLock);
779 ScanKeyInit(&scankey,
780 Anum_pg_database_datname,
781 BTEqualStrategyNumber, F_NAMEEQ,
782 NameGetDatum(stmt->dbname));
783 scan = systable_beginscan(rel, DatabaseNameIndexId, true,
784 SnapshotNow, 1, &scankey);
785 tuple = systable_getnext(scan);
786 if (!HeapTupleIsValid(tuple))
788 (errcode(ERRCODE_UNDEFINED_DATABASE),
789 errmsg("database \"%s\" does not exist", stmt->dbname)));
792 || ((Form_pg_database) GETSTRUCT(tuple))->datdba == GetUserId()))
793 aclcheck_error(ACLCHECK_NOT_OWNER, ACL_KIND_DATABASE,
796 MemSet(repl_repl, ' ', sizeof(repl_repl));
797 repl_repl[Anum_pg_database_datconfig - 1] = 'r';
799 if (strcmp(stmt->variable, "all") == 0 && valuestr == NULL)
802 repl_null[Anum_pg_database_datconfig - 1] = 'n';
803 repl_val[Anum_pg_database_datconfig - 1] = (Datum) 0;
811 repl_null[Anum_pg_database_datconfig - 1] = ' ';
813 datum = heap_getattr(tuple, Anum_pg_database_datconfig,
814 RelationGetDescr(rel), &isnull);
816 a = isnull ? NULL : DatumGetArrayTypeP(datum);
819 a = GUCArrayAdd(a, stmt->variable, valuestr);
821 a = GUCArrayDelete(a, stmt->variable);
824 repl_val[Anum_pg_database_datconfig - 1] = PointerGetDatum(a);
826 repl_null[Anum_pg_database_datconfig - 1] = 'n';
829 newtuple = heap_modifytuple(tuple, RelationGetDescr(rel), repl_val, repl_null, repl_repl);
830 simple_heap_update(rel, &tuple->t_self, newtuple);
833 CatalogUpdateIndexes(rel, newtuple);
835 systable_endscan(scan);
837 /* Close pg_database, but keep lock till commit */
838 heap_close(rel, NoLock);
841 * We don't bother updating the flat file since ALTER DATABASE SET
848 * ALTER DATABASE name OWNER TO newowner
851 AlterDatabaseOwner(const char *dbname, AclId newOwnerSysId)
857 Form_pg_database datForm;
860 * We don't need ExclusiveLock since we aren't updating the
863 rel = heap_open(DatabaseRelationId, RowExclusiveLock);
864 ScanKeyInit(&scankey,
865 Anum_pg_database_datname,
866 BTEqualStrategyNumber, F_NAMEEQ,
867 NameGetDatum(dbname));
868 scan = systable_beginscan(rel, DatabaseNameIndexId, true,
869 SnapshotNow, 1, &scankey);
870 tuple = systable_getnext(scan);
871 if (!HeapTupleIsValid(tuple))
873 (errcode(ERRCODE_UNDEFINED_DATABASE),
874 errmsg("database \"%s\" does not exist", dbname)));
876 datForm = (Form_pg_database) GETSTRUCT(tuple);
879 * If the new owner is the same as the existing owner, consider the
880 * command to have succeeded. This is to be consistent with other
883 if (datForm->datdba != newOwnerSysId)
885 Datum repl_val[Natts_pg_database];
886 char repl_null[Natts_pg_database];
887 char repl_repl[Natts_pg_database];
893 /* must be superuser to change ownership */
896 (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
897 errmsg("must be superuser to change owner")));
899 memset(repl_null, ' ', sizeof(repl_null));
900 memset(repl_repl, ' ', sizeof(repl_repl));
902 repl_repl[Anum_pg_database_datdba - 1] = 'r';
903 repl_val[Anum_pg_database_datdba - 1] = Int32GetDatum(newOwnerSysId);
906 * Determine the modified ACL for the new owner. This is only
907 * necessary when the ACL is non-null.
909 aclDatum = heap_getattr(tuple,
910 Anum_pg_database_datacl,
911 RelationGetDescr(rel),
915 newAcl = aclnewowner(DatumGetAclP(aclDatum),
916 datForm->datdba, newOwnerSysId);
917 repl_repl[Anum_pg_database_datacl - 1] = 'r';
918 repl_val[Anum_pg_database_datacl - 1] = PointerGetDatum(newAcl);
921 newtuple = heap_modifytuple(tuple, RelationGetDescr(rel), repl_val, repl_null, repl_repl);
922 simple_heap_update(rel, &newtuple->t_self, newtuple);
923 CatalogUpdateIndexes(rel, newtuple);
925 heap_freetuple(newtuple);
928 systable_endscan(scan);
930 /* Close pg_database, but keep lock till commit */
931 heap_close(rel, NoLock);
934 * We don't bother updating the flat file since ALTER DATABASE OWNER
945 get_db_info(const char *name, Oid *dbIdP, int4 *ownerIdP,
946 int *encodingP, bool *dbIsTemplateP, bool *dbAllowConnP,
948 TransactionId *dbVacuumXidP, TransactionId *dbFrozenXidP,
959 /* Caller may wish to grab a better lock on pg_database beforehand... */
960 relation = heap_open(DatabaseRelationId, AccessShareLock);
962 ScanKeyInit(&scanKey,
963 Anum_pg_database_datname,
964 BTEqualStrategyNumber, F_NAMEEQ,
967 scan = systable_beginscan(relation, DatabaseNameIndexId, true,
968 SnapshotNow, 1, &scanKey);
970 tuple = systable_getnext(scan);
972 gottuple = HeapTupleIsValid(tuple);
975 Form_pg_database dbform = (Form_pg_database) GETSTRUCT(tuple);
977 /* oid of the database */
979 *dbIdP = HeapTupleGetOid(tuple);
980 /* sysid of the owner */
982 *ownerIdP = dbform->datdba;
983 /* character encoding */
985 *encodingP = dbform->encoding;
986 /* allowed as template? */
988 *dbIsTemplateP = dbform->datistemplate;
989 /* allowing connections? */
991 *dbAllowConnP = dbform->datallowconn;
992 /* last system OID used in database */
994 *dbLastSysOidP = dbform->datlastsysoid;
995 /* limit of vacuumed XIDs */
997 *dbVacuumXidP = dbform->datvacuumxid;
998 /* limit of frozen XIDs */
1000 *dbFrozenXidP = dbform->datfrozenxid;
1001 /* default tablespace for this database */
1003 *dbTablespace = dbform->dattablespace;
1006 systable_endscan(scan);
1007 heap_close(relation, AccessShareLock);
1012 /* Check if current user has createdb privileges */
1014 have_createdb_privilege(void)
1016 bool result = false;
1019 utup = SearchSysCache(SHADOWSYSID,
1020 Int32GetDatum(GetUserId()),
1022 if (HeapTupleIsValid(utup))
1024 result = ((Form_pg_shadow) GETSTRUCT(utup))->usecreatedb;
1025 ReleaseSysCache(utup);
1031 * Remove tablespace directories
1033 * We don't know what tablespaces db_id is using, so iterate through all
1034 * tablespaces removing <tablespace>/db_id
1037 remove_dbtablespaces(Oid db_id)
1043 rel = heap_open(TableSpaceRelationId, AccessShareLock);
1044 scan = heap_beginscan(rel, SnapshotNow, 0, NULL);
1045 while ((tuple = heap_getnext(scan, ForwardScanDirection)) != NULL)
1047 Oid dsttablespace = HeapTupleGetOid(tuple);
1051 /* Don't mess with the global tablespace */
1052 if (dsttablespace == GLOBALTABLESPACE_OID)
1055 dstpath = GetDatabasePath(db_id, dsttablespace);
1057 if (stat(dstpath, &st) < 0 || !S_ISDIR(st.st_mode))
1059 /* Assume we can ignore it */
1064 if (!rmtree(dstpath, true))
1066 (errmsg("could not remove database directory \"%s\"",
1069 /* Record the filesystem change in XLOG */
1071 xl_dbase_drop_rec xlrec;
1072 XLogRecData rdata[1];
1074 xlrec.db_id = db_id;
1075 xlrec.tablespace_id = dsttablespace;
1077 rdata[0].buffer = InvalidBuffer;
1078 rdata[0].data = (char *) &xlrec;
1079 rdata[0].len = sizeof(xl_dbase_drop_rec);
1080 rdata[0].next = NULL;
1082 (void) XLogInsert(RM_DBASE_ID, XLOG_DBASE_DROP, rdata);
1089 heap_close(rel, AccessShareLock);
1094 * get_database_oid - given a database name, look up the OID
1096 * Returns InvalidOid if database name not found.
1098 * This is not actually used in this file, but is exported for use elsewhere.
1101 get_database_oid(const char *dbname)
1103 Relation pg_database;
1104 ScanKeyData entry[1];
1109 /* There's no syscache for pg_database, so must look the hard way */
1110 pg_database = heap_open(DatabaseRelationId, AccessShareLock);
1111 ScanKeyInit(&entry[0],
1112 Anum_pg_database_datname,
1113 BTEqualStrategyNumber, F_NAMEEQ,
1114 CStringGetDatum(dbname));
1115 scan = systable_beginscan(pg_database, DatabaseNameIndexId, true,
1116 SnapshotNow, 1, entry);
1118 dbtuple = systable_getnext(scan);
1120 /* We assume that there can be at most one matching tuple */
1121 if (HeapTupleIsValid(dbtuple))
1122 oid = HeapTupleGetOid(dbtuple);
1126 systable_endscan(scan);
1127 heap_close(pg_database, AccessShareLock);
1134 * get_database_name - given a database OID, look up the name
1136 * Returns a palloc'd string, or NULL if no such database.
1138 * This is not actually used in this file, but is exported for use elsewhere.
1141 get_database_name(Oid dbid)
1143 Relation pg_database;
1144 ScanKeyData entry[1];
1149 /* There's no syscache for pg_database, so must look the hard way */
1150 pg_database = heap_open(DatabaseRelationId, AccessShareLock);
1151 ScanKeyInit(&entry[0],
1152 ObjectIdAttributeNumber,
1153 BTEqualStrategyNumber, F_OIDEQ,
1154 ObjectIdGetDatum(dbid));
1155 scan = systable_beginscan(pg_database, DatabaseOidIndexId, true,
1156 SnapshotNow, 1, entry);
1158 dbtuple = systable_getnext(scan);
1160 /* We assume that there can be at most one matching tuple */
1161 if (HeapTupleIsValid(dbtuple))
1162 result = pstrdup(NameStr(((Form_pg_database) GETSTRUCT(dbtuple))->datname));
1166 systable_endscan(scan);
1167 heap_close(pg_database, AccessShareLock);
1173 * DATABASE resource manager's routines
1176 dbase_redo(XLogRecPtr lsn, XLogRecord *record)
1178 uint8 info = record->xl_info & ~XLR_INFO_MASK;
1180 if (info == XLOG_DBASE_CREATE)
1182 xl_dbase_create_rec *xlrec = (xl_dbase_create_rec *) XLogRecGetData(record);
1188 char buf[2 * MAXPGPATH + 100];
1191 src_path = GetDatabasePath(xlrec->src_db_id, xlrec->src_tablespace_id);
1192 dst_path = GetDatabasePath(xlrec->db_id, xlrec->tablespace_id);
1195 * Our theory for replaying a CREATE is to forcibly drop the
1196 * target subdirectory if present, then re-copy the source data.
1197 * This may be more work than needed, but it is simple to
1200 if (stat(dst_path, &st) == 0 && S_ISDIR(st.st_mode))
1202 if (!rmtree(dst_path, true))
1204 (errmsg("could not remove database directory \"%s\"",
1209 * Force dirty buffers out to disk, to ensure source database is
1210 * up-to-date for the copy. (We really only need to flush buffers for
1211 * the source database, but bufmgr.c provides no API for that.)
1218 * Copy this subdirectory to the new location
1220 * XXX use of cp really makes this code pretty grotty, particularly
1221 * with respect to lack of ability to report errors well. Someday
1222 * rewrite to do it for ourselves.
1225 /* We might need to use cp -R one day for portability */
1226 snprintf(buf, sizeof(buf), "cp -r '%s' '%s'",
1227 src_path, dst_path);
1228 if (system(buf) != 0)
1230 (errmsg("could not initialize database directory"),
1231 errdetail("Failing system command was: %s", buf),
1232 errhint("Look in the postmaster's stderr log for more information.")));
1234 if (copydir(src_path, dst_path) != 0)
1236 /* copydir should already have given details of its troubles */
1238 (errmsg("could not initialize database directory")));
1242 else if (info == XLOG_DBASE_DROP)
1244 xl_dbase_drop_rec *xlrec = (xl_dbase_drop_rec *) XLogRecGetData(record);
1247 dst_path = GetDatabasePath(xlrec->db_id, xlrec->tablespace_id);
1250 * Drop pages for this database that are in the shared buffer
1253 DropBuffers(xlrec->db_id);
1255 if (!rmtree(dst_path, true))
1257 (errmsg("could not remove database directory \"%s\"",
1260 else if (info == XLOG_DBASE_CREATE_OLD)
1262 xl_dbase_create_rec_old *xlrec = (xl_dbase_create_rec_old *) XLogRecGetData(record);
1263 char *dst_path = xlrec->src_path + strlen(xlrec->src_path) + 1;
1267 char buf[2 * MAXPGPATH + 100];
1271 * Our theory for replaying a CREATE is to forcibly drop the
1272 * target subdirectory if present, then re-copy the source data.
1273 * This may be more work than needed, but it is simple to
1276 if (stat(dst_path, &st) == 0 && S_ISDIR(st.st_mode))
1278 if (!rmtree(dst_path, true))
1280 (errmsg("could not remove database directory \"%s\"",
1285 * Force dirty buffers out to disk, to ensure source database is
1286 * up-to-date for the copy. (We really only need to flush buffers for
1287 * the source database, but bufmgr.c provides no API for that.)
1294 * Copy this subdirectory to the new location
1296 * XXX use of cp really makes this code pretty grotty, particularly
1297 * with respect to lack of ability to report errors well. Someday
1298 * rewrite to do it for ourselves.
1301 /* We might need to use cp -R one day for portability */
1302 snprintf(buf, sizeof(buf), "cp -r '%s' '%s'",
1303 xlrec->src_path, dst_path);
1304 if (system(buf) != 0)
1306 (errmsg("could not initialize database directory"),
1307 errdetail("Failing system command was: %s", buf),
1308 errhint("Look in the postmaster's stderr log for more information.")));
1310 if (copydir(xlrec->src_path, dst_path) != 0)
1312 /* copydir should already have given details of its troubles */
1314 (errmsg("could not initialize database directory")));
1318 else if (info == XLOG_DBASE_DROP_OLD)
1320 xl_dbase_drop_rec_old *xlrec = (xl_dbase_drop_rec_old *) XLogRecGetData(record);
1323 * Drop pages for this database that are in the shared buffer
1326 DropBuffers(xlrec->db_id);
1328 if (!rmtree(xlrec->dir_path, true))
1330 (errmsg("could not remove database directory \"%s\"",
1334 elog(PANIC, "dbase_redo: unknown op code %u", info);
1338 dbase_undo(XLogRecPtr lsn, XLogRecord *record)
1340 elog(PANIC, "dbase_undo: unimplemented");
1344 dbase_desc(char *buf, uint8 xl_info, char *rec)
1346 uint8 info = xl_info & ~XLR_INFO_MASK;
1348 if (info == XLOG_DBASE_CREATE)
1350 xl_dbase_create_rec *xlrec = (xl_dbase_create_rec *) rec;
1352 sprintf(buf + strlen(buf), "create db: copy dir %u/%u to %u/%u",
1353 xlrec->src_db_id, xlrec->src_tablespace_id,
1354 xlrec->db_id, xlrec->tablespace_id);
1356 else if (info == XLOG_DBASE_DROP)
1358 xl_dbase_drop_rec *xlrec = (xl_dbase_drop_rec *) rec;
1360 sprintf(buf + strlen(buf), "drop db: dir %u/%u",
1361 xlrec->db_id, xlrec->tablespace_id);
1363 else if (info == XLOG_DBASE_CREATE_OLD)
1365 xl_dbase_create_rec_old *xlrec = (xl_dbase_create_rec_old *) rec;
1366 char *dst_path = xlrec->src_path + strlen(xlrec->src_path) + 1;
1368 sprintf(buf + strlen(buf), "create db: %u copy \"%s\" to \"%s\"",
1369 xlrec->db_id, xlrec->src_path, dst_path);
1371 else if (info == XLOG_DBASE_DROP_OLD)
1373 xl_dbase_drop_rec_old *xlrec = (xl_dbase_drop_rec_old *) rec;
1375 sprintf(buf + strlen(buf), "drop db: %u directory: \"%s\"",
1376 xlrec->db_id, xlrec->dir_path);
1379 strcat(buf, "UNKNOWN");