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.153 2005/03/12 21:11:50 tgl Exp $
20 *-------------------------------------------------------------------------
28 #include "access/genam.h"
29 #include "access/heapam.h"
30 #include "catalog/catname.h"
31 #include "catalog/catalog.h"
32 #include "catalog/pg_database.h"
33 #include "catalog/pg_shadow.h"
34 #include "catalog/pg_tablespace.h"
35 #include "catalog/indexing.h"
36 #include "commands/comment.h"
37 #include "commands/dbcommands.h"
38 #include "commands/tablespace.h"
39 #include "mb/pg_wchar.h"
40 #include "miscadmin.h"
41 #include "postmaster/bgwriter.h"
42 #include "storage/fd.h"
43 #include "storage/freespace.h"
44 #include "storage/sinval.h"
45 #include "utils/acl.h"
46 #include "utils/array.h"
47 #include "utils/builtins.h"
48 #include "utils/flatfiles.h"
49 #include "utils/fmgroids.h"
50 #include "utils/guc.h"
51 #include "utils/lsyscache.h"
52 #include "utils/syscache.h"
55 /* non-export function prototypes */
56 static bool get_db_info(const char *name, Oid *dbIdP, int4 *ownerIdP,
57 int *encodingP, bool *dbIsTemplateP, Oid *dbLastSysOidP,
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)
77 TransactionId src_vacuumxid;
78 TransactionId src_frozenxid;
79 Oid src_deftablespace;
80 Oid dst_deftablespace;
81 Relation pg_database_rel;
83 TupleDesc pg_database_dsc;
84 Datum new_record[Natts_pg_database];
85 char new_record_nulls[Natts_pg_database];
89 DefElem *dtablespacename = NULL;
90 DefElem *downer = NULL;
91 DefElem *dtemplate = NULL;
92 DefElem *dencoding = NULL;
93 char *dbname = stmt->dbname;
95 char *dbtemplate = NULL;
99 char buf[2 * MAXPGPATH + 100];
102 /* don't call this in a transaction block */
103 PreventTransactionChain((void *) stmt, "CREATE DATABASE");
105 /* Extract options from the statement node tree */
106 foreach(option, stmt->options)
108 DefElem *defel = (DefElem *) lfirst(option);
110 if (strcmp(defel->defname, "tablespace") == 0)
114 (errcode(ERRCODE_SYNTAX_ERROR),
115 errmsg("conflicting or redundant options")));
116 dtablespacename = defel;
118 else if (strcmp(defel->defname, "owner") == 0)
122 (errcode(ERRCODE_SYNTAX_ERROR),
123 errmsg("conflicting or redundant options")));
126 else if (strcmp(defel->defname, "template") == 0)
130 (errcode(ERRCODE_SYNTAX_ERROR),
131 errmsg("conflicting or redundant options")));
134 else if (strcmp(defel->defname, "encoding") == 0)
138 (errcode(ERRCODE_SYNTAX_ERROR),
139 errmsg("conflicting or redundant options")));
142 else if (strcmp(defel->defname, "location") == 0)
145 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
146 errmsg("LOCATION is not supported anymore"),
147 errhint("Consider using tablespaces instead.")));
150 elog(ERROR, "option \"%s\" not recognized",
154 if (downer && downer->arg)
155 dbowner = strVal(downer->arg);
156 if (dtemplate && dtemplate->arg)
157 dbtemplate = strVal(dtemplate->arg);
158 if (dencoding && dencoding->arg)
160 const char *encoding_name;
162 if (IsA(dencoding->arg, Integer))
164 encoding = intVal(dencoding->arg);
165 encoding_name = pg_encoding_to_char(encoding);
166 if (strcmp(encoding_name, "") == 0 ||
167 pg_valid_server_encoding(encoding_name) < 0)
169 (errcode(ERRCODE_UNDEFINED_OBJECT),
170 errmsg("%d is not a valid encoding code",
173 else if (IsA(dencoding->arg, String))
175 encoding_name = strVal(dencoding->arg);
176 if (pg_valid_server_encoding(encoding_name) < 0)
178 (errcode(ERRCODE_UNDEFINED_OBJECT),
179 errmsg("%s is not a valid encoding name",
181 encoding = pg_char_to_encoding(encoding_name);
184 elog(ERROR, "unrecognized node type: %d",
185 nodeTag(dencoding->arg));
188 /* obtain sysid of proposed owner */
190 datdba = get_usesysid(dbowner); /* will ereport if no such user */
192 datdba = GetUserId();
194 if (datdba == GetUserId())
196 /* creating database for self: can be superuser or createdb */
197 if (!superuser() && !have_createdb_privilege())
199 (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
200 errmsg("permission denied to create database")));
204 /* creating database for someone else: must be superuser */
205 /* note that the someone else need not have any permissions */
208 (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
209 errmsg("must be superuser to create database for another user")));
213 * Check for db name conflict. There is a race condition here, since
214 * another backend could create the same DB name before we commit.
215 * However, holding an exclusive lock on pg_database for the whole
216 * time we are copying the source database doesn't seem like a good
217 * idea, so accept possibility of race to create. We will check again
218 * after we grab the exclusive lock.
220 if (get_db_info(dbname, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL))
222 (errcode(ERRCODE_DUPLICATE_DATABASE),
223 errmsg("database \"%s\" already exists", dbname)));
226 * Lookup database (template) to be cloned.
229 dbtemplate = "template1"; /* Default template database name */
231 if (!get_db_info(dbtemplate, &src_dboid, &src_owner, &src_encoding,
232 &src_istemplate, &src_lastsysoid,
233 &src_vacuumxid, &src_frozenxid, &src_deftablespace))
235 (errcode(ERRCODE_UNDEFINED_DATABASE),
236 errmsg("template database \"%s\" does not exist", dbtemplate)));
239 * Permission check: to copy a DB that's not marked datistemplate, you
240 * must be superuser or the owner thereof.
244 if (!superuser() && GetUserId() != src_owner)
246 (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
247 errmsg("permission denied to copy database \"%s\"",
252 * The source DB can't have any active backends, except this one
253 * (exception is to allow CREATE DB while connected to template1).
254 * Otherwise we might copy inconsistent data. This check is not
255 * bulletproof, since someone might connect while we are copying...
257 if (DatabaseHasActiveBackends(src_dboid, true))
259 (errcode(ERRCODE_OBJECT_IN_USE),
260 errmsg("source database \"%s\" is being accessed by other users",
263 /* If encoding is defaulted, use source's encoding */
265 encoding = src_encoding;
267 /* Some encodings are client only */
268 if (!PG_VALID_BE_ENCODING(encoding))
270 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
271 errmsg("invalid server encoding %d", encoding)));
273 /* Resolve default tablespace for new database */
274 if (dtablespacename && dtablespacename->arg)
276 char *tablespacename;
279 tablespacename = strVal(dtablespacename->arg);
280 dst_deftablespace = get_tablespace_oid(tablespacename);
281 if (!OidIsValid(dst_deftablespace))
283 (errcode(ERRCODE_UNDEFINED_OBJECT),
284 errmsg("tablespace \"%s\" does not exist",
286 /* check permissions */
287 aclresult = pg_tablespace_aclcheck(dst_deftablespace, GetUserId(),
289 if (aclresult != ACLCHECK_OK)
290 aclcheck_error(aclresult, ACL_KIND_TABLESPACE,
294 * If we are trying to change the default tablespace of the template,
295 * we require that the template not have any files in the new default
296 * tablespace. This is necessary because otherwise the copied
297 * database would contain pg_class rows that refer to its default
298 * tablespace both explicitly (by OID) and implicitly (as zero), which
299 * would cause problems. For example another CREATE DATABASE using
300 * the copied database as template, and trying to change its default
301 * tablespace again, would yield outright incorrect results (it would
302 * improperly move tables to the new default tablespace that should
303 * stay in the same tablespace).
305 if (dst_deftablespace != src_deftablespace)
310 srcpath = GetDatabasePath(src_dboid, dst_deftablespace);
312 if (stat(srcpath, &st) == 0 &&
313 S_ISDIR(st.st_mode) &&
314 !directory_is_empty(srcpath))
316 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
317 errmsg("cannot assign new default tablespace \"%s\"",
319 errdetail("There is a conflict because database \"%s\" already has some tables in this tablespace.",
326 /* Use template database's default tablespace */
327 dst_deftablespace = src_deftablespace;
328 /* Note there is no additional permission check in this path */
332 * Preassign OID for pg_database tuple, so that we can compute db
338 * Force dirty buffers out to disk, to ensure source database is
339 * up-to-date for the copy. (We really only need to flush buffers for
340 * the source database, but bufmgr.c provides no API for that.)
345 * Close virtual file descriptors so the kernel has more available for
346 * the system() calls below.
351 * Iterate through all tablespaces of the template database, and copy
352 * each one to the new database.
354 rel = heap_openr(TableSpaceRelationName, AccessShareLock);
355 scan = heap_beginscan(rel, SnapshotNow, 0, NULL);
356 while ((tuple = heap_getnext(scan, ForwardScanDirection)) != NULL)
358 Oid srctablespace = HeapTupleGetOid(tuple);
364 /* No need to copy global tablespace */
365 if (srctablespace == GLOBALTABLESPACE_OID)
368 srcpath = GetDatabasePath(src_dboid, srctablespace);
370 if (stat(srcpath, &st) < 0 || !S_ISDIR(st.st_mode) ||
371 directory_is_empty(srcpath))
373 /* Assume we can ignore it */
378 if (srctablespace == src_deftablespace)
379 dsttablespace = dst_deftablespace;
381 dsttablespace = srctablespace;
383 dstpath = GetDatabasePath(dboid, dsttablespace);
385 if (stat(dstpath, &st) == 0 || errno != ENOENT)
387 remove_dbtablespaces(dboid);
389 (errmsg("could not initialize database directory"),
390 errdetail("Directory \"%s\" already exists.",
397 * Copy this subdirectory to the new location
399 * XXX use of cp really makes this code pretty grotty, particularly
400 * with respect to lack of ability to report errors well. Someday
401 * rewrite to do it for ourselves.
404 /* We might need to use cp -R one day for portability */
405 snprintf(buf, sizeof(buf), "cp -r '%s' '%s'",
407 if (system(buf) != 0)
409 remove_dbtablespaces(dboid);
411 (errmsg("could not initialize database directory"),
412 errdetail("Failing system command was: %s", buf),
413 errhint("Look in the postmaster's stderr log for more information.")));
416 if (copydir(srcpath, dstpath) != 0)
418 /* copydir should already have given details of its troubles */
419 remove_dbtablespaces(dboid);
421 (errmsg("could not initialize database directory")));
425 /* Record the filesystem change in XLOG */
427 xl_dbase_create_rec xlrec;
428 XLogRecData rdata[3];
431 rdata[0].buffer = InvalidBuffer;
432 rdata[0].data = (char *) &xlrec;
433 rdata[0].len = offsetof(xl_dbase_create_rec, src_path);
434 rdata[0].next = &(rdata[1]);
436 rdata[1].buffer = InvalidBuffer;
437 rdata[1].data = (char *) srcpath;
438 rdata[1].len = strlen(srcpath) + 1;
439 rdata[1].next = &(rdata[2]);
441 rdata[2].buffer = InvalidBuffer;
442 rdata[2].data = (char *) dstpath;
443 rdata[2].len = strlen(dstpath) + 1;
444 rdata[2].next = NULL;
446 (void) XLogInsert(RM_DBASE_ID, XLOG_DBASE_CREATE, rdata);
450 heap_close(rel, AccessShareLock);
453 * Now OK to grab exclusive lock on pg_database.
455 pg_database_rel = heap_openr(DatabaseRelationName, ExclusiveLock);
457 /* Check to see if someone else created same DB name meanwhile. */
458 if (get_db_info(dbname, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL))
460 /* Don't hold lock while doing recursive remove */
461 heap_close(pg_database_rel, ExclusiveLock);
462 remove_dbtablespaces(dboid);
464 (errcode(ERRCODE_DUPLICATE_DATABASE),
465 errmsg("database \"%s\" already exists", dbname)));
469 * Insert a new tuple into pg_database
471 pg_database_dsc = RelationGetDescr(pg_database_rel);
474 MemSet(new_record, 0, sizeof(new_record));
475 MemSet(new_record_nulls, ' ', sizeof(new_record_nulls));
477 new_record[Anum_pg_database_datname - 1] =
478 DirectFunctionCall1(namein, CStringGetDatum(dbname));
479 new_record[Anum_pg_database_datdba - 1] = Int32GetDatum(datdba);
480 new_record[Anum_pg_database_encoding - 1] = Int32GetDatum(encoding);
481 new_record[Anum_pg_database_datistemplate - 1] = BoolGetDatum(false);
482 new_record[Anum_pg_database_datallowconn - 1] = BoolGetDatum(true);
483 new_record[Anum_pg_database_datlastsysoid - 1] = ObjectIdGetDatum(src_lastsysoid);
484 new_record[Anum_pg_database_datvacuumxid - 1] = TransactionIdGetDatum(src_vacuumxid);
485 new_record[Anum_pg_database_datfrozenxid - 1] = TransactionIdGetDatum(src_frozenxid);
486 new_record[Anum_pg_database_dattablespace - 1] = ObjectIdGetDatum(dst_deftablespace);
489 * We deliberately set datconfig and datacl to defaults (NULL), rather
490 * than copying them from the template database. Copying datacl would
491 * be a bad idea when the owner is not the same as the template's
492 * owner. It's more debatable whether datconfig should be copied.
494 new_record_nulls[Anum_pg_database_datconfig - 1] = 'n';
495 new_record_nulls[Anum_pg_database_datacl - 1] = 'n';
497 tuple = heap_formtuple(pg_database_dsc, new_record, new_record_nulls);
499 HeapTupleSetOid(tuple, dboid); /* override heap_insert's OID
502 simple_heap_insert(pg_database_rel, tuple);
505 CatalogUpdateIndexes(pg_database_rel, tuple);
507 /* Close pg_database, but keep exclusive lock till commit */
508 heap_close(pg_database_rel, NoLock);
511 * Set flag to update flat database file at commit.
513 database_file_update_needed();
521 dropdb(const char *dbname)
527 SysScanDesc pgdbscan;
531 PreventTransactionChain((void *) dbname, "DROP DATABASE");
535 if (strcmp(dbname, get_database_name(MyDatabaseId)) == 0)
537 (errcode(ERRCODE_OBJECT_IN_USE),
538 errmsg("cannot drop the currently open database")));
541 * Obtain exclusive lock on pg_database. We need this to ensure that
542 * no new backend starts up in the target database while we are
543 * deleting it. (Actually, a new backend might still manage to start
544 * up, because it isn't able to lock pg_database while starting. But
545 * it will detect its error in ReverifyMyDatabase and shut down before
546 * any serious damage is done. See postinit.c.)
548 * An ExclusiveLock, rather than AccessExclusiveLock, is sufficient
549 * since ReverifyMyDatabase takes RowShareLock. This allows ordinary
550 * readers of pg_database to proceed in parallel.
552 pgdbrel = heap_openr(DatabaseRelationName, ExclusiveLock);
554 if (!get_db_info(dbname, &db_id, &db_owner, NULL,
555 &db_istemplate, NULL, NULL, NULL, NULL))
557 (errcode(ERRCODE_UNDEFINED_DATABASE),
558 errmsg("database \"%s\" does not exist", dbname)));
560 if (GetUserId() != db_owner && !superuser())
561 aclcheck_error(ACLCHECK_NOT_OWNER, ACL_KIND_DATABASE,
565 * Disallow dropping a DB that is marked istemplate. This is just to
566 * prevent people from accidentally dropping template0 or template1;
567 * they can do so if they're really determined ...
571 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
572 errmsg("cannot drop a template database")));
575 * Check for active backends in the target database.
577 if (DatabaseHasActiveBackends(db_id, false))
579 (errcode(ERRCODE_OBJECT_IN_USE),
580 errmsg("database \"%s\" is being accessed by other users",
584 * Find the database's tuple by OID (should be unique).
587 ObjectIdAttributeNumber,
588 BTEqualStrategyNumber, F_OIDEQ,
589 ObjectIdGetDatum(db_id));
591 pgdbscan = systable_beginscan(pgdbrel, DatabaseOidIndex, true,
592 SnapshotNow, 1, &key);
594 tup = systable_getnext(pgdbscan);
595 if (!HeapTupleIsValid(tup))
598 * This error should never come up since the existence of the
599 * database is checked earlier
601 elog(ERROR, "database \"%s\" doesn't exist despite earlier reports to the contrary",
605 /* Remove the database's tuple from pg_database */
606 simple_heap_delete(pgdbrel, &tup->t_self);
608 systable_endscan(pgdbscan);
611 * Delete any comments associated with the database
613 * NOTE: this is probably dead code since any such comments should have
614 * been in that database, not mine.
616 DeleteComments(db_id, RelationGetRelid(pgdbrel), 0);
619 * Drop pages for this database that are in the shared buffer cache.
620 * This is important to ensure that no remaining backend tries to
621 * write out a dirty buffer to the dead database later...
626 * Also, clean out any entries in the shared free space map.
628 FreeSpaceMapForgetDatabase(db_id);
631 * On Windows, force a checkpoint so that the bgwriter doesn't hold any
632 * open files, which would cause rmdir() to fail.
635 RequestCheckpoint(true);
639 * Remove all tablespace subdirs belonging to the database.
641 remove_dbtablespaces(db_id);
643 /* Close pg_database, but keep exclusive lock till commit */
644 heap_close(pgdbrel, NoLock);
647 * Set flag to update flat database file at commit.
649 database_file_update_needed();
657 RenameDatabase(const char *oldname, const char *newname)
668 * Obtain ExclusiveLock so that no new session gets started
669 * while the rename is in progress.
671 rel = heap_openr(DatabaseRelationName, ExclusiveLock);
674 Anum_pg_database_datname,
675 BTEqualStrategyNumber, F_NAMEEQ,
676 NameGetDatum(oldname));
677 scan = systable_beginscan(rel, DatabaseNameIndex, true,
678 SnapshotNow, 1, &key);
680 tup = systable_getnext(scan);
681 if (!HeapTupleIsValid(tup))
683 (errcode(ERRCODE_UNDEFINED_DATABASE),
684 errmsg("database \"%s\" does not exist", oldname)));
687 * XXX Client applications probably store the current database
688 * somewhere, so renaming it could cause confusion. On the other
689 * hand, there may not be an actual problem besides a little
690 * confusion, so think about this and decide.
692 if (HeapTupleGetOid(tup) == MyDatabaseId)
694 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
695 errmsg("current database may not be renamed")));
698 * Make sure the database does not have active sessions. Might not be
699 * necessary, but it's consistent with other database operations.
701 if (DatabaseHasActiveBackends(HeapTupleGetOid(tup), false))
703 (errcode(ERRCODE_OBJECT_IN_USE),
704 errmsg("database \"%s\" is being accessed by other users",
707 /* make sure the new name doesn't exist */
709 Anum_pg_database_datname,
710 BTEqualStrategyNumber, F_NAMEEQ,
711 NameGetDatum(newname));
712 scan2 = systable_beginscan(rel, DatabaseNameIndex, true,
713 SnapshotNow, 1, &key2);
714 if (HeapTupleIsValid(systable_getnext(scan2)))
716 (errcode(ERRCODE_DUPLICATE_DATABASE),
717 errmsg("database \"%s\" already exists", newname)));
718 systable_endscan(scan2);
721 if (!pg_database_ownercheck(HeapTupleGetOid(tup), GetUserId()))
722 aclcheck_error(ACLCHECK_NOT_OWNER, ACL_KIND_DATABASE,
725 /* must have createdb rights */
726 if (!superuser() && !have_createdb_privilege())
728 (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
729 errmsg("permission denied to rename database")));
732 newtup = heap_copytuple(tup);
733 namestrcpy(&(((Form_pg_database) GETSTRUCT(newtup))->datname), newname);
734 simple_heap_update(rel, &newtup->t_self, newtup);
735 CatalogUpdateIndexes(rel, newtup);
737 systable_endscan(scan);
739 /* Close pg_database, but keep exclusive lock till commit */
740 heap_close(rel, NoLock);
743 * Set flag to update flat database file at commit.
745 database_file_update_needed();
750 * ALTER DATABASE name SET ...
753 AlterDatabaseSet(AlterDatabaseSetStmt *stmt)
761 Datum repl_val[Natts_pg_database];
762 char repl_null[Natts_pg_database];
763 char repl_repl[Natts_pg_database];
765 valuestr = flatten_set_variable_args(stmt->variable, stmt->value);
768 * We don't need ExclusiveLock since we aren't updating the
771 rel = heap_openr(DatabaseRelationName, RowExclusiveLock);
772 ScanKeyInit(&scankey,
773 Anum_pg_database_datname,
774 BTEqualStrategyNumber, F_NAMEEQ,
775 NameGetDatum(stmt->dbname));
776 scan = systable_beginscan(rel, DatabaseNameIndex, true,
777 SnapshotNow, 1, &scankey);
778 tuple = systable_getnext(scan);
779 if (!HeapTupleIsValid(tuple))
781 (errcode(ERRCODE_UNDEFINED_DATABASE),
782 errmsg("database \"%s\" does not exist", stmt->dbname)));
785 || ((Form_pg_database) GETSTRUCT(tuple))->datdba == GetUserId()))
786 aclcheck_error(ACLCHECK_NOT_OWNER, ACL_KIND_DATABASE,
789 MemSet(repl_repl, ' ', sizeof(repl_repl));
790 repl_repl[Anum_pg_database_datconfig - 1] = 'r';
792 if (strcmp(stmt->variable, "all") == 0 && valuestr == NULL)
795 repl_null[Anum_pg_database_datconfig - 1] = 'n';
796 repl_val[Anum_pg_database_datconfig - 1] = (Datum) 0;
804 repl_null[Anum_pg_database_datconfig - 1] = ' ';
806 datum = heap_getattr(tuple, Anum_pg_database_datconfig,
807 RelationGetDescr(rel), &isnull);
809 a = isnull ? NULL : DatumGetArrayTypeP(datum);
812 a = GUCArrayAdd(a, stmt->variable, valuestr);
814 a = GUCArrayDelete(a, stmt->variable);
817 repl_val[Anum_pg_database_datconfig - 1] = PointerGetDatum(a);
819 repl_null[Anum_pg_database_datconfig - 1] = 'n';
822 newtuple = heap_modifytuple(tuple, RelationGetDescr(rel), repl_val, repl_null, repl_repl);
823 simple_heap_update(rel, &tuple->t_self, newtuple);
826 CatalogUpdateIndexes(rel, newtuple);
828 systable_endscan(scan);
830 /* Close pg_database, but keep lock till commit */
831 heap_close(rel, NoLock);
834 * We don't bother updating the flat file since ALTER DATABASE SET
841 * ALTER DATABASE name OWNER TO newowner
844 AlterDatabaseOwner(const char *dbname, AclId newOwnerSysId)
850 Form_pg_database datForm;
853 * We don't need ExclusiveLock since we aren't updating the
856 rel = heap_openr(DatabaseRelationName, RowExclusiveLock);
857 ScanKeyInit(&scankey,
858 Anum_pg_database_datname,
859 BTEqualStrategyNumber, F_NAMEEQ,
860 NameGetDatum(dbname));
861 scan = systable_beginscan(rel, DatabaseNameIndex, true,
862 SnapshotNow, 1, &scankey);
863 tuple = systable_getnext(scan);
864 if (!HeapTupleIsValid(tuple))
866 (errcode(ERRCODE_UNDEFINED_DATABASE),
867 errmsg("database \"%s\" does not exist", dbname)));
869 datForm = (Form_pg_database) GETSTRUCT(tuple);
872 * If the new owner is the same as the existing owner, consider the
873 * command to have succeeded. This is to be consistent with other
876 if (datForm->datdba != newOwnerSysId)
878 Datum repl_val[Natts_pg_database];
879 char repl_null[Natts_pg_database];
880 char repl_repl[Natts_pg_database];
886 /* must be superuser to change ownership */
889 (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
890 errmsg("must be superuser to change owner")));
892 memset(repl_null, ' ', sizeof(repl_null));
893 memset(repl_repl, ' ', sizeof(repl_repl));
895 repl_repl[Anum_pg_database_datdba - 1] = 'r';
896 repl_val[Anum_pg_database_datdba - 1] = Int32GetDatum(newOwnerSysId);
899 * Determine the modified ACL for the new owner. This is only
900 * necessary when the ACL is non-null.
902 aclDatum = heap_getattr(tuple,
903 Anum_pg_database_datacl,
904 RelationGetDescr(rel),
908 newAcl = aclnewowner(DatumGetAclP(aclDatum),
909 datForm->datdba, newOwnerSysId);
910 repl_repl[Anum_pg_database_datacl - 1] = 'r';
911 repl_val[Anum_pg_database_datacl - 1] = PointerGetDatum(newAcl);
914 newtuple = heap_modifytuple(tuple, RelationGetDescr(rel), repl_val, repl_null, repl_repl);
915 simple_heap_update(rel, &newtuple->t_self, newtuple);
916 CatalogUpdateIndexes(rel, newtuple);
918 heap_freetuple(newtuple);
921 systable_endscan(scan);
923 /* Close pg_database, but keep lock till commit */
924 heap_close(rel, NoLock);
927 * We don't bother updating the flat file since ALTER DATABASE OWNER
938 get_db_info(const char *name, Oid *dbIdP, int4 *ownerIdP,
939 int *encodingP, bool *dbIsTemplateP, Oid *dbLastSysOidP,
940 TransactionId *dbVacuumXidP, TransactionId *dbFrozenXidP,
951 /* Caller may wish to grab a better lock on pg_database beforehand... */
952 relation = heap_openr(DatabaseRelationName, AccessShareLock);
954 ScanKeyInit(&scanKey,
955 Anum_pg_database_datname,
956 BTEqualStrategyNumber, F_NAMEEQ,
959 scan = systable_beginscan(relation, DatabaseNameIndex, true,
960 SnapshotNow, 1, &scanKey);
962 tuple = systable_getnext(scan);
964 gottuple = HeapTupleIsValid(tuple);
967 Form_pg_database dbform = (Form_pg_database) GETSTRUCT(tuple);
969 /* oid of the database */
971 *dbIdP = HeapTupleGetOid(tuple);
972 /* sysid of the owner */
974 *ownerIdP = dbform->datdba;
975 /* character encoding */
977 *encodingP = dbform->encoding;
978 /* allowed as template? */
980 *dbIsTemplateP = dbform->datistemplate;
981 /* last system OID used in database */
983 *dbLastSysOidP = dbform->datlastsysoid;
984 /* limit of vacuumed XIDs */
986 *dbVacuumXidP = dbform->datvacuumxid;
987 /* limit of frozen XIDs */
989 *dbFrozenXidP = dbform->datfrozenxid;
990 /* default tablespace for this database */
992 *dbTablespace = dbform->dattablespace;
995 systable_endscan(scan);
996 heap_close(relation, AccessShareLock);
1001 /* Check if current user has createdb privileges */
1003 have_createdb_privilege(void)
1005 bool result = false;
1008 utup = SearchSysCache(SHADOWSYSID,
1009 Int32GetDatum(GetUserId()),
1011 if (HeapTupleIsValid(utup))
1013 result = ((Form_pg_shadow) GETSTRUCT(utup))->usecreatedb;
1014 ReleaseSysCache(utup);
1020 * Remove tablespace directories
1022 * We don't know what tablespaces db_id is using, so iterate through all
1023 * tablespaces removing <tablespace>/db_id
1026 remove_dbtablespaces(Oid db_id)
1032 rel = heap_openr(TableSpaceRelationName, AccessShareLock);
1033 scan = heap_beginscan(rel, SnapshotNow, 0, NULL);
1034 while ((tuple = heap_getnext(scan, ForwardScanDirection)) != NULL)
1036 Oid dsttablespace = HeapTupleGetOid(tuple);
1040 /* Don't mess with the global tablespace */
1041 if (dsttablespace == GLOBALTABLESPACE_OID)
1044 dstpath = GetDatabasePath(db_id, dsttablespace);
1046 if (stat(dstpath, &st) < 0 || !S_ISDIR(st.st_mode))
1048 /* Assume we can ignore it */
1053 if (!rmtree(dstpath, true))
1055 (errmsg("could not remove database directory \"%s\"",
1058 /* Record the filesystem change in XLOG */
1060 xl_dbase_drop_rec xlrec;
1061 XLogRecData rdata[2];
1063 xlrec.db_id = db_id;
1064 rdata[0].buffer = InvalidBuffer;
1065 rdata[0].data = (char *) &xlrec;
1066 rdata[0].len = offsetof(xl_dbase_drop_rec, dir_path);
1067 rdata[0].next = &(rdata[1]);
1069 rdata[1].buffer = InvalidBuffer;
1070 rdata[1].data = (char *) dstpath;
1071 rdata[1].len = strlen(dstpath) + 1;
1072 rdata[1].next = NULL;
1074 (void) XLogInsert(RM_DBASE_ID, XLOG_DBASE_DROP, rdata);
1081 heap_close(rel, AccessShareLock);
1086 * get_database_oid - given a database name, look up the OID
1088 * Returns InvalidOid if database name not found.
1090 * This is not actually used in this file, but is exported for use elsewhere.
1093 get_database_oid(const char *dbname)
1095 Relation pg_database;
1096 ScanKeyData entry[1];
1101 /* There's no syscache for pg_database, so must look the hard way */
1102 pg_database = heap_openr(DatabaseRelationName, AccessShareLock);
1103 ScanKeyInit(&entry[0],
1104 Anum_pg_database_datname,
1105 BTEqualStrategyNumber, F_NAMEEQ,
1106 CStringGetDatum(dbname));
1107 scan = systable_beginscan(pg_database, DatabaseNameIndex, true,
1108 SnapshotNow, 1, entry);
1110 dbtuple = systable_getnext(scan);
1112 /* We assume that there can be at most one matching tuple */
1113 if (HeapTupleIsValid(dbtuple))
1114 oid = HeapTupleGetOid(dbtuple);
1118 systable_endscan(scan);
1119 heap_close(pg_database, AccessShareLock);
1126 * get_database_name - given a database OID, look up the name
1128 * Returns a palloc'd string, or NULL if no such database.
1130 * This is not actually used in this file, but is exported for use elsewhere.
1133 get_database_name(Oid dbid)
1135 Relation pg_database;
1136 ScanKeyData entry[1];
1141 /* There's no syscache for pg_database, so must look the hard way */
1142 pg_database = heap_openr(DatabaseRelationName, AccessShareLock);
1143 ScanKeyInit(&entry[0],
1144 ObjectIdAttributeNumber,
1145 BTEqualStrategyNumber, F_OIDEQ,
1146 ObjectIdGetDatum(dbid));
1147 scan = systable_beginscan(pg_database, DatabaseOidIndex, true,
1148 SnapshotNow, 1, entry);
1150 dbtuple = systable_getnext(scan);
1152 /* We assume that there can be at most one matching tuple */
1153 if (HeapTupleIsValid(dbtuple))
1154 result = pstrdup(NameStr(((Form_pg_database) GETSTRUCT(dbtuple))->datname));
1158 systable_endscan(scan);
1159 heap_close(pg_database, AccessShareLock);
1165 * DATABASE resource manager's routines
1168 dbase_redo(XLogRecPtr lsn, XLogRecord *record)
1170 uint8 info = record->xl_info & ~XLR_INFO_MASK;
1172 if (info == XLOG_DBASE_CREATE)
1174 xl_dbase_create_rec *xlrec = (xl_dbase_create_rec *) XLogRecGetData(record);
1175 char *dst_path = xlrec->src_path + strlen(xlrec->src_path) + 1;
1179 char buf[2 * MAXPGPATH + 100];
1183 * Our theory for replaying a CREATE is to forcibly drop the
1184 * target subdirectory if present, then re-copy the source data.
1185 * This may be more work than needed, but it is simple to
1188 if (stat(dst_path, &st) == 0 && S_ISDIR(st.st_mode))
1190 if (!rmtree(dst_path, true))
1192 (errmsg("could not remove database directory \"%s\"",
1197 * Force dirty buffers out to disk, to ensure source database is
1198 * up-to-date for the copy. (We really only need to flush buffers for
1199 * the source database, but bufmgr.c provides no API for that.)
1206 * Copy this subdirectory to the new location
1208 * XXX use of cp really makes this code pretty grotty, particularly
1209 * with respect to lack of ability to report errors well. Someday
1210 * rewrite to do it for ourselves.
1213 /* We might need to use cp -R one day for portability */
1214 snprintf(buf, sizeof(buf), "cp -r '%s' '%s'",
1215 xlrec->src_path, dst_path);
1216 if (system(buf) != 0)
1218 (errmsg("could not initialize database directory"),
1219 errdetail("Failing system command was: %s", buf),
1220 errhint("Look in the postmaster's stderr log for more information.")));
1222 if (copydir(xlrec->src_path, dst_path) != 0)
1224 /* copydir should already have given details of its troubles */
1226 (errmsg("could not initialize database directory")));
1230 else if (info == XLOG_DBASE_DROP)
1232 xl_dbase_drop_rec *xlrec = (xl_dbase_drop_rec *) XLogRecGetData(record);
1235 * Drop pages for this database that are in the shared buffer
1238 DropBuffers(xlrec->db_id);
1240 if (!rmtree(xlrec->dir_path, true))
1242 (errmsg("could not remove database directory \"%s\"",
1246 elog(PANIC, "dbase_redo: unknown op code %u", info);
1250 dbase_undo(XLogRecPtr lsn, XLogRecord *record)
1252 elog(PANIC, "dbase_undo: unimplemented");
1256 dbase_desc(char *buf, uint8 xl_info, char *rec)
1258 uint8 info = xl_info & ~XLR_INFO_MASK;
1260 if (info == XLOG_DBASE_CREATE)
1262 xl_dbase_create_rec *xlrec = (xl_dbase_create_rec *) rec;
1263 char *dst_path = xlrec->src_path + strlen(xlrec->src_path) + 1;
1265 sprintf(buf + strlen(buf), "create db: %u copy \"%s\" to \"%s\"",
1266 xlrec->db_id, xlrec->src_path, dst_path);
1268 else if (info == XLOG_DBASE_DROP)
1270 xl_dbase_drop_rec *xlrec = (xl_dbase_drop_rec *) rec;
1272 sprintf(buf + strlen(buf), "drop db: %u directory: \"%s\"",
1273 xlrec->db_id, xlrec->dir_path);
1276 strcat(buf, "UNKNOWN");