1 /*-------------------------------------------------------------------------
4 * Database management commands (create/drop database).
7 * Portions Copyright (c) 1996-2005, PostgreSQL Global Development Group
8 * Portions Copyright (c) 1994, Regents of the University of California
12 * $PostgreSQL: pgsql/src/backend/commands/dbcommands.c,v 1.150 2005/02/20 02:21:34 tgl Exp $
14 *-------------------------------------------------------------------------
22 #include "access/genam.h"
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/pg_tablespace.h"
29 #include "catalog/indexing.h"
30 #include "commands/comment.h"
31 #include "commands/dbcommands.h"
32 #include "commands/tablespace.h"
33 #include "mb/pg_wchar.h"
34 #include "miscadmin.h"
35 #include "postmaster/bgwriter.h"
36 #include "storage/fd.h"
37 #include "storage/freespace.h"
38 #include "storage/sinval.h"
39 #include "utils/acl.h"
40 #include "utils/array.h"
41 #include "utils/builtins.h"
42 #include "utils/flatfiles.h"
43 #include "utils/fmgroids.h"
44 #include "utils/guc.h"
45 #include "utils/lsyscache.h"
46 #include "utils/syscache.h"
49 /* non-export function prototypes */
50 static bool get_db_info(const char *name, Oid *dbIdP, int4 *ownerIdP,
51 int *encodingP, bool *dbIsTemplateP, Oid *dbLastSysOidP,
52 TransactionId *dbVacuumXidP, TransactionId *dbFrozenXidP,
54 static bool have_createdb_privilege(void);
55 static void remove_dbtablespaces(Oid db_id);
62 createdb(const CreatedbStmt *stmt)
71 TransactionId src_vacuumxid;
72 TransactionId src_frozenxid;
73 Oid src_deftablespace;
74 Oid dst_deftablespace;
75 Relation pg_database_rel;
77 TupleDesc pg_database_dsc;
78 Datum new_record[Natts_pg_database];
79 char new_record_nulls[Natts_pg_database];
83 DefElem *dtablespacename = NULL;
84 DefElem *downer = NULL;
85 DefElem *dtemplate = NULL;
86 DefElem *dencoding = NULL;
87 char *dbname = stmt->dbname;
89 char *dbtemplate = NULL;
93 char buf[2 * MAXPGPATH + 100];
96 /* don't call this in a transaction block */
97 PreventTransactionChain((void *) stmt, "CREATE DATABASE");
99 /* Extract options from the statement node tree */
100 foreach(option, stmt->options)
102 DefElem *defel = (DefElem *) lfirst(option);
104 if (strcmp(defel->defname, "tablespace") == 0)
108 (errcode(ERRCODE_SYNTAX_ERROR),
109 errmsg("conflicting or redundant options")));
110 dtablespacename = defel;
112 else if (strcmp(defel->defname, "owner") == 0)
116 (errcode(ERRCODE_SYNTAX_ERROR),
117 errmsg("conflicting or redundant options")));
120 else if (strcmp(defel->defname, "template") == 0)
124 (errcode(ERRCODE_SYNTAX_ERROR),
125 errmsg("conflicting or redundant options")));
128 else if (strcmp(defel->defname, "encoding") == 0)
132 (errcode(ERRCODE_SYNTAX_ERROR),
133 errmsg("conflicting or redundant options")));
136 else if (strcmp(defel->defname, "location") == 0)
139 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
140 errmsg("LOCATION is not supported anymore"),
141 errhint("Consider using tablespaces instead.")));
144 elog(ERROR, "option \"%s\" not recognized",
148 if (downer && downer->arg)
149 dbowner = strVal(downer->arg);
150 if (dtemplate && dtemplate->arg)
151 dbtemplate = strVal(dtemplate->arg);
152 if (dencoding && dencoding->arg)
154 const char *encoding_name;
156 if (IsA(dencoding->arg, Integer))
158 encoding = intVal(dencoding->arg);
159 encoding_name = pg_encoding_to_char(encoding);
160 if (strcmp(encoding_name, "") == 0 ||
161 pg_valid_server_encoding(encoding_name) < 0)
163 (errcode(ERRCODE_UNDEFINED_OBJECT),
164 errmsg("%d is not a valid encoding code",
167 else if (IsA(dencoding->arg, String))
169 encoding_name = strVal(dencoding->arg);
170 if (pg_valid_server_encoding(encoding_name) < 0)
172 (errcode(ERRCODE_UNDEFINED_OBJECT),
173 errmsg("%s is not a valid encoding name",
175 encoding = pg_char_to_encoding(encoding_name);
178 elog(ERROR, "unrecognized node type: %d",
179 nodeTag(dencoding->arg));
182 /* obtain sysid of proposed owner */
184 datdba = get_usesysid(dbowner); /* will ereport if no such user */
186 datdba = GetUserId();
188 if (datdba == GetUserId())
190 /* creating database for self: can be superuser or createdb */
191 if (!superuser() && !have_createdb_privilege())
193 (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
194 errmsg("permission denied to create database")));
198 /* creating database for someone else: must be superuser */
199 /* note that the someone else need not have any permissions */
202 (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
203 errmsg("must be superuser to create database for another user")));
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.
214 if (get_db_info(dbname, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL))
216 (errcode(ERRCODE_DUPLICATE_DATABASE),
217 errmsg("database \"%s\" already exists", dbname)));
220 * Lookup database (template) to be cloned.
223 dbtemplate = "template1"; /* Default template database name */
225 if (!get_db_info(dbtemplate, &src_dboid, &src_owner, &src_encoding,
226 &src_istemplate, &src_lastsysoid,
227 &src_vacuumxid, &src_frozenxid, &src_deftablespace))
229 (errcode(ERRCODE_UNDEFINED_DATABASE),
230 errmsg("template database \"%s\" does not exist", dbtemplate)));
233 * Permission check: to copy a DB that's not marked datistemplate, you
234 * must be superuser or the owner thereof.
238 if (!superuser() && GetUserId() != src_owner)
240 (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
241 errmsg("permission denied to copy database \"%s\"",
246 * The source DB can't have any active backends, except this one
247 * (exception is to allow CREATE DB while connected to template1).
248 * Otherwise we might copy inconsistent data. This check is not
249 * bulletproof, since someone might connect while we are copying...
251 if (DatabaseHasActiveBackends(src_dboid, true))
253 (errcode(ERRCODE_OBJECT_IN_USE),
254 errmsg("source database \"%s\" is being accessed by other users",
257 /* If encoding is defaulted, use source's encoding */
259 encoding = src_encoding;
261 /* Some encodings are client only */
262 if (!PG_VALID_BE_ENCODING(encoding))
264 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
265 errmsg("invalid server encoding %d", encoding)));
267 /* Resolve default tablespace for new database */
268 if (dtablespacename && dtablespacename->arg)
270 char *tablespacename;
273 tablespacename = strVal(dtablespacename->arg);
274 dst_deftablespace = get_tablespace_oid(tablespacename);
275 if (!OidIsValid(dst_deftablespace))
277 (errcode(ERRCODE_UNDEFINED_OBJECT),
278 errmsg("tablespace \"%s\" does not exist",
280 /* check permissions */
281 aclresult = pg_tablespace_aclcheck(dst_deftablespace, GetUserId(),
283 if (aclresult != ACLCHECK_OK)
284 aclcheck_error(aclresult, ACL_KIND_TABLESPACE,
288 * If we are trying to change the default tablespace of the template,
289 * we require that the template not have any files in the new default
290 * tablespace. This is necessary because otherwise the copied
291 * database would contain pg_class rows that refer to its default
292 * tablespace both explicitly (by OID) and implicitly (as zero), which
293 * would cause problems. For example another CREATE DATABASE using
294 * the copied database as template, and trying to change its default
295 * tablespace again, would yield outright incorrect results (it would
296 * improperly move tables to the new default tablespace that should
297 * stay in the same tablespace).
299 if (dst_deftablespace != src_deftablespace)
304 srcpath = GetDatabasePath(src_dboid, dst_deftablespace);
306 if (stat(srcpath, &st) == 0 &&
307 S_ISDIR(st.st_mode) &&
308 !directory_is_empty(srcpath))
310 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
311 errmsg("cannot assign new default tablespace \"%s\"",
313 errdetail("There is a conflict because database \"%s\" already has some tables in this tablespace.",
320 /* Use template database's default tablespace */
321 dst_deftablespace = src_deftablespace;
322 /* Note there is no additional permission check in this path */
326 * Preassign OID for pg_database tuple, so that we can compute db
332 * Force dirty buffers out to disk, to ensure source database is
333 * up-to-date for the copy. (We really only need to flush buffers for
334 * the source database, but bufmgr.c provides no API for that.)
339 * Close virtual file descriptors so the kernel has more available for
340 * the system() calls below.
345 * Iterate through all tablespaces of the template database, and copy
346 * each one to the new database.
348 rel = heap_openr(TableSpaceRelationName, AccessShareLock);
349 scan = heap_beginscan(rel, SnapshotNow, 0, NULL);
350 while ((tuple = heap_getnext(scan, ForwardScanDirection)) != NULL)
352 Oid srctablespace = HeapTupleGetOid(tuple);
358 /* No need to copy global tablespace */
359 if (srctablespace == GLOBALTABLESPACE_OID)
362 srcpath = GetDatabasePath(src_dboid, srctablespace);
364 if (stat(srcpath, &st) < 0 || !S_ISDIR(st.st_mode) ||
365 directory_is_empty(srcpath))
367 /* Assume we can ignore it */
372 if (srctablespace == src_deftablespace)
373 dsttablespace = dst_deftablespace;
375 dsttablespace = srctablespace;
377 dstpath = GetDatabasePath(dboid, dsttablespace);
379 if (stat(dstpath, &st) == 0 || errno != ENOENT)
381 remove_dbtablespaces(dboid);
383 (errmsg("could not initialize database directory"),
384 errdetail("Directory \"%s\" already exists.",
391 * Copy this subdirectory to the new location
393 * XXX use of cp really makes this code pretty grotty, particularly
394 * with respect to lack of ability to report errors well. Someday
395 * rewrite to do it for ourselves.
398 /* We might need to use cp -R one day for portability */
399 snprintf(buf, sizeof(buf), "cp -r '%s' '%s'",
401 if (system(buf) != 0)
403 remove_dbtablespaces(dboid);
405 (errmsg("could not initialize database directory"),
406 errdetail("Failing system command was: %s", buf),
407 errhint("Look in the postmaster's stderr log for more information.")));
410 if (copydir(srcpath, dstpath) != 0)
412 /* copydir should already have given details of its troubles */
413 remove_dbtablespaces(dboid);
415 (errmsg("could not initialize database directory")));
419 /* Record the filesystem change in XLOG */
421 xl_dbase_create_rec xlrec;
422 XLogRecData rdata[3];
425 rdata[0].buffer = InvalidBuffer;
426 rdata[0].data = (char *) &xlrec;
427 rdata[0].len = offsetof(xl_dbase_create_rec, src_path);
428 rdata[0].next = &(rdata[1]);
430 rdata[1].buffer = InvalidBuffer;
431 rdata[1].data = (char *) srcpath;
432 rdata[1].len = strlen(srcpath) + 1;
433 rdata[1].next = &(rdata[2]);
435 rdata[2].buffer = InvalidBuffer;
436 rdata[2].data = (char *) dstpath;
437 rdata[2].len = strlen(dstpath) + 1;
438 rdata[2].next = NULL;
440 (void) XLogInsert(RM_DBASE_ID, XLOG_DBASE_CREATE, rdata);
444 heap_close(rel, AccessShareLock);
447 * Now OK to grab exclusive lock on pg_database.
449 pg_database_rel = heap_openr(DatabaseRelationName, AccessExclusiveLock);
451 /* Check to see if someone else created same DB name meanwhile. */
452 if (get_db_info(dbname, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL))
454 /* Don't hold lock while doing recursive remove */
455 heap_close(pg_database_rel, AccessExclusiveLock);
456 remove_dbtablespaces(dboid);
458 (errcode(ERRCODE_DUPLICATE_DATABASE),
459 errmsg("database \"%s\" already exists", dbname)));
463 * Insert a new tuple into pg_database
465 pg_database_dsc = RelationGetDescr(pg_database_rel);
468 MemSet(new_record, 0, sizeof(new_record));
469 MemSet(new_record_nulls, ' ', sizeof(new_record_nulls));
471 new_record[Anum_pg_database_datname - 1] =
472 DirectFunctionCall1(namein, CStringGetDatum(dbname));
473 new_record[Anum_pg_database_datdba - 1] = Int32GetDatum(datdba);
474 new_record[Anum_pg_database_encoding - 1] = Int32GetDatum(encoding);
475 new_record[Anum_pg_database_datistemplate - 1] = BoolGetDatum(false);
476 new_record[Anum_pg_database_datallowconn - 1] = BoolGetDatum(true);
477 new_record[Anum_pg_database_datlastsysoid - 1] = ObjectIdGetDatum(src_lastsysoid);
478 new_record[Anum_pg_database_datvacuumxid - 1] = TransactionIdGetDatum(src_vacuumxid);
479 new_record[Anum_pg_database_datfrozenxid - 1] = TransactionIdGetDatum(src_frozenxid);
480 new_record[Anum_pg_database_dattablespace - 1] = ObjectIdGetDatum(dst_deftablespace);
483 * We deliberately set datconfig and datacl to defaults (NULL), rather
484 * than copying them from the template database. Copying datacl would
485 * be a bad idea when the owner is not the same as the template's
486 * owner. It's more debatable whether datconfig should be copied.
488 new_record_nulls[Anum_pg_database_datconfig - 1] = 'n';
489 new_record_nulls[Anum_pg_database_datacl - 1] = 'n';
491 tuple = heap_formtuple(pg_database_dsc, new_record, new_record_nulls);
493 HeapTupleSetOid(tuple, dboid); /* override heap_insert's OID
496 simple_heap_insert(pg_database_rel, tuple);
499 CatalogUpdateIndexes(pg_database_rel, tuple);
502 * Force dirty buffers out to disk, so that newly-connecting backends
503 * will see the new database in pg_database right away. (They'll see
504 * an uncommitted tuple, but they don't care; see GetRawDatabaseInfo.)
506 FlushRelationBuffers(pg_database_rel, MaxBlockNumber);
508 /* Close pg_database, but keep exclusive lock till commit */
509 heap_close(pg_database_rel, NoLock);
512 * Set flag to update flat database file at commit.
514 database_file_update_needed();
522 dropdb(const char *dbname)
528 SysScanDesc pgdbscan;
532 PreventTransactionChain((void *) dbname, "DROP DATABASE");
536 if (strcmp(dbname, get_database_name(MyDatabaseId)) == 0)
538 (errcode(ERRCODE_OBJECT_IN_USE),
539 errmsg("cannot drop the currently open database")));
542 * Obtain exclusive lock on pg_database. We need this to ensure that
543 * no new backend starts up in the target database while we are
544 * deleting it. (Actually, a new backend might still manage to start
545 * up, because it will read pg_database without any locking to
546 * discover the database's OID. But it will detect its error in
547 * ReverifyMyDatabase and shut down before any serious damage is done.
550 pgdbrel = heap_openr(DatabaseRelationName, AccessExclusiveLock);
552 if (!get_db_info(dbname, &db_id, &db_owner, NULL,
553 &db_istemplate, NULL, NULL, NULL, NULL))
555 (errcode(ERRCODE_UNDEFINED_DATABASE),
556 errmsg("database \"%s\" does not exist", dbname)));
558 if (GetUserId() != db_owner && !superuser())
559 aclcheck_error(ACLCHECK_NOT_OWNER, ACL_KIND_DATABASE,
563 * Disallow dropping a DB that is marked istemplate. This is just to
564 * prevent people from accidentally dropping template0 or template1;
565 * they can do so if they're really determined ...
569 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
570 errmsg("cannot drop a template database")));
573 * Check for active backends in the target database.
575 if (DatabaseHasActiveBackends(db_id, false))
577 (errcode(ERRCODE_OBJECT_IN_USE),
578 errmsg("database \"%s\" is being accessed by other users",
582 * Find the database's tuple by OID (should be unique).
585 ObjectIdAttributeNumber,
586 BTEqualStrategyNumber, F_OIDEQ,
587 ObjectIdGetDatum(db_id));
589 pgdbscan = systable_beginscan(pgdbrel, DatabaseOidIndex, true,
590 SnapshotNow, 1, &key);
592 tup = systable_getnext(pgdbscan);
593 if (!HeapTupleIsValid(tup))
596 * This error should never come up since the existence of the
597 * database is checked earlier
599 elog(ERROR, "database \"%s\" doesn't exist despite earlier reports to the contrary",
603 /* Remove the database's tuple from pg_database */
604 simple_heap_delete(pgdbrel, &tup->t_self);
606 systable_endscan(pgdbscan);
609 * Delete any comments associated with the database
611 * NOTE: this is probably dead code since any such comments should have
612 * been in that database, not mine.
614 DeleteComments(db_id, RelationGetRelid(pgdbrel), 0);
617 * Drop pages for this database that are in the shared buffer cache.
618 * This is important to ensure that no remaining backend tries to
619 * write out a dirty buffer to the dead database later...
624 * Also, clean out any entries in the shared free space map.
626 FreeSpaceMapForgetDatabase(db_id);
629 * On Windows, force a checkpoint so that the bgwriter doesn't hold any
630 * open files, which would cause rmdir() to fail.
633 RequestCheckpoint(true);
637 * Remove all tablespace subdirs belonging to the database.
639 remove_dbtablespaces(db_id);
642 * Force dirty buffers out to disk, so that newly-connecting backends
643 * will see the database tuple marked dead in pg_database right away.
644 * (They'll see an uncommitted deletion, but they don't care; see
645 * GetRawDatabaseInfo.)
647 FlushRelationBuffers(pgdbrel, MaxBlockNumber);
649 /* Close pg_database, but keep exclusive lock till commit */
650 heap_close(pgdbrel, NoLock);
653 * Set flag to update flat database file at commit.
655 database_file_update_needed();
663 RenameDatabase(const char *oldname, const char *newname)
674 * Obtain AccessExclusiveLock so that no new session gets started
675 * while the rename is in progress.
677 rel = heap_openr(DatabaseRelationName, AccessExclusiveLock);
680 Anum_pg_database_datname,
681 BTEqualStrategyNumber, F_NAMEEQ,
682 NameGetDatum(oldname));
683 scan = systable_beginscan(rel, DatabaseNameIndex, true,
684 SnapshotNow, 1, &key);
686 tup = systable_getnext(scan);
687 if (!HeapTupleIsValid(tup))
689 (errcode(ERRCODE_UNDEFINED_DATABASE),
690 errmsg("database \"%s\" does not exist", oldname)));
693 * XXX Client applications probably store the current database
694 * somewhere, so renaming it could cause confusion. On the other
695 * hand, there may not be an actual problem besides a little
696 * confusion, so think about this and decide.
698 if (HeapTupleGetOid(tup) == MyDatabaseId)
700 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
701 errmsg("current database may not be renamed")));
704 * Make sure the database does not have active sessions. Might not be
705 * necessary, but it's consistent with other database operations.
707 if (DatabaseHasActiveBackends(HeapTupleGetOid(tup), false))
709 (errcode(ERRCODE_OBJECT_IN_USE),
710 errmsg("database \"%s\" is being accessed by other users",
713 /* make sure the new name doesn't exist */
715 Anum_pg_database_datname,
716 BTEqualStrategyNumber, F_NAMEEQ,
717 NameGetDatum(newname));
718 scan2 = systable_beginscan(rel, DatabaseNameIndex, true,
719 SnapshotNow, 1, &key2);
720 if (HeapTupleIsValid(systable_getnext(scan2)))
722 (errcode(ERRCODE_DUPLICATE_DATABASE),
723 errmsg("database \"%s\" already exists", newname)));
724 systable_endscan(scan2);
727 if (!pg_database_ownercheck(HeapTupleGetOid(tup), GetUserId()))
728 aclcheck_error(ACLCHECK_NOT_OWNER, ACL_KIND_DATABASE,
731 /* must have createdb */
732 if (!have_createdb_privilege())
734 (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
735 errmsg("permission denied to rename database")));
738 newtup = heap_copytuple(tup);
739 namestrcpy(&(((Form_pg_database) GETSTRUCT(newtup))->datname), newname);
740 simple_heap_update(rel, &newtup->t_self, newtup);
741 CatalogUpdateIndexes(rel, newtup);
743 systable_endscan(scan);
746 * Force dirty buffers out to disk, so that newly-connecting backends
747 * will see the renamed database in pg_database right away. (They'll
748 * see an uncommitted tuple, but they don't care; see
749 * GetRawDatabaseInfo.)
751 FlushRelationBuffers(rel, MaxBlockNumber);
753 /* Close pg_database, but keep exclusive lock till commit */
754 heap_close(rel, NoLock);
757 * Set flag to update flat database file at commit.
759 database_file_update_needed();
764 * ALTER DATABASE name SET ...
767 AlterDatabaseSet(AlterDatabaseSetStmt *stmt)
775 Datum repl_val[Natts_pg_database];
776 char repl_null[Natts_pg_database];
777 char repl_repl[Natts_pg_database];
779 valuestr = flatten_set_variable_args(stmt->variable, stmt->value);
782 * We need AccessExclusiveLock so we can safely do FlushRelationBuffers.
784 rel = heap_openr(DatabaseRelationName, AccessExclusiveLock);
785 ScanKeyInit(&scankey,
786 Anum_pg_database_datname,
787 BTEqualStrategyNumber, F_NAMEEQ,
788 NameGetDatum(stmt->dbname));
789 scan = systable_beginscan(rel, DatabaseNameIndex, true,
790 SnapshotNow, 1, &scankey);
791 tuple = systable_getnext(scan);
792 if (!HeapTupleIsValid(tuple))
794 (errcode(ERRCODE_UNDEFINED_DATABASE),
795 errmsg("database \"%s\" does not exist", stmt->dbname)));
798 || ((Form_pg_database) GETSTRUCT(tuple))->datdba == GetUserId()))
799 aclcheck_error(ACLCHECK_NOT_OWNER, ACL_KIND_DATABASE,
802 MemSet(repl_repl, ' ', sizeof(repl_repl));
803 repl_repl[Anum_pg_database_datconfig - 1] = 'r';
805 if (strcmp(stmt->variable, "all") == 0 && valuestr == NULL)
808 repl_null[Anum_pg_database_datconfig - 1] = 'n';
809 repl_val[Anum_pg_database_datconfig - 1] = (Datum) 0;
817 repl_null[Anum_pg_database_datconfig - 1] = ' ';
819 datum = heap_getattr(tuple, Anum_pg_database_datconfig,
820 RelationGetDescr(rel), &isnull);
822 a = isnull ? NULL : DatumGetArrayTypeP(datum);
825 a = GUCArrayAdd(a, stmt->variable, valuestr);
827 a = GUCArrayDelete(a, stmt->variable);
830 repl_val[Anum_pg_database_datconfig - 1] = PointerGetDatum(a);
832 repl_null[Anum_pg_database_datconfig - 1] = 'n';
835 newtuple = heap_modifytuple(tuple, RelationGetDescr(rel), repl_val, repl_null, repl_repl);
836 simple_heap_update(rel, &tuple->t_self, newtuple);
839 CatalogUpdateIndexes(rel, newtuple);
841 systable_endscan(scan);
844 * Force dirty buffers out to disk, so that newly-connecting backends
845 * will see the altered row in pg_database right away. (They'll
846 * see an uncommitted tuple, but they don't care; see
847 * GetRawDatabaseInfo.)
849 FlushRelationBuffers(rel, MaxBlockNumber);
851 /* Close pg_database, but keep exclusive lock till commit */
852 heap_close(rel, NoLock);
855 * We don't bother updating the flat file since ALTER DATABASE SET
862 * ALTER DATABASE name OWNER TO newowner
865 AlterDatabaseOwner(const char *dbname, AclId newOwnerSysId)
871 Form_pg_database datForm;
874 * We need AccessExclusiveLock so we can safely do FlushRelationBuffers.
876 rel = heap_openr(DatabaseRelationName, AccessExclusiveLock);
877 ScanKeyInit(&scankey,
878 Anum_pg_database_datname,
879 BTEqualStrategyNumber, F_NAMEEQ,
880 NameGetDatum(dbname));
881 scan = systable_beginscan(rel, DatabaseNameIndex, true,
882 SnapshotNow, 1, &scankey);
883 tuple = systable_getnext(scan);
884 if (!HeapTupleIsValid(tuple))
886 (errcode(ERRCODE_UNDEFINED_DATABASE),
887 errmsg("database \"%s\" does not exist", dbname)));
889 datForm = (Form_pg_database) GETSTRUCT(tuple);
892 * If the new owner is the same as the existing owner, consider the
893 * command to have succeeded. This is to be consistent with other
896 if (datForm->datdba != newOwnerSysId)
898 Datum repl_val[Natts_pg_database];
899 char repl_null[Natts_pg_database];
900 char repl_repl[Natts_pg_database];
906 /* changing owner's database for someone else: must be superuser */
907 /* note that the someone else need not have any permissions */
910 (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
911 errmsg("must be superuser to change owner")));
913 memset(repl_null, ' ', sizeof(repl_null));
914 memset(repl_repl, ' ', sizeof(repl_repl));
916 repl_repl[Anum_pg_database_datdba - 1] = 'r';
917 repl_val[Anum_pg_database_datdba - 1] = Int32GetDatum(newOwnerSysId);
920 * Determine the modified ACL for the new owner. This is only
921 * necessary when the ACL is non-null.
923 aclDatum = heap_getattr(tuple,
924 Anum_pg_database_datacl,
925 RelationGetDescr(rel),
929 newAcl = aclnewowner(DatumGetAclP(aclDatum),
930 datForm->datdba, newOwnerSysId);
931 repl_repl[Anum_pg_database_datacl - 1] = 'r';
932 repl_val[Anum_pg_database_datacl - 1] = PointerGetDatum(newAcl);
935 newtuple = heap_modifytuple(tuple, RelationGetDescr(rel), repl_val, repl_null, repl_repl);
936 simple_heap_update(rel, &newtuple->t_self, newtuple);
937 CatalogUpdateIndexes(rel, newtuple);
939 heap_freetuple(newtuple);
941 /* must release buffer pins before FlushRelationBuffers */
942 systable_endscan(scan);
945 * Force dirty buffers out to disk, so that newly-connecting backends
946 * will see the altered row in pg_database right away. (They'll
947 * see an uncommitted tuple, but they don't care; see
948 * GetRawDatabaseInfo.)
950 FlushRelationBuffers(rel, MaxBlockNumber);
953 systable_endscan(scan);
955 /* Close pg_database, but keep exclusive lock till commit */
956 heap_close(rel, NoLock);
959 * We don't bother updating the flat file since ALTER DATABASE OWNER
970 get_db_info(const char *name, Oid *dbIdP, int4 *ownerIdP,
971 int *encodingP, bool *dbIsTemplateP, Oid *dbLastSysOidP,
972 TransactionId *dbVacuumXidP, TransactionId *dbFrozenXidP,
983 /* Caller may wish to grab a better lock on pg_database beforehand... */
984 relation = heap_openr(DatabaseRelationName, AccessShareLock);
986 ScanKeyInit(&scanKey,
987 Anum_pg_database_datname,
988 BTEqualStrategyNumber, F_NAMEEQ,
991 scan = systable_beginscan(relation, DatabaseNameIndex, true,
992 SnapshotNow, 1, &scanKey);
994 tuple = systable_getnext(scan);
996 gottuple = HeapTupleIsValid(tuple);
999 Form_pg_database dbform = (Form_pg_database) GETSTRUCT(tuple);
1001 /* oid of the database */
1003 *dbIdP = HeapTupleGetOid(tuple);
1004 /* sysid of the owner */
1006 *ownerIdP = dbform->datdba;
1007 /* character encoding */
1009 *encodingP = dbform->encoding;
1010 /* allowed as template? */
1012 *dbIsTemplateP = dbform->datistemplate;
1013 /* last system OID used in database */
1015 *dbLastSysOidP = dbform->datlastsysoid;
1016 /* limit of vacuumed XIDs */
1018 *dbVacuumXidP = dbform->datvacuumxid;
1019 /* limit of frozen XIDs */
1021 *dbFrozenXidP = dbform->datfrozenxid;
1022 /* default tablespace for this database */
1024 *dbTablespace = dbform->dattablespace;
1027 systable_endscan(scan);
1028 heap_close(relation, AccessShareLock);
1034 have_createdb_privilege(void)
1039 utup = SearchSysCache(SHADOWSYSID,
1040 Int32GetDatum(GetUserId()),
1043 if (!HeapTupleIsValid(utup))
1046 retval = ((Form_pg_shadow) GETSTRUCT(utup))->usecreatedb;
1048 ReleaseSysCache(utup);
1054 * Remove tablespace directories
1056 * We don't know what tablespaces db_id is using, so iterate through all
1057 * tablespaces removing <tablespace>/db_id
1060 remove_dbtablespaces(Oid db_id)
1066 rel = heap_openr(TableSpaceRelationName, AccessShareLock);
1067 scan = heap_beginscan(rel, SnapshotNow, 0, NULL);
1068 while ((tuple = heap_getnext(scan, ForwardScanDirection)) != NULL)
1070 Oid dsttablespace = HeapTupleGetOid(tuple);
1074 /* Don't mess with the global tablespace */
1075 if (dsttablespace == GLOBALTABLESPACE_OID)
1078 dstpath = GetDatabasePath(db_id, dsttablespace);
1080 if (stat(dstpath, &st) < 0 || !S_ISDIR(st.st_mode))
1082 /* Assume we can ignore it */
1087 if (!rmtree(dstpath, true))
1089 (errmsg("could not remove database directory \"%s\"",
1092 /* Record the filesystem change in XLOG */
1094 xl_dbase_drop_rec xlrec;
1095 XLogRecData rdata[2];
1097 xlrec.db_id = db_id;
1098 rdata[0].buffer = InvalidBuffer;
1099 rdata[0].data = (char *) &xlrec;
1100 rdata[0].len = offsetof(xl_dbase_drop_rec, dir_path);
1101 rdata[0].next = &(rdata[1]);
1103 rdata[1].buffer = InvalidBuffer;
1104 rdata[1].data = (char *) dstpath;
1105 rdata[1].len = strlen(dstpath) + 1;
1106 rdata[1].next = NULL;
1108 (void) XLogInsert(RM_DBASE_ID, XLOG_DBASE_DROP, rdata);
1115 heap_close(rel, AccessShareLock);
1120 * get_database_oid - given a database name, look up the OID
1122 * Returns InvalidOid if database name not found.
1124 * This is not actually used in this file, but is exported for use elsewhere.
1127 get_database_oid(const char *dbname)
1129 Relation pg_database;
1130 ScanKeyData entry[1];
1135 /* There's no syscache for pg_database, so must look the hard way */
1136 pg_database = heap_openr(DatabaseRelationName, AccessShareLock);
1137 ScanKeyInit(&entry[0],
1138 Anum_pg_database_datname,
1139 BTEqualStrategyNumber, F_NAMEEQ,
1140 CStringGetDatum(dbname));
1141 scan = systable_beginscan(pg_database, DatabaseNameIndex, true,
1142 SnapshotNow, 1, entry);
1144 dbtuple = systable_getnext(scan);
1146 /* We assume that there can be at most one matching tuple */
1147 if (HeapTupleIsValid(dbtuple))
1148 oid = HeapTupleGetOid(dbtuple);
1152 systable_endscan(scan);
1153 heap_close(pg_database, AccessShareLock);
1160 * get_database_name - given a database OID, look up the name
1162 * Returns a palloc'd string, or NULL if no such database.
1164 * This is not actually used in this file, but is exported for use elsewhere.
1167 get_database_name(Oid dbid)
1169 Relation pg_database;
1170 ScanKeyData entry[1];
1175 /* There's no syscache for pg_database, so must look the hard way */
1176 pg_database = heap_openr(DatabaseRelationName, AccessShareLock);
1177 ScanKeyInit(&entry[0],
1178 ObjectIdAttributeNumber,
1179 BTEqualStrategyNumber, F_OIDEQ,
1180 ObjectIdGetDatum(dbid));
1181 scan = systable_beginscan(pg_database, DatabaseOidIndex, true,
1182 SnapshotNow, 1, entry);
1184 dbtuple = systable_getnext(scan);
1186 /* We assume that there can be at most one matching tuple */
1187 if (HeapTupleIsValid(dbtuple))
1188 result = pstrdup(NameStr(((Form_pg_database) GETSTRUCT(dbtuple))->datname));
1192 systable_endscan(scan);
1193 heap_close(pg_database, AccessShareLock);
1199 * DATABASE resource manager's routines
1202 dbase_redo(XLogRecPtr lsn, XLogRecord *record)
1204 uint8 info = record->xl_info & ~XLR_INFO_MASK;
1206 if (info == XLOG_DBASE_CREATE)
1208 xl_dbase_create_rec *xlrec = (xl_dbase_create_rec *) XLogRecGetData(record);
1209 char *dst_path = xlrec->src_path + strlen(xlrec->src_path) + 1;
1213 char buf[2 * MAXPGPATH + 100];
1217 * Our theory for replaying a CREATE is to forcibly drop the
1218 * target subdirectory if present, then re-copy the source data.
1219 * This may be more work than needed, but it is simple to
1222 if (stat(dst_path, &st) == 0 && S_ISDIR(st.st_mode))
1224 if (!rmtree(dst_path, true))
1226 (errmsg("could not remove database directory \"%s\"",
1231 * Force dirty buffers out to disk, to ensure source database is
1232 * up-to-date for the copy. (We really only need to flush buffers for
1233 * the source database, but bufmgr.c provides no API for that.)
1240 * Copy this subdirectory to the new location
1242 * XXX use of cp really makes this code pretty grotty, particularly
1243 * with respect to lack of ability to report errors well. Someday
1244 * rewrite to do it for ourselves.
1247 /* We might need to use cp -R one day for portability */
1248 snprintf(buf, sizeof(buf), "cp -r '%s' '%s'",
1249 xlrec->src_path, dst_path);
1250 if (system(buf) != 0)
1252 (errmsg("could not initialize database directory"),
1253 errdetail("Failing system command was: %s", buf),
1254 errhint("Look in the postmaster's stderr log for more information.")));
1256 if (copydir(xlrec->src_path, dst_path) != 0)
1258 /* copydir should already have given details of its troubles */
1260 (errmsg("could not initialize database directory")));
1264 else if (info == XLOG_DBASE_DROP)
1266 xl_dbase_drop_rec *xlrec = (xl_dbase_drop_rec *) XLogRecGetData(record);
1269 * Drop pages for this database that are in the shared buffer
1272 DropBuffers(xlrec->db_id);
1274 if (!rmtree(xlrec->dir_path, true))
1276 (errmsg("could not remove database directory \"%s\"",
1280 elog(PANIC, "dbase_redo: unknown op code %u", info);
1284 dbase_undo(XLogRecPtr lsn, XLogRecord *record)
1286 elog(PANIC, "dbase_undo: unimplemented");
1290 dbase_desc(char *buf, uint8 xl_info, char *rec)
1292 uint8 info = xl_info & ~XLR_INFO_MASK;
1294 if (info == XLOG_DBASE_CREATE)
1296 xl_dbase_create_rec *xlrec = (xl_dbase_create_rec *) rec;
1297 char *dst_path = xlrec->src_path + strlen(xlrec->src_path) + 1;
1299 sprintf(buf + strlen(buf), "create db: %u copy \"%s\" to \"%s\"",
1300 xlrec->db_id, xlrec->src_path, dst_path);
1302 else if (info == XLOG_DBASE_DROP)
1304 xl_dbase_drop_rec *xlrec = (xl_dbase_drop_rec *) rec;
1306 sprintf(buf + strlen(buf), "drop db: %u directory: \"%s\"",
1307 xlrec->db_id, xlrec->dir_path);
1310 strcat(buf, "UNKNOWN");