LCOV - differential code coverage report
Current view: top level - src/backend/commands - dbcommands.c (source / functions) Coverage Total Hit UNC UBC GBC GNC CBC DCB
Current: 4b3c9325757dfd8f2312e9f1a8decf4431f344ae vs e87b024bfb8dd55e3049b1b6e6ab4e810cf1abc8 Lines: 85.3 % 1132 966 1 165 3 7 956 4
Current Date: 2026-11-28 16:48:44 +0900 Functions: 96.6 % 29 28 1 6 22
Baseline: lcov-20261128-baseline Branches: 58.6 % 986 578 5 403 2 5 571
Baseline Date: 2026-11-28 16:48:48 +0900 Line coverage date bins:
Legend: Lines:     hit not hit
Branches: + taken - not taken # not executed
(7,30] days: 100.0 % 8 8 1 7
(30,360] days: 84.6 % 13 11 1 1 6 5
(360..) days: 85.2 % 1111 947 164 3 944
Function coverage date bins:
(360..) days: 96.6 % 29 28 1 6 22
Branch coverage date bins:
(7,30] days: 81.2 % 16 13 3 13
(30,360] days: 50.0 % 18 9 5 4 5 4
(360..) days: 58.4 % 952 556 396 2 554

 Age         Owner                    Branch data    TLA  Line data    Source code
                                  1                 :                : /*-------------------------------------------------------------------------
                                  2                 :                :  *
                                  3                 :                :  * dbcommands.c
                                  4                 :                :  *      Database management commands (create/drop database).
                                  5                 :                :  *
                                  6                 :                :  * Note: database creation/destruction commands use exclusive locks on
                                  7                 :                :  * the database objects (as expressed by LockSharedObject()) to avoid
                                  8                 :                :  * stepping on each others' toes.  Formerly we used table-level locks
                                  9                 :                :  * on pg_database, but that's too coarse-grained.
                                 10                 :                :  *
                                 11                 :                :  * Portions Copyright (c) 1996-2026, PostgreSQL Global Development Group
                                 12                 :                :  * Portions Copyright (c) 1994, Regents of the University of California
                                 13                 :                :  *
                                 14                 :                :  *
                                 15                 :                :  * IDENTIFICATION
                                 16                 :                :  *    src/backend/commands/dbcommands.c
                                 17                 :                :  *
                                 18                 :                :  *-------------------------------------------------------------------------
                                 19                 :                :  */
                                 20                 :                : #include "postgres.h"
                                 21                 :                : 
                                 22                 :                : #include <fcntl.h>
                                 23                 :                : #include <unistd.h>
                                 24                 :                : #include <sys/stat.h>
                                 25                 :                : 
                                 26                 :                : #include "access/genam.h"
                                 27                 :                : #include "access/heapam.h"
                                 28                 :                : #include "access/htup_details.h"
                                 29                 :                : #include "access/multixact.h"
                                 30                 :                : #include "access/tableam.h"
                                 31                 :                : #include "access/xact.h"
                                 32                 :                : #include "access/xloginsert.h"
                                 33                 :                : #include "access/xlogrecovery.h"
                                 34                 :                : #include "access/xlogutils.h"
                                 35                 :                : #include "catalog/catalog.h"
                                 36                 :                : #include "catalog/dependency.h"
                                 37                 :                : #include "catalog/indexing.h"
                                 38                 :                : #include "catalog/objectaccess.h"
                                 39                 :                : #include "catalog/pg_am_d.h"
                                 40                 :                : #include "catalog/pg_authid.h"
                                 41                 :                : #include "catalog/pg_collation.h"
                                 42                 :                : #include "catalog/pg_database.h"
                                 43                 :                : #include "catalog/pg_db_role_setting.h"
                                 44                 :                : #include "catalog/pg_subscription.h"
                                 45                 :                : #include "catalog/pg_tablespace.h"
                                 46                 :                : #include "commands/comment.h"
                                 47                 :                : #include "commands/dbcommands.h"
                                 48                 :                : #include "commands/dbcommands_xlog.h"
                                 49                 :                : #include "commands/defrem.h"
                                 50                 :                : #include "commands/seclabel.h"
                                 51                 :                : #include "commands/tablespace.h"
                                 52                 :                : #include "common/file_perm.h"
                                 53                 :                : #include "mb/pg_wchar.h"
                                 54                 :                : #include "miscadmin.h"
                                 55                 :                : #include "pgstat.h"
                                 56                 :                : #include "postmaster/bgwriter.h"
                                 57                 :                : #include "replication/slot.h"
                                 58                 :                : #include "storage/copydir.h"
                                 59                 :                : #include "storage/fd.h"
                                 60                 :                : #include "storage/ipc.h"
                                 61                 :                : #include "storage/lmgr.h"
                                 62                 :                : #include "storage/md.h"
                                 63                 :                : #include "storage/procarray.h"
                                 64                 :                : #include "storage/procsignal.h"
                                 65                 :                : #include "storage/smgr.h"
                                 66                 :                : #include "utils/acl.h"
                                 67                 :                : #include "utils/builtins.h"
                                 68                 :                : #include "utils/fmgroids.h"
                                 69                 :                : #include "utils/injection_point.h"
                                 70                 :                : #include "utils/lsyscache.h"
                                 71                 :                : #include "utils/pg_locale.h"
                                 72                 :                : #include "utils/relmapper.h"
                                 73                 :                : #include "utils/snapmgr.h"
                                 74                 :                : #include "utils/syscache.h"
                                 75                 :                : #include "utils/wait_event.h"
                                 76                 :                : 
                                 77                 :                : /*
                                 78                 :                :  * Create database strategy.
                                 79                 :                :  *
                                 80                 :                :  * CREATEDB_WAL_LOG will copy the database at the block level and WAL log each
                                 81                 :                :  * copied block.
                                 82                 :                :  *
                                 83                 :                :  * CREATEDB_FILE_COPY will simply perform a file system level copy of the
                                 84                 :                :  * database and log a single record for each tablespace copied. To make this
                                 85                 :                :  * safe, it also triggers checkpoints before and after the operation.
                                 86                 :                :  */
                                 87                 :                : typedef enum CreateDBStrategy
                                 88                 :                : {
                                 89                 :                :     CREATEDB_WAL_LOG,
                                 90                 :                :     CREATEDB_FILE_COPY,
                                 91                 :                : } CreateDBStrategy;
                                 92                 :                : 
                                 93                 :                : typedef struct
                                 94                 :                : {
                                 95                 :                :     Oid         src_dboid;      /* source (template) DB */
                                 96                 :                :     Oid         dest_dboid;     /* DB we are trying to create */
                                 97                 :                :     CreateDBStrategy strategy;  /* create db strategy */
                                 98                 :                : } createdb_failure_params;
                                 99                 :                : 
                                100                 :                : typedef struct
                                101                 :                : {
                                102                 :                :     Oid         dest_dboid;     /* DB we are trying to move */
                                103                 :                :     Oid         dest_tsoid;     /* tablespace we are trying to move to */
                                104                 :                : } movedb_failure_params;
                                105                 :                : 
                                106                 :                : /*
                                107                 :                :  * Information about a relation to be copied when creating a database.
                                108                 :                :  */
                                109                 :                : typedef struct CreateDBRelInfo
                                110                 :                : {
                                111                 :                :     RelFileLocator rlocator;    /* physical relation identifier */
                                112                 :                :     Oid         reloid;         /* relation oid */
                                113                 :                :     bool        permanent;      /* relation is permanent or unlogged */
                                114                 :                :     bool        mainfork_page_std;  /* main fork has standard page layout */
                                115                 :                : } CreateDBRelInfo;
                                116                 :                : 
                                117                 :                : 
                                118                 :                : /* non-export function prototypes */
                                119                 :                : static void createdb_failure_callback(int code, Datum arg);
                                120                 :                : static void movedb(const char *dbname, const char *tblspcname);
                                121                 :                : static void movedb_failure_callback(int code, Datum arg);
                                122                 :                : static bool get_db_info(const char *name, LOCKMODE lockmode,
                                123                 :                :                         Oid *dbIdP, Oid *ownerIdP,
                                124                 :                :                         int *encodingP, bool *dbIsTemplateP, bool *dbAllowConnP, bool *dbHasLoginEvtP,
                                125                 :                :                         TransactionId *dbFrozenXidP, MultiXactId *dbMinMultiP,
                                126                 :                :                         Oid *dbTablespace, char **dbCollate, char **dbCtype, char **dbLocale,
                                127                 :                :                         char **dbIcurules,
                                128                 :                :                         char *dbLocProvider,
                                129                 :                :                         char **dbCollversion);
                                130                 :                : static void remove_dbtablespaces(Oid db_id);
                                131                 :                : static bool check_db_file_conflict(Oid db_id);
                                132                 :                : static int  errdetail_busy_db(int notherbackends, int npreparedxacts);
                                133                 :                : static void CreateDatabaseUsingWalLog(Oid src_dboid, Oid dst_dboid, Oid src_tsid,
                                134                 :                :                                       Oid dst_tsid);
                                135                 :                : static List *ScanSourceDatabasePgClass(Oid tbid, Oid dbid, char *srcpath);
                                136                 :                : static List *ScanSourceDatabasePgClassPage(Page page, Buffer buf, Oid tbid,
                                137                 :                :                                            Oid dbid, char *srcpath,
                                138                 :                :                                            List *rlocatorlist, Snapshot snapshot);
                                139                 :                : static CreateDBRelInfo *ScanSourceDatabasePgClassTuple(HeapTupleData *tuple,
                                140                 :                :                                                        Oid tbid, Oid dbid,
                                141                 :                :                                                        char *srcpath);
                                142                 :                : static void CreateDirAndVersionFile(char *dbpath, Oid dbid, Oid tsid,
                                143                 :                :                                     bool isRedo);
                                144                 :                : static void CreateDatabaseUsingFileCopy(Oid src_dboid, Oid dst_dboid,
                                145                 :                :                                         Oid src_tsid, Oid dst_tsid);
                                146                 :                : static void recovery_create_dbdir(char *path, bool only_tblspc);
                                147                 :                : 
                                148                 :                : /*
                                149                 :                :  * Create a new database using the WAL_LOG strategy.
                                150                 :                :  *
                                151                 :                :  * Each copied block is separately written to the write-ahead log.
                                152                 :                :  */
                                153                 :                : static void
 1705 rhaas@postgresql.org      154                 :CBC         291 : CreateDatabaseUsingWalLog(Oid src_dboid, Oid dst_dboid,
                                155                 :                :                           Oid src_tsid, Oid dst_tsid)
                                156                 :                : {
                                157                 :                :     char       *srcpath;
                                158                 :                :     char       *dstpath;
 1606                           159                 :            291 :     List       *rlocatorlist = NULL;
                                160                 :                :     ListCell   *cell;
                                161                 :                :     LockRelId   srcrelid;
                                162                 :                :     LockRelId   dstrelid;
                                163                 :                :     RelFileLocator srcrlocator;
                                164                 :                :     RelFileLocator dstrlocator;
                                165                 :                :     CreateDBRelInfo *relinfo;
                                166                 :                : 
                                167                 :                :     /* Get source and destination database paths. */
 1705                           168                 :            291 :     srcpath = GetDatabasePath(src_dboid, src_tsid);
                                169                 :            291 :     dstpath = GetDatabasePath(dst_dboid, dst_tsid);
                                170                 :                : 
                                171                 :                :     /* Create database directory and write PG_VERSION file. */
                                172                 :            291 :     CreateDirAndVersionFile(dstpath, dst_dboid, dst_tsid, false);
                                173                 :                : 
                                174                 :                :     /* Copy relmap file from source database to the destination database. */
                                175                 :            291 :     RelationMapCopy(dst_dboid, dst_tsid, srcpath, dstpath);
                                176                 :                : 
                                177                 :                :     /* Get list of relfilelocators to copy from the source database. */
 1606                           178                 :            291 :     rlocatorlist = ScanSourceDatabasePgClass(src_tsid, src_dboid, srcpath);
                                179         [ -  + ]:            291 :     Assert(rlocatorlist != NIL);
                                180                 :                : 
                                181                 :                :     /*
                                182                 :                :      * Database IDs will be the same for all relations so set them before
                                183                 :                :      * entering the loop.
                                184                 :                :      */
 1705                           185                 :            291 :     srcrelid.dbId = src_dboid;
                                186                 :            291 :     dstrelid.dbId = dst_dboid;
                                187                 :                : 
                                188                 :                :     /* Loop over our list of relfilelocators and copy each one. */
 1606                           189   [ +  -  +  +  :          65356 :     foreach(cell, rlocatorlist)
                                              +  + ]
                                190                 :                :     {
 1705                           191                 :          65067 :         relinfo = lfirst(cell);
 1606                           192                 :          65067 :         srcrlocator = relinfo->rlocator;
                                193                 :                : 
                                194                 :                :         /*
                                195                 :                :          * If the relation is from the source db's default tablespace then we
                                196                 :                :          * need to create it in the destination db's default tablespace.
                                197                 :                :          * Otherwise, we need to create in the same tablespace as it is in the
                                198                 :                :          * source database.
                                199                 :                :          */
                                200         [ +  - ]:          65067 :         if (srcrlocator.spcOid == src_tsid)
                                201                 :          65067 :             dstrlocator.spcOid = dst_tsid;
                                202                 :                :         else
 1606 rhaas@postgresql.org      203                 :UBC           0 :             dstrlocator.spcOid = srcrlocator.spcOid;
                                204                 :                : 
 1606 rhaas@postgresql.org      205                 :CBC       65067 :         dstrlocator.dbOid = dst_dboid;
                                206                 :          65067 :         dstrlocator.relNumber = srcrlocator.relNumber;
                                207                 :                : 
                                208                 :                :         /*
                                209                 :                :          * Acquire locks on source and target relations before copying.
                                210                 :                :          *
                                211                 :                :          * We typically do not read relation data into shared_buffers without
                                212                 :                :          * holding a relation lock. It's unclear what could go wrong if we
                                213                 :                :          * skipped it in this case, because nobody can be modifying either the
                                214                 :                :          * source or destination database at this point, and we have locks on
                                215                 :                :          * both databases, too, but let's take the conservative route.
                                216                 :                :          */
 1705                           217                 :          65067 :         dstrelid.relId = srcrelid.relId = relinfo->reloid;
                                218                 :          65067 :         LockRelationId(&srcrelid, AccessShareLock);
                                219                 :          65067 :         LockRelationId(&dstrelid, AccessShareLock);
                                220                 :                : 
                                221                 :                :         /* Copy relation storage from source to the destination. */
    9 melanieplageman@gmai      222                 :GNC       65067 :         CreateAndCopyRelationData(srcrlocator, dstrlocator, relinfo->permanent,
    9 melanieplageman@gmai      223                 :CBC       65067 :                                   relinfo->mainfork_page_std);
                                224                 :                : 
                                225                 :                :         /* Release the relation locks. */
 1705 rhaas@postgresql.org      226                 :          65065 :         UnlockRelationId(&srcrelid, AccessShareLock);
                                227                 :          65065 :         UnlockRelationId(&dstrelid, AccessShareLock);
                                228                 :                :     }
                                229                 :                : 
 1678 alvherre@alvh.no-ip.      230                 :            289 :     pfree(srcpath);
                                231                 :            289 :     pfree(dstpath);
 1606 rhaas@postgresql.org      232                 :            289 :     list_free_deep(rlocatorlist);
 1705                           233                 :            289 : }
                                234                 :                : 
                                235                 :                : /*
                                236                 :                :  * Scan the pg_class table in the source database to identify the relations
                                237                 :                :  * that need to be copied to the destination database.
                                238                 :                :  *
                                239                 :                :  * This is an exception to the usual rule that cross-database access is
                                240                 :                :  * not possible. We can make it work here because we know that there are no
                                241                 :                :  * connections to the source database and (since there can't be prepared
                                242                 :                :  * transactions touching that database) no in-doubt tuples either. This
                                243                 :                :  * means that we don't need to worry about pruning removing anything from
                                244                 :                :  * under us, and we don't need to be too picky about our snapshot either.
                                245                 :                :  * As long as it sees all previously-committed XIDs as committed and all
                                246                 :                :  * aborted XIDs as aborted, we should be fine: nothing else is possible
                                247                 :                :  * here.
                                248                 :                :  *
                                249                 :                :  * We can't rely on the relcache for anything here, because that only knows
                                250                 :                :  * about the database to which we are connected, and can't handle access to
                                251                 :                :  * other databases. That also means we can't rely on the heap scan
                                252                 :                :  * infrastructure, which would be a bad idea anyway since it might try
                                253                 :                :  * to do things like HOT pruning which we definitely can't do safely in
                                254                 :                :  * a database to which we're not even connected.
                                255                 :                :  */
                                256                 :                : static List *
                                257                 :            291 : ScanSourceDatabasePgClass(Oid tbid, Oid dbid, char *srcpath)
                                258                 :                : {
                                259                 :                :     RelFileLocator rlocator;
                                260                 :                :     BlockNumber nblocks;
                                261                 :                :     BlockNumber blkno;
                                262                 :                :     Buffer      buf;
                                263                 :                :     RelFileNumber relfilenumber;
                                264                 :                :     Page        page;
 1606                           265                 :            291 :     List       *rlocatorlist = NIL;
                                266                 :                :     LockRelId   relid;
                                267                 :                :     Snapshot    snapshot;
                                268                 :                :     SMgrRelation smgr;
                                269                 :                :     BufferAccessStrategy bstrategy;
                                270                 :                : 
                                271                 :                :     /* Get pg_class relfilenumber. */
                                272                 :            291 :     relfilenumber = RelationMapOidToFilenumberForDatabase(srcpath,
                                273                 :                :                                                           RelationRelationId);
                                274                 :                : 
                                275                 :                :     /* Don't read data into shared_buffers without holding a relation lock. */
 1705                           276                 :            291 :     relid.dbId = dbid;
                                277                 :            291 :     relid.relId = RelationRelationId;
                                278                 :            291 :     LockRelationId(&relid, AccessShareLock);
                                279                 :                : 
                                280                 :                :     /* Prepare a RelFileLocator for the pg_class relation. */
 1606                           281                 :            291 :     rlocator.spcOid = tbid;
                                282                 :            291 :     rlocator.dbOid = dbid;
                                283                 :            291 :     rlocator.relNumber = relfilenumber;
                                284                 :                : 
 1000 heikki.linnakangas@i      285                 :            291 :     smgr = smgropen(rlocator, INVALID_PROC_NUMBER);
 1569 rhaas@postgresql.org      286                 :            291 :     nblocks = smgrnblocks(smgr, MAIN_FORKNUM);
                                287                 :            291 :     smgrclose(smgr);
                                288                 :                : 
                                289                 :                :     /* Use a buffer access strategy since this is a bulk read operation. */
 1705                           290                 :            291 :     bstrategy = GetAccessStrategy(BAS_BULKREAD);
                                291                 :                : 
                                292                 :                :     /*
                                293                 :                :      * As explained in the function header comments, we need a snapshot that
                                294                 :                :      * will see all committed transactions as committed, and our transaction
                                295                 :                :      * snapshot - or the active snapshot - might not be new enough for that,
                                296                 :                :      * but the return value of GetLatestSnapshot() should work fine.
                                297                 :                :      */
  627 heikki.linnakangas@i      298                 :            291 :     snapshot = RegisterSnapshot(GetLatestSnapshot());
                                299                 :                : 
                                300                 :                :     /* Process the relation block by block. */
 1705 rhaas@postgresql.org      301         [ +  + ]:           4656 :     for (blkno = 0; blkno < nblocks; blkno++)
                                302                 :                :     {
                                303         [ -  + ]:           4365 :         CHECK_FOR_INTERRUPTS();
                                304                 :                : 
 1606                           305                 :           4365 :         buf = ReadBufferWithoutRelcache(rlocator, MAIN_FORKNUM, blkno,
                                306                 :                :                                         RBM_NORMAL, bstrategy, true);
                                307                 :                : 
 1705                           308                 :           4365 :         LockBuffer(buf, BUFFER_LOCK_SHARE);
                                309                 :           4365 :         page = BufferGetPage(buf);
                                310   [ +  -  -  + ]:           4365 :         if (PageIsNew(page) || PageIsEmpty(page))
                                311                 :                :         {
 1705 rhaas@postgresql.org      312                 :UBC           0 :             UnlockReleaseBuffer(buf);
                                313                 :              0 :             continue;
                                314                 :                :         }
                                315                 :                : 
                                316                 :                :         /* Append relevant pg_class tuples for current page to rlocatorlist. */
 1606 rhaas@postgresql.org      317                 :CBC        4365 :         rlocatorlist = ScanSourceDatabasePgClassPage(page, buf, tbid, dbid,
                                318                 :                :                                                      srcpath, rlocatorlist,
                                319                 :                :                                                      snapshot);
                                320                 :                : 
 1705                           321                 :           4365 :         UnlockReleaseBuffer(buf);
                                322                 :                :     }
  627 heikki.linnakangas@i      323                 :            291 :     UnregisterSnapshot(snapshot);
                                324                 :                : 
                                325                 :                :     /* Release relation lock. */
 1705 rhaas@postgresql.org      326                 :            291 :     UnlockRelationId(&relid, AccessShareLock);
                                327                 :                : 
 1606                           328                 :            291 :     return rlocatorlist;
                                329                 :                : }
                                330                 :                : 
                                331                 :                : /*
                                332                 :                :  * Scan one page of the source database's pg_class relation and add relevant
                                333                 :                :  * entries to rlocatorlist. The return value is the updated list.
                                334                 :                :  */
                                335                 :                : static List *
 1705                           336                 :           4365 : ScanSourceDatabasePgClassPage(Page page, Buffer buf, Oid tbid, Oid dbid,
                                337                 :                :                               char *srcpath, List *rlocatorlist,
                                338                 :                :                               Snapshot snapshot)
                                339                 :                : {
 1661 tgl@sss.pgh.pa.us         340                 :           4365 :     BlockNumber blkno = BufferGetBlockNumber(buf);
                                341                 :                :     OffsetNumber offnum;
                                342                 :                :     OffsetNumber maxoff;
                                343                 :                :     HeapTupleData tuple;
                                344                 :                : 
 1705 rhaas@postgresql.org      345                 :           4365 :     maxoff = PageGetMaxOffsetNumber(page);
                                346                 :                : 
                                347                 :                :     /* Loop over offsets. */
                                348                 :           4365 :     for (offnum = FirstOffsetNumber;
                                349         [ +  + ]:         216306 :          offnum <= maxoff;
                                350                 :         211941 :          offnum = OffsetNumberNext(offnum))
                                351                 :                :     {
                                352                 :                :         ItemId      itemid;
                                353                 :                : 
                                354                 :         211941 :         itemid = PageGetItemId(page, offnum);
                                355                 :                : 
                                356                 :                :         /* Nothing to do if slot is empty or already dead. */
                                357   [ +  +  +  + ]:         211941 :         if (!ItemIdIsUsed(itemid) || ItemIdIsDead(itemid) ||
                                358         [ +  + ]:         149056 :             ItemIdIsRedirected(itemid))
                                359                 :          88494 :             continue;
                                360                 :                : 
                                361         [ -  + ]:         123447 :         Assert(ItemIdIsNormal(itemid));
                                362                 :         123447 :         ItemPointerSet(&(tuple.t_self), blkno, offnum);
                                363                 :                : 
                                364                 :                :         /* Initialize a HeapTupleData structure. */
                                365                 :         123447 :         tuple.t_data = (HeapTupleHeader) PageGetItem(page, itemid);
                                366                 :         123447 :         tuple.t_len = ItemIdGetLength(itemid);
                                367                 :         123447 :         tuple.t_tableOid = RelationRelationId;
                                368                 :                : 
                                369                 :                :         /* Skip tuples that are not visible to this snapshot. */
                                370         [ +  + ]:         123447 :         if (HeapTupleSatisfiesVisibility(&tuple, snapshot, buf))
                                371                 :                :         {
                                372                 :                :             CreateDBRelInfo *relinfo;
                                373                 :                : 
                                374                 :                :             /*
                                375                 :                :              * ScanSourceDatabasePgClassTuple is in charge of constructing a
                                376                 :                :              * CreateDBRelInfo object for this tuple, but can also decide that
                                377                 :                :              * this tuple isn't something we need to copy. If we do need to
                                378                 :                :              * copy the relation, add it to the list.
                                379                 :                :              */
                                380                 :         123426 :             relinfo = ScanSourceDatabasePgClassTuple(&tuple, tbid, dbid,
                                381                 :                :                                                      srcpath);
                                382         [ +  + ]:         123426 :             if (relinfo != NULL)
 1606                           383                 :          65517 :                 rlocatorlist = lappend(rlocatorlist, relinfo);
                                384                 :                :         }
                                385                 :                :     }
                                386                 :                : 
                                387                 :           4365 :     return rlocatorlist;
                                388                 :                : }
                                389                 :                : 
                                390                 :                : /*
                                391                 :                :  * Decide whether a certain pg_class tuple represents something that
                                392                 :                :  * needs to be copied from the source database to the destination database,
                                393                 :                :  * and if so, construct a CreateDBRelInfo for it.
                                394                 :                :  *
                                395                 :                :  * Visibility checks are handled by the caller, so our job here is just
                                396                 :                :  * to assess the data stored in the tuple.
                                397                 :                :  */
                                398                 :                : CreateDBRelInfo *
 1705                           399                 :         123426 : ScanSourceDatabasePgClassTuple(HeapTupleData *tuple, Oid tbid, Oid dbid,
                                400                 :                :                                char *srcpath)
                                401                 :                : {
                                402                 :                :     CreateDBRelInfo *relinfo;
                                403                 :                :     Form_pg_class classForm;
 1584                           404                 :         123426 :     RelFileNumber relfilenumber = InvalidRelFileNumber;
                                405                 :                : 
 1705                           406                 :         123426 :     classForm = (Form_pg_class) GETSTRUCT(tuple);
                                407                 :                : 
                                408                 :                :     /*
                                409                 :                :      * Return NULL if this object does not need to be copied.
                                410                 :                :      *
                                411                 :                :      * Shared objects don't need to be copied, because they are shared.
                                412                 :                :      * Objects without storage can't be copied, because there's nothing to
                                413                 :                :      * copy. Temporary relations don't need to be copied either, because they
                                414                 :                :      * are inaccessible outside of the session that created them, which must
                                415                 :                :      * be gone already, and couldn't connect to a different database if it
                                416                 :                :      * still existed. autovacuum will eventually remove the pg_class entries
                                417                 :                :      * as well.
                                418                 :                :      */
                                419         [ +  + ]:         123426 :     if (classForm->reltablespace == GLOBALTABLESPACE_OID ||
                                420   [ +  +  +  +  :         110040 :         !RELKIND_HAS_STORAGE(classForm->relkind) ||
                                     +  +  +  +  -  
                                                 + ]
                                421         [ -  + ]:          65517 :         classForm->relpersistence == RELPERSISTENCE_TEMP)
                                422                 :          57909 :         return NULL;
                                423                 :                : 
                                424                 :                :     /*
                                425                 :                :      * If relfilenumber is valid then directly use it.  Otherwise, consult the
                                426                 :                :      * relmap.
                                427                 :                :      */
 1606                           428         [ +  + ]:          65517 :     if (RelFileNumberIsValid(classForm->relfilenode))
                                429                 :          60570 :         relfilenumber = classForm->relfilenode;
                                430                 :                :     else
                                431                 :           4947 :         relfilenumber = RelationMapOidToFilenumberForDatabase(srcpath,
                                432                 :                :                                                               classForm->oid);
                                433                 :                : 
                                434                 :                :     /* We must have a valid relfilenumber. */
                                435         [ -  + ]:          65517 :     if (!RelFileNumberIsValid(relfilenumber))
 1606 rhaas@postgresql.org      436         [ #  # ]:UBC           0 :         elog(ERROR, "relation with OID %u does not have a valid relfilenumber",
                                437                 :                :              classForm->oid);
                                438                 :                : 
                                439                 :                :     /* Prepare a rel info element and add it to the list. */
  353 michael@paquier.xyz       440                 :CBC       65517 :     relinfo = palloc_object(CreateDBRelInfo);
 1705 rhaas@postgresql.org      441         [ -  + ]:          65517 :     if (OidIsValid(classForm->reltablespace))
 1606 rhaas@postgresql.org      442                 :UBC           0 :         relinfo->rlocator.spcOid = classForm->reltablespace;
                                443                 :                :     else
 1606 rhaas@postgresql.org      444                 :CBC       65517 :         relinfo->rlocator.spcOid = tbid;
                                445                 :                : 
                                446                 :          65517 :     relinfo->rlocator.dbOid = dbid;
                                447                 :          65517 :     relinfo->rlocator.relNumber = relfilenumber;
 1705                           448                 :          65517 :     relinfo->reloid = classForm->oid;
                                449                 :                : 
                                450                 :                :     /* Temporary relations were rejected above. */
                                451         [ -  + ]:          65517 :     Assert(classForm->relpersistence != RELPERSISTENCE_TEMP);
                                452                 :          65517 :     relinfo->permanent =
                                453                 :          65517 :         (classForm->relpersistence == RELPERSISTENCE_PERMANENT) ? true : false;
                                454                 :                : 
                                455                 :                :     /*
                                456                 :                :      * Heap tables and B-tree indexes are common cases whose main forks are
                                457                 :                :      * known to use the standard page layout. Other access methods may do so
                                458                 :                :      * as well, but some, such as GIN, have legacy page formats that differ
                                459                 :                :      * from their current format. Keep the classification conservative by
                                460                 :                :      * limiting it to heap and B-tree.
                                461                 :                :      */
    9 melanieplageman@gmai      462                 :          65517 :     relinfo->mainfork_page_std =
                                463   [ +  +  -  + ]:          48912 :         (RELKIND_HAS_TABLE_AM(classForm->relkind) &&
                                464   [ +  +  -  + ]:         114429 :          classForm->relam == HEAP_TABLE_AM_OID) ||
                                465         [ +  + ]:          39593 :         (classForm->relkind == RELKIND_INDEX &&
                                466         [ +  - ]:          39591 :          classForm->relam == BTREE_AM_OID);
                                467                 :                : 
 1705 rhaas@postgresql.org      468                 :          65517 :     return relinfo;
                                469                 :                : }
                                470                 :                : 
                                471                 :                : /*
                                472                 :                :  * Create database directory and write out the PG_VERSION file in the database
                                473                 :                :  * path.  If isRedo is true, it's okay for the database directory to exist
                                474                 :                :  * already.
                                475                 :                :  */
                                476                 :                : static void
                                477                 :            314 : CreateDirAndVersionFile(char *dbpath, Oid dbid, Oid tsid, bool isRedo)
                                478                 :                : {
                                479                 :                :     int         fd;
                                480                 :                :     size_t      nbytes;
                                481                 :                :     char        versionfile[MAXPGPATH];
                                482                 :                :     char        buf[16];
                                483                 :                : 
                                484                 :                :     /*
                                485                 :                :      * Note that we don't have to copy version data from the source database;
                                486                 :                :      * there's only one legal value.
                                487                 :                :      */
                                488                 :            314 :     sprintf(buf, "%s\n", PG_MAJORVERSION);
                                489                 :            314 :     nbytes = strlen(PG_MAJORVERSION) + 1;
                                490                 :                : 
                                491                 :                :     /* Create database directory. */
                                492         [ +  + ]:            314 :     if (MakePGDirectory(dbpath) < 0)
                                493                 :                :     {
                                494                 :                :         /* Failure other than already exists or not in WAL replay? */
                                495   [ +  -  -  + ]:              9 :         if (errno != EEXIST || !isRedo)
 1705 rhaas@postgresql.org      496         [ #  # ]:UBC           0 :             ereport(ERROR,
                                497                 :                :                     (errcode_for_file_access(),
                                498                 :                :                      errmsg("could not create directory \"%s\": %m", dbpath)));
                                499                 :                :     }
                                500                 :                : 
                                501                 :                :     /*
                                502                 :                :      * Create PG_VERSION file in the database path.  If the file already
                                503                 :                :      * exists and we are in WAL replay then try again to open it in write
                                504                 :                :      * mode.
                                505                 :                :      */
 1705 rhaas@postgresql.org      506                 :CBC         314 :     snprintf(versionfile, sizeof(versionfile), "%s/%s", dbpath, "PG_VERSION");
                                507                 :                : 
                                508                 :            314 :     fd = OpenTransientFile(versionfile, O_WRONLY | O_CREAT | O_EXCL | PG_BINARY);
                                509   [ +  +  +  -  :            314 :     if (fd < 0 && errno == EEXIST && isRedo)
                                              +  - ]
                                510                 :              9 :         fd = OpenTransientFile(versionfile, O_WRONLY | O_TRUNC | PG_BINARY);
                                511                 :                : 
                                512         [ -  + ]:            314 :     if (fd < 0)
 1705 rhaas@postgresql.org      513         [ #  # ]:UBC           0 :         ereport(ERROR,
                                514                 :                :                 (errcode_for_file_access(),
                                515                 :                :                  errmsg("could not create file \"%s\": %m", versionfile)));
                                516                 :                : 
                                517                 :                :     /* Write PG_MAJORVERSION in the PG_VERSION file. */
 1705 rhaas@postgresql.org      518                 :CBC         314 :     pgstat_report_wait_start(WAIT_EVENT_VERSION_FILE_WRITE);
                                519                 :            314 :     errno = 0;
  136 peter@eisentraut.org      520         [ -  + ]:GNC         314 :     if (write(fd, buf, nbytes) != nbytes)
                                521                 :                :     {
                                522                 :                :         /* If write didn't set errno, assume problem is no disk space. */
 1705 rhaas@postgresql.org      523         [ #  # ]:UBC           0 :         if (errno == 0)
                                524                 :              0 :             errno = ENOSPC;
                                525         [ #  # ]:              0 :         ereport(ERROR,
                                526                 :                :                 (errcode_for_file_access(),
                                527                 :                :                  errmsg("could not write to file \"%s\": %m", versionfile)));
                                528                 :                :     }
 1705 rhaas@postgresql.org      529                 :CBC         314 :     pgstat_report_wait_end();
                                530                 :                : 
 1031 noah@leadboat.com         531                 :            314 :     pgstat_report_wait_start(WAIT_EVENT_VERSION_FILE_SYNC);
                                532         [ -  + ]:            314 :     if (pg_fsync(fd) != 0)
 1031 noah@leadboat.com         533         [ #  # ]:UBC           0 :         ereport(data_sync_elevel(ERROR),
                                534                 :                :                 (errcode_for_file_access(),
                                535                 :                :                  errmsg("could not fsync file \"%s\": %m", versionfile)));
 1031 noah@leadboat.com         536                 :CBC         314 :     fsync_fname(dbpath, true);
                                537                 :            314 :     pgstat_report_wait_end();
                                538                 :                : 
                                539                 :                :     /* Close the version file. */
 1705 rhaas@postgresql.org      540                 :            314 :     CloseTransientFile(fd);
                                541                 :                : 
                                542                 :                :     /* If we are not in WAL replay then write the WAL. */
                                543         [ +  + ]:            314 :     if (!isRedo)
                                544                 :                :     {
                                545                 :                :         xl_dbase_create_wal_log_rec xlrec;
                                546                 :                : 
 1031 noah@leadboat.com         547                 :            291 :         START_CRIT_SECTION();
                                548                 :                : 
                                549                 :            291 :         xlrec.db_id = dbid;
                                550                 :            291 :         xlrec.tablespace_id = tsid;
                                551                 :                : 
                                552                 :            291 :         XLogBeginInsert();
  655 peter@eisentraut.org      553                 :            291 :         XLogRegisterData(&xlrec,
                                554                 :                :                          sizeof(xl_dbase_create_wal_log_rec));
                                555                 :                : 
 1031 noah@leadboat.com         556                 :            291 :         (void) XLogInsert(RM_DBASE_ID, XLOG_DBASE_CREATE_WAL_LOG);
                                557                 :                : 
 1705 rhaas@postgresql.org      558         [ -  + ]:            291 :         END_CRIT_SECTION();
                                559                 :                :     }
                                560                 :            314 : }
                                561                 :                : 
                                562                 :                : /*
                                563                 :                :  * Create a new database using the FILE_COPY strategy.
                                564                 :                :  *
                                565                 :                :  * Copy each tablespace at the filesystem level, and log a single WAL record
                                566                 :                :  * for each tablespace copied.  This requires a checkpoint before and after the
                                567                 :                :  * copy, which may be expensive, but it does greatly reduce WAL generation
                                568                 :                :  * if the copied database is large.
                                569                 :                :  */
                                570                 :                : static void
                                571                 :            161 : CreateDatabaseUsingFileCopy(Oid src_dboid, Oid dst_dboid, Oid src_tsid,
                                572                 :                :                             Oid dst_tsid)
                                573                 :                : {
                                574                 :                :     TableScanDesc scan;
                                575                 :                :     Relation    rel;
                                576                 :                :     HeapTuple   tuple;
                                577                 :                : 
                                578                 :                :     /*
                                579                 :                :      * The strategy check in createdb() runs before our transaction has an XID
                                580                 :                :      * and before the pg_database row exists, so the datachecksumsworker
                                581                 :                :      * launcher can start in that window and miss both the new database and
                                582                 :                :      * our transaction, leaving the raw-copied files without checksums.
                                583                 :                :      */
  123 dgustafsson@postgres      584         [ +  + ]:GNC         161 :     if (DataChecksumsInProgressOn())
                                585         [ +  - ]:              1 :         ereport(ERROR,
                                586                 :                :                 errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
                                587                 :                :                 errmsg("create database strategy \"%s\" not allowed when data checksums are being enabled",
                                588                 :                :                        "file_copy"));
                                589                 :                : 
                                590                 :                :     /*
                                591                 :                :      * The XID is assigned by now, so a datachecksumsworker launcher starting
                                592                 :                :      * after this point will wait for us and find the new database.
                                593                 :                :      */
                                594                 :                : 
                                595                 :                :     /*
                                596                 :                :      * Force a checkpoint before starting the copy. This will force all dirty
                                597                 :                :      * buffers, including those of unlogged tables, out to disk, to ensure
                                598                 :                :      * source database is up-to-date on disk for the copy.
                                599                 :                :      * FlushDatabaseBuffers() would suffice for that, but we also want to
                                600                 :                :      * process any pending unlink requests. Otherwise, if a checkpoint
                                601                 :                :      * happened while we're copying files, a file might be deleted just when
                                602                 :                :      * we're about to copy it, causing the lstat() call in copydir() to fail
                                603                 :                :      * with ENOENT.
                                604                 :                :      *
                                605                 :                :      * In binary upgrade mode, we can skip this checkpoint because pg_upgrade
                                606                 :                :      * is careful to ensure that template0 is fully written to disk prior to
                                607                 :                :      * any CREATE DATABASE commands.
                                608                 :                :      */
  873 nathan@postgresql.or      609         [ +  + ]:CBC         160 :     if (!IsBinaryUpgrade)
  505                           610                 :            126 :         RequestCheckpoint(CHECKPOINT_FAST | CHECKPOINT_FORCE |
                                611                 :                :                           CHECKPOINT_WAIT | CHECKPOINT_FLUSH_UNLOGGED);
                                612                 :                : 
                                613                 :                :     /*
                                614                 :                :      * Iterate through all tablespaces of the template database, and copy each
                                615                 :                :      * one to the new database.
                                616                 :                :      */
 1705 rhaas@postgresql.org      617                 :            160 :     rel = table_open(TableSpaceRelationId, AccessShareLock);
                                618                 :            160 :     scan = table_beginscan_catalog(rel, 0, NULL);
                                619         [ +  + ]:            514 :     while ((tuple = heap_getnext(scan, ForwardScanDirection)) != NULL)
                                620                 :                :     {
                                621                 :            354 :         Form_pg_tablespace spaceform = (Form_pg_tablespace) GETSTRUCT(tuple);
                                622                 :            354 :         Oid         srctablespace = spaceform->oid;
                                623                 :                :         Oid         dsttablespace;
                                624                 :                :         char       *srcpath;
                                625                 :                :         char       *dstpath;
                                626                 :                :         struct stat st;
                                627                 :                : 
                                628                 :                :         /* No need to copy global tablespace */
                                629         [ +  + ]:            354 :         if (srctablespace == GLOBALTABLESPACE_OID)
                                630                 :            194 :             continue;
                                631                 :                : 
                                632                 :            194 :         srcpath = GetDatabasePath(src_dboid, srctablespace);
                                633                 :                : 
                                634   [ +  +  +  -  :            354 :         if (stat(srcpath, &st) < 0 || !S_ISDIR(st.st_mode) ||
                                              -  + ]
                                635                 :            160 :             directory_is_empty(srcpath))
                                636                 :                :         {
                                637                 :                :             /* Assume we can ignore it */
                                638                 :             34 :             pfree(srcpath);
                                639                 :             34 :             continue;
                                640                 :                :         }
                                641                 :                : 
                                642         [ +  - ]:            160 :         if (srctablespace == src_tsid)
                                643                 :            160 :             dsttablespace = dst_tsid;
                                644                 :                :         else
 1705 rhaas@postgresql.org      645                 :UBC           0 :             dsttablespace = srctablespace;
                                646                 :                : 
 1705 rhaas@postgresql.org      647                 :CBC         160 :         dstpath = GetDatabasePath(dst_dboid, dsttablespace);
                                648                 :                : 
                                649                 :                :         /*
                                650                 :                :          * Copy this subdirectory to the new location
                                651                 :                :          *
                                652                 :                :          * We don't need to copy subdirectories
                                653                 :                :          */
                                654                 :            160 :         copydir(srcpath, dstpath, false);
                                655                 :                : 
                                656                 :                :         /* Record the filesystem change in XLOG */
                                657                 :                :         {
                                658                 :                :             xl_dbase_create_file_copy_rec xlrec;
                                659                 :                : 
                                660                 :            160 :             xlrec.db_id = dst_dboid;
                                661                 :            160 :             xlrec.tablespace_id = dsttablespace;
                                662                 :            160 :             xlrec.src_db_id = src_dboid;
                                663                 :            160 :             xlrec.src_tablespace_id = srctablespace;
                                664                 :                : 
                                665                 :            160 :             XLogBeginInsert();
  655 peter@eisentraut.org      666                 :            160 :             XLogRegisterData(&xlrec,
                                667                 :                :                              sizeof(xl_dbase_create_file_copy_rec));
                                668                 :                : 
 1705 rhaas@postgresql.org      669                 :            160 :             (void) XLogInsert(RM_DBASE_ID,
                                670                 :                :                               XLOG_DBASE_CREATE_FILE_COPY | XLR_SPECIAL_REL_UPDATE);
                                671                 :                :         }
 1678 alvherre@alvh.no-ip.      672                 :            160 :         pfree(srcpath);
                                673                 :            160 :         pfree(dstpath);
                                674                 :                :     }
 1705 rhaas@postgresql.org      675                 :            160 :     table_endscan(scan);
                                676                 :            160 :     table_close(rel, AccessShareLock);
                                677                 :                : 
                                678                 :                :     /*
                                679                 :                :      * We force a checkpoint before committing.  This effectively means that
                                680                 :                :      * committed XLOG_DBASE_CREATE_FILE_COPY operations will never need to be
                                681                 :                :      * replayed (at least not in ordinary crash recovery; we still have to
                                682                 :                :      * make the XLOG entry for the benefit of PITR operations). This avoids
                                683                 :                :      * two nasty scenarios:
                                684                 :                :      *
                                685                 :                :      * #1: At wal_level=minimal, we don't XLOG the contents of newly created
                                686                 :                :      * relfilenodes; therefore the drop-and-recreate-whole-directory behavior
                                687                 :                :      * of DBASE_CREATE replay would lose such files created in the new
                                688                 :                :      * database between our commit and the next checkpoint.
                                689                 :                :      *
                                690                 :                :      * #2: Since we have to recopy the source database during DBASE_CREATE
                                691                 :                :      * replay, we run the risk of copying changes in it that were committed
                                692                 :                :      * after the original CREATE DATABASE command but before the system crash
                                693                 :                :      * that led to the replay.  This is at least unexpected and at worst could
                                694                 :                :      * lead to inconsistencies, eg duplicate table names.
                                695                 :                :      *
                                696                 :                :      * (Both of these were real bugs in releases 8.0 through 8.0.3.)
                                697                 :                :      *
                                698                 :                :      * In PITR replay, the first of these isn't an issue, and the second is
                                699                 :                :      * only a risk if the CREATE DATABASE and subsequent template database
                                700                 :                :      * change both occur while a base backup is being taken. There doesn't
                                701                 :                :      * seem to be much we can do about that except document it as a
                                702                 :                :      * limitation.
                                703                 :                :      *
                                704                 :                :      * In binary upgrade mode, we can skip this checkpoint because neither of
                                705                 :                :      * these problems applies: we don't ever replay the WAL generated during
                                706                 :                :      * pg_upgrade, and we don't support taking base backups during pg_upgrade
                                707                 :                :      * (not to mention that we don't concurrently modify template0, either).
                                708                 :                :      *
                                709                 :                :      * See CreateDatabaseUsingWalLog() for a less cheesy CREATE DATABASE
                                710                 :                :      * strategy that avoids these problems.
                                711                 :                :      */
  873 nathan@postgresql.or      712         [ +  + ]:            160 :     if (!IsBinaryUpgrade)
  505                           713                 :            126 :         RequestCheckpoint(CHECKPOINT_FAST | CHECKPOINT_FORCE |
                                714                 :                :                           CHECKPOINT_WAIT);
 1705 rhaas@postgresql.org      715                 :            160 : }
                                716                 :                : 
                                717                 :                : /*
                                718                 :                :  * CREATE DATABASE
                                719                 :                :  */
                                720                 :                : Oid
 3735 peter_e@gmx.net           721                 :            475 : createdb(ParseState *pstate, const CreatedbStmt *stmt)
                                722                 :                : {
                                723                 :                :     Oid         src_dboid;
                                724                 :                :     Oid         src_owner;
 2619 andres@anarazel.de        725                 :            475 :     int         src_encoding = -1;
                                726                 :            475 :     char       *src_collate = NULL;
                                727                 :            475 :     char       *src_ctype = NULL;
  994 jdavis@postgresql.or      728                 :            475 :     char       *src_locale = NULL;
 1361 peter@eisentraut.org      729                 :            475 :     char       *src_icurules = NULL;
 1716 andres@anarazel.de        730                 :            475 :     char        src_locprovider = '\0';
 1748 peter@eisentraut.org      731                 :            475 :     char       *src_collversion = NULL;
                                732                 :                :     bool        src_istemplate;
 1024 akorotkov@postgresql      733                 :            475 :     bool        src_hasloginevt = false;
                                734                 :                :     bool        src_allowconn;
 2619 andres@anarazel.de        735                 :            475 :     TransactionId src_frozenxid = InvalidTransactionId;
                                736                 :            475 :     MultiXactId src_minmxid = InvalidMultiXactId;
                                737                 :                :     Oid         src_deftablespace;
                                738                 :                :     volatile Oid dst_deftablespace;
                                739                 :                :     Relation    pg_database_rel;
                                740                 :                :     HeapTuple   tuple;
 1596 peter@eisentraut.org      741                 :            475 :     Datum       new_record[Natts_pg_database] = {0};
                                742                 :            475 :     bool        new_record_nulls[Natts_pg_database] = {0};
 1769 rhaas@postgresql.org      743                 :            475 :     Oid         dboid = InvalidOid;
                                744                 :                :     Oid         datdba;
                                745                 :                :     ListCell   *option;
  835 peter@eisentraut.org      746                 :            475 :     DefElem    *tablespacenameEl = NULL;
                                747                 :            475 :     DefElem    *ownerEl = NULL;
                                748                 :            475 :     DefElem    *templateEl = NULL;
                                749                 :            475 :     DefElem    *encodingEl = NULL;
                                750                 :            475 :     DefElem    *localeEl = NULL;
                                751                 :            475 :     DefElem    *builtinlocaleEl = NULL;
                                752                 :            475 :     DefElem    *collateEl = NULL;
                                753                 :            475 :     DefElem    *ctypeEl = NULL;
                                754                 :            475 :     DefElem    *iculocaleEl = NULL;
                                755                 :            475 :     DefElem    *icurulesEl = NULL;
                                756                 :            475 :     DefElem    *locproviderEl = NULL;
                                757                 :            475 :     DefElem    *istemplateEl = NULL;
                                758                 :            475 :     DefElem    *allowconnectionsEl = NULL;
                                759                 :            475 :     DefElem    *connlimitEl = NULL;
                                760                 :            475 :     DefElem    *collversionEl = NULL;
                                761                 :            475 :     DefElem    *strategyEl = NULL;
 8929 bruce@momjian.us          762                 :            475 :     char       *dbname = stmt->dbname;
                                763                 :            475 :     char       *dbowner = NULL;
 7830 tgl@sss.pgh.pa.us         764                 :            475 :     const char *dbtemplate = NULL;
 6640 heikki.linnakangas@i      765                 :            475 :     char       *dbcollate = NULL;
                                766                 :            475 :     char       *dbctype = NULL;
  990 jdavis@postgresql.or      767                 :            475 :     const char *dblocale = NULL;
 1361 peter@eisentraut.org      768                 :            475 :     char       *dbicurules = NULL;
 1717                           769                 :            475 :     char        dblocprovider = '\0';
                                770                 :                :     char       *canonname;
 7513 tgl@sss.pgh.pa.us         771                 :            475 :     int         encoding = -1;
 4533                           772                 :            475 :     bool        dbistemplate = false;
                                773                 :            475 :     bool        dballowconnections = true;
 1234 andres@anarazel.de        774                 :            475 :     int         dbconnlimit = DATCONNLIMIT_UNLIMITED;
 1748 peter@eisentraut.org      775                 :            475 :     char       *dbcollversion = NULL;
                                776                 :                :     int         notherbackends;
                                777                 :                :     int         npreparedxacts;
 1705 rhaas@postgresql.org      778                 :            475 :     CreateDBStrategy dbstrategy = CREATEDB_WAL_LOG;
                                779                 :                :     createdb_failure_params fparms;
                                780                 :                : 
                                781                 :                :     /* Report error if name has \n or \r character. */
  280 andrew@dunslane.net       782         [ +  + ]:            475 :     if (strpbrk(dbname, "\n\r"))
                                783         [ +  - ]:              3 :         ereport(ERROR,
                                784                 :                :                 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
                                785                 :                :                  errmsg("database name \"%s\" contains a newline or carriage return character", dbname)));
                                786                 :                : 
                                787                 :                :     /* Extract options from the statement node tree */
 8929 bruce@momjian.us          788   [ +  +  +  +  :           1440 :     foreach(option, stmt->options)
                                              +  + ]
                                789                 :                :     {
                                790                 :            968 :         DefElem    *defel = (DefElem *) lfirst(option);
                                791                 :                : 
 8198 tgl@sss.pgh.pa.us         792         [ +  + ]:            968 :         if (strcmp(defel->defname, "tablespace") == 0)
                                793                 :                :         {
  835 peter@eisentraut.org      794         [ -  + ]:             17 :             if (tablespacenameEl)
 1962 dean.a.rasheed@gmail      795                 :UBC           0 :                 errorConflictingDefElem(defel, pstate);
  835 peter@eisentraut.org      796                 :CBC          17 :             tablespacenameEl = defel;
                                797                 :                :         }
 8198 tgl@sss.pgh.pa.us         798         [ +  + ]:            951 :         else if (strcmp(defel->defname, "owner") == 0)
                                799                 :                :         {
  835 peter@eisentraut.org      800         [ -  + ]:              1 :             if (ownerEl)
 1962 dean.a.rasheed@gmail      801                 :UBC           0 :                 errorConflictingDefElem(defel, pstate);
  835 peter@eisentraut.org      802                 :CBC           1 :             ownerEl = defel;
                                803                 :                :         }
 8929 bruce@momjian.us          804         [ +  + ]:            950 :         else if (strcmp(defel->defname, "template") == 0)
                                805                 :                :         {
  835 peter@eisentraut.org      806         [ -  + ]:            216 :             if (templateEl)
 1962 dean.a.rasheed@gmail      807                 :UBC           0 :                 errorConflictingDefElem(defel, pstate);
  835 peter@eisentraut.org      808                 :CBC         216 :             templateEl = defel;
                                809                 :                :         }
 8929 bruce@momjian.us          810         [ +  + ]:            734 :         else if (strcmp(defel->defname, "encoding") == 0)
                                811                 :                :         {
  835 peter@eisentraut.org      812         [ -  + ]:             69 :             if (encodingEl)
 1962 dean.a.rasheed@gmail      813                 :UBC           0 :                 errorConflictingDefElem(defel, pstate);
  835 peter@eisentraut.org      814                 :CBC          69 :             encodingEl = defel;
                                815                 :                :         }
 2685                           816         [ +  + ]:            665 :         else if (strcmp(defel->defname, "locale") == 0)
                                817                 :                :         {
  835                           818         [ -  + ]:             69 :             if (localeEl)
 1962 dean.a.rasheed@gmail      819                 :UBC           0 :                 errorConflictingDefElem(defel, pstate);
  835 peter@eisentraut.org      820                 :CBC          69 :             localeEl = defel;
                                821                 :                :         }
  990 jdavis@postgresql.or      822         [ +  + ]:            596 :         else if (strcmp(defel->defname, "builtin_locale") == 0)
                                823                 :                :         {
  835 peter@eisentraut.org      824         [ -  + ]:              9 :             if (builtinlocaleEl)
  990 jdavis@postgresql.or      825                 :UBC           0 :                 errorConflictingDefElem(defel, pstate);
  835 peter@eisentraut.org      826                 :CBC           9 :             builtinlocaleEl = defel;
                                827                 :                :         }
 6445 heikki.linnakangas@i      828         [ +  + ]:            587 :         else if (strcmp(defel->defname, "lc_collate") == 0)
                                829                 :                :         {
  835 peter@eisentraut.org      830         [ -  + ]:             12 :             if (collateEl)
 1962 dean.a.rasheed@gmail      831                 :UBC           0 :                 errorConflictingDefElem(defel, pstate);
  835 peter@eisentraut.org      832                 :CBC          12 :             collateEl = defel;
                                833                 :                :         }
 6445 heikki.linnakangas@i      834         [ +  + ]:            575 :         else if (strcmp(defel->defname, "lc_ctype") == 0)
                                835                 :                :         {
  835 peter@eisentraut.org      836         [ -  + ]:             12 :             if (ctypeEl)
 1962 dean.a.rasheed@gmail      837                 :UBC           0 :                 errorConflictingDefElem(defel, pstate);
  835 peter@eisentraut.org      838                 :CBC          12 :             ctypeEl = defel;
                                839                 :                :         }
 1717                           840         [ +  + ]:            563 :         else if (strcmp(defel->defname, "icu_locale") == 0)
                                841                 :                :         {
  835                           842         [ -  + ]:              5 :             if (iculocaleEl)
 1717 peter@eisentraut.org      843                 :UBC           0 :                 errorConflictingDefElem(defel, pstate);
  835 peter@eisentraut.org      844                 :CBC           5 :             iculocaleEl = defel;
                                845                 :                :         }
 1361                           846         [ +  + ]:            558 :         else if (strcmp(defel->defname, "icu_rules") == 0)
                                847                 :                :         {
  835                           848         [ -  + ]:              1 :             if (icurulesEl)
 1361 peter@eisentraut.org      849                 :UBC           0 :                 errorConflictingDefElem(defel, pstate);
  835 peter@eisentraut.org      850                 :CBC           1 :             icurulesEl = defel;
                                851                 :                :         }
 1717                           852         [ +  + ]:            557 :         else if (strcmp(defel->defname, "locale_provider") == 0)
                                853                 :                :         {
  835                           854         [ -  + ]:             75 :             if (locproviderEl)
 1717 peter@eisentraut.org      855                 :UBC           0 :                 errorConflictingDefElem(defel, pstate);
  835 peter@eisentraut.org      856                 :CBC          75 :             locproviderEl = defel;
                                857                 :                :         }
 4533 tgl@sss.pgh.pa.us         858         [ +  + ]:            482 :         else if (strcmp(defel->defname, "is_template") == 0)
                                859                 :                :         {
  835 peter@eisentraut.org      860         [ -  + ]:             60 :             if (istemplateEl)
 1962 dean.a.rasheed@gmail      861                 :UBC           0 :                 errorConflictingDefElem(defel, pstate);
  835 peter@eisentraut.org      862                 :CBC          60 :             istemplateEl = defel;
                                863                 :                :         }
 4533 tgl@sss.pgh.pa.us         864         [ +  + ]:            422 :         else if (strcmp(defel->defname, "allow_connections") == 0)
                                865                 :                :         {
  835 peter@eisentraut.org      866         [ -  + ]:             59 :             if (allowconnectionsEl)
 1962 dean.a.rasheed@gmail      867                 :UBC           0 :                 errorConflictingDefElem(defel, pstate);
  835 peter@eisentraut.org      868                 :CBC          59 :             allowconnectionsEl = defel;
                                869                 :                :         }
 4533 tgl@sss.pgh.pa.us         870         [ -  + ]:            363 :         else if (strcmp(defel->defname, "connection_limit") == 0)
                                871                 :                :         {
  835 peter@eisentraut.org      872         [ #  # ]:UBC           0 :             if (connlimitEl)
 1962 dean.a.rasheed@gmail      873                 :              0 :                 errorConflictingDefElem(defel, pstate);
  835 peter@eisentraut.org      874                 :              0 :             connlimitEl = defel;
                                875                 :                :         }
 1748 peter@eisentraut.org      876         [ +  + ]:CBC         363 :         else if (strcmp(defel->defname, "collation_version") == 0)
                                877                 :                :         {
  835                           878         [ -  + ]:             34 :             if (collversionEl)
 1748 peter@eisentraut.org      879                 :UBC           0 :                 errorConflictingDefElem(defel, pstate);
  835 peter@eisentraut.org      880                 :CBC          34 :             collversionEl = defel;
                                881                 :                :         }
 8198 tgl@sss.pgh.pa.us         882         [ -  + ]:            329 :         else if (strcmp(defel->defname, "location") == 0)
                                883                 :                :         {
 8198 tgl@sss.pgh.pa.us         884         [ #  # ]:UBC           0 :             ereport(WARNING,
                                885                 :                :                     (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
                                886                 :                :                      errmsg("LOCATION is not supported anymore"),
                                887                 :                :                      errhint("Consider using tablespaces instead."),
                                888                 :                :                      parser_errposition(pstate, defel->location)));
                                889                 :                :         }
 1769 rhaas@postgresql.org      890         [ +  + ]:CBC         329 :         else if (strcmp(defel->defname, "oid") == 0)
                                891                 :                :         {
 1485 tgl@sss.pgh.pa.us         892                 :            155 :             dboid = defGetObjectId(defel);
                                893                 :                : 
                                894                 :                :             /*
                                895                 :                :              * We don't normally permit new databases to be created with
                                896                 :                :              * system-assigned OIDs. pg_upgrade tries to preserve database
                                897                 :                :              * OIDs, so we can't allow any database to be created with an OID
                                898                 :                :              * that might be in use in a freshly-initialized cluster created
                                899                 :                :              * by some future version. We assume all such OIDs will be from
                                900                 :                :              * the system-managed OID range.
                                901                 :                :              *
                                902                 :                :              * As an exception, however, we permit any OID to be assigned when
                                903                 :                :              * allow_system_table_mods=on (so that initdb can assign system
                                904                 :                :              * OIDs to template0 and postgres) or when performing a binary
                                905                 :                :              * upgrade (so that pg_upgrade can preserve whatever OIDs it finds
                                906                 :                :              * in the source cluster).
                                907                 :                :              */
 1769 rhaas@postgresql.org      908         [ +  + ]:            155 :             if (dboid < FirstNormalObjectId &&
                                909   [ +  +  -  + ]:            138 :                 !allowSystemTableMods && !IsBinaryUpgrade)
 1769 rhaas@postgresql.org      910         [ #  # ]:UBC           0 :                 ereport(ERROR,
                                911                 :                :                         (errcode(ERRCODE_INVALID_PARAMETER_VALUE)),
                                912                 :                :                         errmsg("OIDs less than %u are reserved for system objects", FirstNormalObjectId));
                                913                 :                :         }
 1705 rhaas@postgresql.org      914         [ +  - ]:CBC         174 :         else if (strcmp(defel->defname, "strategy") == 0)
                                915                 :                :         {
  835 peter@eisentraut.org      916         [ -  + ]:            174 :             if (strategyEl)
 1705 rhaas@postgresql.org      917                 :UBC           0 :                 errorConflictingDefElem(defel, pstate);
  835 peter@eisentraut.org      918                 :CBC         174 :             strategyEl = defel;
                                919                 :                :         }
                                920                 :                :         else
 4533 tgl@sss.pgh.pa.us         921         [ #  # ]:UBC           0 :             ereport(ERROR,
                                922                 :                :                     (errcode(ERRCODE_SYNTAX_ERROR),
                                923                 :                :                      errmsg("option \"%s\" not recognized", defel->defname),
                                924                 :                :                      parser_errposition(pstate, defel->location)));
                                925                 :                :     }
                                926                 :                : 
  835 peter@eisentraut.org      927   [ +  +  +  - ]:CBC         472 :     if (ownerEl && ownerEl->arg)
                                928                 :              1 :         dbowner = defGetString(ownerEl);
                                929   [ +  +  +  - ]:            472 :     if (templateEl && templateEl->arg)
                                930                 :            216 :         dbtemplate = defGetString(templateEl);
                                931   [ +  +  +  - ]:            472 :     if (encodingEl && encodingEl->arg)
                                932                 :                :     {
                                933                 :                :         const char *encoding_name;
                                934                 :                : 
                                935         [ -  + ]:             69 :         if (IsA(encodingEl->arg, Integer))
                                936                 :                :         {
  835 peter@eisentraut.org      937                 :UBC           0 :             encoding = defGetInt32(encodingEl);
 8792 tgl@sss.pgh.pa.us         938                 :              0 :             encoding_name = pg_encoding_to_char(encoding);
                                939         [ #  # ]:              0 :             if (strcmp(encoding_name, "") == 0 ||
                                940         [ #  # ]:              0 :                 pg_valid_server_encoding(encoding_name) < 0)
 8534                           941         [ #  # ]:              0 :                 ereport(ERROR,
                                942                 :                :                         (errcode(ERRCODE_UNDEFINED_OBJECT),
                                943                 :                :                          errmsg("%d is not a valid encoding code",
                                944                 :                :                                 encoding),
                                945                 :                :                          parser_errposition(pstate, encodingEl->location)));
                                946                 :                :         }
                                947                 :                :         else
                                948                 :                :         {
  835 peter@eisentraut.org      949                 :CBC          69 :             encoding_name = defGetString(encodingEl);
 6986 tgl@sss.pgh.pa.us         950                 :             69 :             encoding = pg_valid_server_encoding(encoding_name);
                                951         [ -  + ]:             69 :             if (encoding < 0)
 8534 tgl@sss.pgh.pa.us         952         [ #  # ]:UBC           0 :                 ereport(ERROR,
                                953                 :                :                         (errcode(ERRCODE_UNDEFINED_OBJECT),
                                954                 :                :                          errmsg("%s is not a valid encoding name",
                                955                 :                :                                 encoding_name),
                                956                 :                :                          parser_errposition(pstate, encodingEl->location)));
                                957                 :                :         }
                                958                 :                :     }
  835 peter@eisentraut.org      959   [ +  +  +  - ]:CBC         472 :     if (localeEl && localeEl->arg)
                                960                 :                :     {
                                961                 :             69 :         dbcollate = defGetString(localeEl);
                                962                 :             69 :         dbctype = defGetString(localeEl);
                                963                 :             69 :         dblocale = defGetString(localeEl);
                                964                 :                :     }
                                965   [ +  +  +  - ]:            472 :     if (builtinlocaleEl && builtinlocaleEl->arg)
                                966                 :              9 :         dblocale = defGetString(builtinlocaleEl);
                                967   [ +  +  +  - ]:            472 :     if (collateEl && collateEl->arg)
                                968                 :             12 :         dbcollate = defGetString(collateEl);
                                969   [ +  +  +  - ]:            472 :     if (ctypeEl && ctypeEl->arg)
                                970                 :             12 :         dbctype = defGetString(ctypeEl);
                                971   [ +  +  +  - ]:            472 :     if (iculocaleEl && iculocaleEl->arg)
                                972                 :              5 :         dblocale = defGetString(iculocaleEl);
                                973   [ +  +  +  - ]:            472 :     if (icurulesEl && icurulesEl->arg)
                                974                 :              1 :         dbicurules = defGetString(icurulesEl);
                                975   [ +  +  +  - ]:            472 :     if (locproviderEl && locproviderEl->arg)
                                976                 :                :     {
                                977                 :             75 :         char       *locproviderstr = defGetString(locproviderEl);
                                978                 :                : 
  990 jdavis@postgresql.or      979         [ +  + ]:             75 :         if (pg_strcasecmp(locproviderstr, "builtin") == 0)
                                980                 :             19 :             dblocprovider = COLLPROVIDER_BUILTIN;
                                981         [ +  + ]:             56 :         else if (pg_strcasecmp(locproviderstr, "icu") == 0)
 1717 peter@eisentraut.org      982                 :              8 :             dblocprovider = COLLPROVIDER_ICU;
                                983         [ +  + ]:             48 :         else if (pg_strcasecmp(locproviderstr, "libc") == 0)
                                984                 :             47 :             dblocprovider = COLLPROVIDER_LIBC;
                                985                 :                :         else
                                986         [ +  - ]:              1 :             ereport(ERROR,
                                987                 :                :                     (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
                                988                 :                :                      errmsg("unrecognized locale provider: %s",
                                989                 :                :                             locproviderstr)));
                                990                 :                :     }
  835                           991   [ +  +  +  - ]:            471 :     if (istemplateEl && istemplateEl->arg)
                                992                 :             60 :         dbistemplate = defGetBoolean(istemplateEl);
                                993   [ +  +  +  - ]:            471 :     if (allowconnectionsEl && allowconnectionsEl->arg)
                                994                 :             59 :         dballowconnections = defGetBoolean(allowconnectionsEl);
                                995   [ -  +  -  - ]:            471 :     if (connlimitEl && connlimitEl->arg)
                                996                 :                :     {
  835 peter@eisentraut.org      997                 :UBC           0 :         dbconnlimit = defGetInt32(connlimitEl);
 1234 andres@anarazel.de        998         [ #  # ]:              0 :         if (dbconnlimit < DATCONNLIMIT_UNLIMITED)
 6511 heikki.linnakangas@i      999         [ #  # ]:              0 :             ereport(ERROR,
                               1000                 :                :                     (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
                               1001                 :                :                      errmsg("invalid connection limit: %d", dbconnlimit)));
                               1002                 :                :     }
  835 peter@eisentraut.org     1003         [ +  + ]:CBC         471 :     if (collversionEl)
                               1004                 :             34 :         dbcollversion = defGetString(collversionEl);
                               1005                 :                : 
                               1006                 :                :     /* obtain OID of proposed owner */
 9043 tgl@sss.pgh.pa.us        1007         [ +  + ]:            471 :     if (dbowner)
 5959 rhaas@postgresql.org     1008                 :              1 :         datdba = get_role_oid(dbowner, false);
                               1009                 :                :     else
 9043 tgl@sss.pgh.pa.us        1010                 :            470 :         datdba = GetUserId();
                               1011                 :                : 
                               1012                 :                :     /*
                               1013                 :                :      * To create a database, must have createdb privilege and must be able to
                               1014                 :                :      * become the target role (this does not imply that the target role itself
                               1015                 :                :      * must have createdb privilege).  The latter provision guards against
                               1016                 :                :      * "giveaway" attacks.  Note that a superuser will always have both of
                               1017                 :                :      * these privileges a fortiori.
                               1018                 :                :      */
 4358 alvherre@alvh.no-ip.     1019         [ +  + ]:            471 :     if (!have_createdb_privilege())
 7807 tgl@sss.pgh.pa.us        1020         [ +  - ]:              4 :         ereport(ERROR,
                               1021                 :                :                 (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
                               1022                 :                :                  errmsg("permission denied to create database")));
                               1023                 :                : 
 1471 rhaas@postgresql.org     1024                 :            467 :     check_can_set_role(GetUserId(), datdba);
                               1025                 :                : 
                               1026                 :                :     /*
                               1027                 :                :      * Lookup database (template) to be cloned, and obtain share lock on it.
                               1028                 :                :      * ShareLock allows two CREATE DATABASEs to work from the same template
                               1029                 :                :      * concurrently, while ensuring no one is busy dropping it in parallel
                               1030                 :                :      * (which would be Very Bad since we'd likely get an incomplete copy
                               1031                 :                :      * without knowing it).  This also prevents any new connections from being
                               1032                 :                :      * made to the source until we finish copying it, so we can be sure it
                               1033                 :                :      * won't change underneath us.
                               1034                 :                :      */
 9510 tgl@sss.pgh.pa.us        1035         [ +  + ]:            467 :     if (!dbtemplate)
 3447                          1036                 :            252 :         dbtemplate = "template1"; /* Default template database name */
                               1037                 :                : 
 7513                          1038         [ -  + ]:            467 :     if (!get_db_info(dbtemplate, ShareLock,
                               1039                 :                :                      &src_dboid, &src_owner, &src_encoding,
                               1040                 :                :                      &src_istemplate, &src_allowconn, &src_hasloginevt,
                               1041                 :                :                      &src_frozenxid, &src_minmxid, &src_deftablespace,
                               1042                 :                :                      &src_collate, &src_ctype, &src_locale, &src_icurules, &src_locprovider,
                               1043                 :                :                      &src_collversion))
 8534 tgl@sss.pgh.pa.us        1044         [ #  # ]:UBC           0 :         ereport(ERROR,
                               1045                 :                :                 (errcode(ERRCODE_UNDEFINED_DATABASE),
                               1046                 :                :                  errmsg("template database \"%s\" does not exist",
                               1047                 :                :                         dbtemplate)));
                               1048                 :                : 
                               1049                 :                :     /*
                               1050                 :                :      * If the source database was in the process of being dropped, we can't
                               1051                 :                :      * use it as a template.
                               1052                 :                :      */
 1234 andres@anarazel.de       1053         [ +  + ]:CBC         467 :     if (database_is_invalid_oid(src_dboid))
                               1054         [ +  - ]:              1 :         ereport(ERROR,
                               1055                 :                :                 errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
                               1056                 :                :                 errmsg("cannot use invalid database \"%s\" as template", dbtemplate),
                               1057                 :                :                 errhint("Use DROP DATABASE to drop invalid databases."));
                               1058                 :                : 
                               1059                 :                :     /*
                               1060                 :                :      * Permission check: to copy a DB that's not marked datistemplate, you
                               1061                 :                :      * must be superuser or the owner thereof.
                               1062                 :                :      */
 9510 tgl@sss.pgh.pa.us        1063         [ +  + ]:            466 :     if (!src_istemplate)
                               1064                 :                :     {
 1476 peter@eisentraut.org     1065         [ -  + ]:             16 :         if (!object_ownercheck(DatabaseRelationId, src_dboid, GetUserId()))
 8534 tgl@sss.pgh.pa.us        1066         [ #  # ]:UBC           0 :             ereport(ERROR,
                               1067                 :                :                     (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
                               1068                 :                :                      errmsg("permission denied to copy database \"%s\"",
                               1069                 :                :                             dbtemplate)));
                               1070                 :                :     }
                               1071                 :                : 
                               1072                 :                :     /* Validate the database creation strategy. */
  835 peter@eisentraut.org     1073   [ +  +  +  - ]:CBC         466 :     if (strategyEl && strategyEl->arg)
                               1074                 :                :     {
                               1075                 :                :         char       *strategy;
                               1076                 :                : 
                               1077                 :            174 :         strategy = defGetString(strategyEl);
  951 tomas.vondra@postgre     1078         [ +  + ]:            174 :         if (pg_strcasecmp(strategy, "wal_log") == 0)
 1705 rhaas@postgresql.org     1079                 :             12 :             dbstrategy = CREATEDB_WAL_LOG;
  951 tomas.vondra@postgre     1080         [ +  + ]:            162 :         else if (pg_strcasecmp(strategy, "file_copy") == 0)
                               1081                 :                :         {
                               1082                 :                :             /*
                               1083                 :                :              * If data checksums are being enabled we must not use file_copy
                               1084                 :                :              * since it might copy source database which hasn't yet had data
                               1085                 :                :              * checksums enabled, and the destination database will be skipped
                               1086                 :                :              * as it's expected to have data checksums enabled.  Once we have
                               1087                 :                :              * an XID assigned this needs to be rechecked, but if can error
                               1088                 :                :              * out already we can save a lot of work.
                               1089                 :                :              */
  239 dgustafsson@postgres     1090         [ -  + ]:GNC         161 :             if (DataChecksumsInProgressOn())
  239 dgustafsson@postgres     1091         [ #  # ]:UNC           0 :                 ereport(ERROR,
                               1092                 :                :                         errcode(ERRCODE_INVALID_PARAMETER_VALUE),
                               1093                 :                :                         errmsg("create database strategy \"%s\" not allowed when data checksums are being enabled",
                               1094                 :                :                                strategy));
 1705 rhaas@postgresql.org     1095                 :CBC         161 :             dbstrategy = CREATEDB_FILE_COPY;
                               1096                 :                :         }
                               1097                 :                :         else
                               1098         [ +  - ]:              1 :             ereport(ERROR,
                               1099                 :                :                     (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
                               1100                 :                :                      errmsg("invalid create database strategy \"%s\"", strategy),
                               1101                 :                :                      errhint("Valid strategies are \"wal_log\" and \"file_copy\".")));
                               1102                 :                :     }
                               1103                 :                : 
                               1104                 :                :     /* If encoding or locales are defaulted, use source's setting */
 9510 tgl@sss.pgh.pa.us        1105         [ +  + ]:            465 :     if (encoding < 0)
                               1106                 :            396 :         encoding = src_encoding;
 6640 heikki.linnakangas@i     1107         [ +  + ]:            465 :     if (dbcollate == NULL)
                               1108                 :            387 :         dbcollate = src_collate;
                               1109         [ +  + ]:            465 :     if (dbctype == NULL)
                               1110                 :            387 :         dbctype = src_ctype;
 1717 peter@eisentraut.org     1111         [ +  + ]:            465 :     if (dblocprovider == '\0')
                               1112                 :            391 :         dblocprovider = src_locprovider;
  480 jdavis@postgresql.or     1113   [ +  +  +  + ]:            465 :     if (dblocale == NULL && dblocprovider == src_locprovider)
  990                          1114                 :            387 :         dblocale = src_locale;
   10                          1115   [ +  +  +  + ]:            465 :     if (dbicurules == NULL && dblocprovider == COLLPROVIDER_ICU)
 1361 peter@eisentraut.org     1116                 :             18 :         dbicurules = src_icurules;
                               1117                 :                : 
                               1118                 :                :     /* Some encodings are client only */
 9165 bruce@momjian.us         1119   [ +  -  +  -  :            465 :     if (!PG_VALID_BE_ENCODING(encoding))
                                              -  + ]
 8534 tgl@sss.pgh.pa.us        1120         [ #  # ]:UBC           0 :         ereport(ERROR,
                               1121                 :                :                 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
                               1122                 :                :                  errmsg("invalid server encoding %d", encoding)));
                               1123                 :                : 
                               1124                 :                :     /* Check that the chosen locales are valid, and get canonical spellings */
 5361 tgl@sss.pgh.pa.us        1125         [ +  + ]:CBC         465 :     if (!check_locale(LC_COLLATE, dbcollate, &canonname))
                               1126                 :                :     {
  540 jdavis@postgresql.or     1127         [ -  + ]:              1 :         if (dblocprovider == COLLPROVIDER_BUILTIN)
  540 jdavis@postgresql.or     1128         [ #  # ]:UBC           0 :             ereport(ERROR,
                               1129                 :                :                     (errcode(ERRCODE_WRONG_OBJECT_TYPE),
                               1130                 :                :                      errmsg("invalid LC_COLLATE locale name: \"%s\"", dbcollate),
                               1131                 :                :                      errhint("If the locale name is specific to the builtin provider, use BUILTIN_LOCALE.")));
  540 jdavis@postgresql.or     1132         [ -  + ]:CBC           1 :         else if (dblocprovider == COLLPROVIDER_ICU)
  540 jdavis@postgresql.or     1133         [ #  # ]:UBC           0 :             ereport(ERROR,
                               1134                 :                :                     (errcode(ERRCODE_WRONG_OBJECT_TYPE),
                               1135                 :                :                      errmsg("invalid LC_COLLATE locale name: \"%s\"", dbcollate),
                               1136                 :                :                      errhint("If the locale name is specific to the ICU provider, use ICU_LOCALE.")));
                               1137                 :                :         else
  540 jdavis@postgresql.or     1138         [ +  - ]:CBC           1 :             ereport(ERROR,
                               1139                 :                :                     (errcode(ERRCODE_WRONG_OBJECT_TYPE),
                               1140                 :                :                      errmsg("invalid LC_COLLATE locale name: \"%s\"", dbcollate)));
                               1141                 :                :     }
 5361 tgl@sss.pgh.pa.us        1142                 :            464 :     dbcollate = canonname;
                               1143         [ +  + ]:            464 :     if (!check_locale(LC_CTYPE, dbctype, &canonname))
                               1144                 :                :     {
  540 jdavis@postgresql.or     1145         [ -  + ]:              1 :         if (dblocprovider == COLLPROVIDER_BUILTIN)
  540 jdavis@postgresql.or     1146         [ #  # ]:UBC           0 :             ereport(ERROR,
                               1147                 :                :                     (errcode(ERRCODE_WRONG_OBJECT_TYPE),
                               1148                 :                :                      errmsg("invalid LC_CTYPE locale name: \"%s\"", dbctype),
                               1149                 :                :                      errhint("If the locale name is specific to the builtin provider, use BUILTIN_LOCALE.")));
  540 jdavis@postgresql.or     1150         [ -  + ]:CBC           1 :         else if (dblocprovider == COLLPROVIDER_ICU)
  540 jdavis@postgresql.or     1151         [ #  # ]:UBC           0 :             ereport(ERROR,
                               1152                 :                :                     (errcode(ERRCODE_WRONG_OBJECT_TYPE),
                               1153                 :                :                      errmsg("invalid LC_CTYPE locale name: \"%s\"", dbctype),
                               1154                 :                :                      errhint("If the locale name is specific to the ICU provider, use ICU_LOCALE.")));
                               1155                 :                :         else
  540 jdavis@postgresql.or     1156         [ +  - ]:CBC           1 :             ereport(ERROR,
                               1157                 :                :                     (errcode(ERRCODE_WRONG_OBJECT_TYPE),
                               1158                 :                :                      errmsg("invalid LC_CTYPE locale name: \"%s\"", dbctype)));
                               1159                 :                :     }
                               1160                 :                : 
 5361 tgl@sss.pgh.pa.us        1161                 :            463 :     dbctype = canonname;
                               1162                 :                : 
 5768 peter_e@gmx.net          1163                 :            463 :     check_encoding_locale_matches(encoding, dbcollate, dbctype);
                               1164                 :                : 
                               1165                 :                :     /* validate provider-specific parameters */
  990 jdavis@postgresql.or     1166         [ +  + ]:            463 :     if (dblocprovider != COLLPROVIDER_BUILTIN)
                               1167                 :                :     {
  835 peter@eisentraut.org     1168         [ -  + ]:            430 :         if (builtinlocaleEl)
  990 jdavis@postgresql.or     1169         [ #  # ]:UBC           0 :             ereport(ERROR,
                               1170                 :                :                     (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
                               1171                 :                :                      errmsg("BUILTIN_LOCALE cannot be specified unless locale provider is builtin")));
                               1172                 :                :     }
                               1173                 :                : 
  942 jdavis@postgresql.or     1174         [ +  + ]:CBC         463 :     if (dblocprovider != COLLPROVIDER_ICU)
                               1175                 :                :     {
  835 peter@eisentraut.org     1176         [ +  + ]:            445 :         if (iculocaleEl)
  990 jdavis@postgresql.or     1177         [ +  - ]:              1 :             ereport(ERROR,
                               1178                 :                :                     (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
                               1179                 :                :                      errmsg("ICU locale cannot be specified unless locale provider is ICU")));
                               1180                 :                : 
                               1181         [ +  + ]:            444 :         if (dbicurules)
                               1182         [ +  - ]:              1 :             ereport(ERROR,
                               1183                 :                :                     (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
                               1184                 :                :                      errmsg("ICU rules cannot be specified unless locale provider is ICU")));
                               1185                 :                :     }
                               1186                 :                : 
                               1187                 :                :     /* validate and canonicalize locale for the provider */
                               1188         [ +  + ]:            461 :     if (dblocprovider == COLLPROVIDER_BUILTIN)
                               1189                 :                :     {
                               1190                 :                :         /*
                               1191                 :                :          * This would happen if template0 uses the libc provider but the new
                               1192                 :                :          * database uses builtin.
                               1193                 :                :          */
                               1194         [ +  + ]:             31 :         if (!dblocale)
                               1195         [ +  - ]:              1 :             ereport(ERROR,
                               1196                 :                :                     (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
                               1197                 :                :                      errmsg("LOCALE or BUILTIN_LOCALE must be specified")));
                               1198                 :                : 
                               1199                 :             30 :         dblocale = builtin_validate_locale(encoding, dblocale);
                               1200                 :                :     }
                               1201         [ +  + ]:            430 :     else if (dblocprovider == COLLPROVIDER_ICU)
                               1202                 :                :     {
 1534 peter@eisentraut.org     1203         [ +  + ]:             18 :         if (!(is_encoding_supported_by_icu(encoding)))
                               1204         [ +  - ]:              1 :             ereport(ERROR,
                               1205                 :                :                     (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
                               1206                 :                :                      errmsg("encoding \"%s\" is not supported with ICU provider",
                               1207                 :                :                             pg_encoding_to_char(encoding))));
                               1208                 :                : 
                               1209                 :                :         /*
                               1210                 :                :          * This would happen if template0 uses the libc provider but the new
                               1211                 :                :          * database uses icu.
                               1212                 :                :          */
  994 jdavis@postgresql.or     1213         [ +  + ]:             17 :         if (!dblocale)
 1717 peter@eisentraut.org     1214         [ +  - ]:              1 :             ereport(ERROR,
                               1215                 :                :                     (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
                               1216                 :                :                      errmsg("LOCALE or ICU_LOCALE must be specified")));
                               1217                 :                : 
                               1218                 :                :         /*
                               1219                 :                :          * During binary upgrade, or when the locale came from the template
                               1220                 :                :          * database, preserve locale string. Otherwise, canonicalize to a
                               1221                 :                :          * language tag.
                               1222                 :                :          */
  994 jdavis@postgresql.or     1223   [ +  -  +  + ]:             16 :         if (!IsBinaryUpgrade && dblocale != src_locale)
                               1224                 :                :         {
                               1225                 :              7 :             char       *langtag = icu_language_tag(dblocale,
                               1226                 :                :                                                    icu_validation_level);
                               1227                 :                : 
                               1228   [ +  +  +  + ]:              7 :             if (langtag && strcmp(dblocale, langtag) != 0)
                               1229                 :                :             {
 1334                          1230         [ +  - ]:              3 :                 ereport(NOTICE,
                               1231                 :                :                         (errmsg("using standard form \"%s\" for ICU locale \"%s\"",
                               1232                 :                :                                 langtag, dblocale)));
                               1233                 :                : 
  994                          1234                 :              3 :                 dblocale = langtag;
                               1235                 :                :             }
                               1236                 :                :         }
                               1237                 :                : 
                               1238                 :             16 :         icu_validate_locale(dblocale);
                               1239                 :                :     }
                               1240                 :                : 
                               1241                 :                :     /* for libc, locale comes from datcollate and datctype */
  990                          1242         [ +  + ]:            456 :     if (dblocprovider == COLLPROVIDER_LIBC)
                               1243                 :            412 :         dblocale = NULL;
                               1244                 :                : 
                               1245                 :                :     /*
                               1246                 :                :      * Check that the new encoding and locale settings match the source
                               1247                 :                :      * database.  We insist on this because we simply copy the source data ---
                               1248                 :                :      * any non-ASCII data would be wrongly encoded, and any indexes sorted
                               1249                 :                :      * according to the source locale would be wrong.
                               1250                 :                :      *
                               1251                 :                :      * However, we assume that template0 doesn't contain any non-ASCII data
                               1252                 :                :      * nor any indexes that depend on collation or ctype, so template0 can be
                               1253                 :                :      * used as template for creating a database with any encoding or locale.
                               1254                 :                :      */
 6640 heikki.linnakangas@i     1255         [ +  + ]:            456 :     if (strcmp(dbtemplate, "template0") != 0)
                               1256                 :                :     {
 6415 tgl@sss.pgh.pa.us        1257         [ -  + ]:            270 :         if (encoding != src_encoding)
 6415 tgl@sss.pgh.pa.us        1258         [ #  # ]:UBC           0 :             ereport(ERROR,
                               1259                 :                :                     (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
                               1260                 :                :                      errmsg("new encoding (%s) is incompatible with the encoding of the template database (%s)",
                               1261                 :                :                             pg_encoding_to_char(encoding),
                               1262                 :                :                             pg_encoding_to_char(src_encoding)),
                               1263                 :                :                      errhint("Use the same encoding as in the template database, or use template0 as template.")));
                               1264                 :                : 
 6428 tgl@sss.pgh.pa.us        1265         [ +  + ]:CBC         270 :         if (strcmp(dbcollate, src_collate) != 0)
 6640 heikki.linnakangas@i     1266         [ +  - ]:              1 :             ereport(ERROR,
                               1267                 :                :                     (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
                               1268                 :                :                      errmsg("new collation (%s) is incompatible with the collation of the template database (%s)",
                               1269                 :                :                             dbcollate, src_collate),
                               1270                 :                :                      errhint("Use the same collation as in the template database, or use template0 as template.")));
                               1271                 :                : 
 6428 tgl@sss.pgh.pa.us        1272         [ -  + ]:            269 :         if (strcmp(dbctype, src_ctype) != 0)
 6640 heikki.linnakangas@i     1273         [ #  # ]:UBC           0 :             ereport(ERROR,
                               1274                 :                :                     (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
                               1275                 :                :                      errmsg("new LC_CTYPE (%s) is incompatible with the LC_CTYPE of the template database (%s)",
                               1276                 :                :                             dbctype, src_ctype),
                               1277                 :                :                      errhint("Use the same LC_CTYPE as in the template database, or use template0 as template.")));
                               1278                 :                : 
 1717 peter@eisentraut.org     1279         [ +  + ]:CBC         269 :         if (dblocprovider != src_locprovider)
                               1280         [ +  - ]:              1 :             ereport(ERROR,
                               1281                 :                :                     (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
                               1282                 :                :                      errmsg("new locale provider (%s) does not match locale provider of the template database (%s)",
                               1283                 :                :                             collprovider_name(dblocprovider), collprovider_name(src_locprovider)),
                               1284                 :                :                      errhint("Use the same locale provider as in the template database, or use template0 as template.")));
                               1285                 :                : 
                               1286         [ +  + ]:            268 :         if (dblocprovider == COLLPROVIDER_ICU)
                               1287                 :                :         {
                               1288                 :                :             char       *val1;
                               1289                 :                :             char       *val2;
                               1290                 :                : 
  994 jdavis@postgresql.or     1291         [ -  + ]:              8 :             Assert(dblocale);
                               1292         [ -  + ]:              8 :             Assert(src_locale);
                               1293         [ -  + ]:              8 :             if (strcmp(dblocale, src_locale) != 0)
 1717 peter@eisentraut.org     1294         [ #  # ]:UBC           0 :                 ereport(ERROR,
                               1295                 :                :                         (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
                               1296                 :                :                          errmsg("new ICU locale (%s) is incompatible with the ICU locale of the template database (%s)",
                               1297                 :                :                                 dblocale, src_locale),
                               1298                 :                :                          errhint("Use the same ICU locale as in the template database, or use template0 as template.")));
                               1299                 :                : 
 1361 peter@eisentraut.org     1300                 :CBC           8 :             val1 = dbicurules;
                               1301         [ +  + ]:              8 :             if (!val1)
                               1302                 :              6 :                 val1 = "";
                               1303                 :              8 :             val2 = src_icurules;
                               1304         [ +  + ]:              8 :             if (!val2)
                               1305                 :              6 :                 val2 = "";
                               1306         [ -  + ]:              8 :             if (strcmp(val1, val2) != 0)
 1361 peter@eisentraut.org     1307         [ #  # ]:UBC           0 :                 ereport(ERROR,
                               1308                 :                :                         (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
                               1309                 :                :                          errmsg("new ICU collation rules (%s) are incompatible with the ICU collation rules of the template database (%s)",
                               1310                 :                :                                 val1, val2),
                               1311                 :                :                          errhint("Use the same ICU collation rules as in the template database, or use template0 as template.")));
                               1312                 :                :         }
                               1313                 :                :     }
                               1314                 :                : 
                               1315                 :                :     /*
                               1316                 :                :      * If we got a collation version for the template database, check that it
                               1317                 :                :      * matches the actual OS collation version.  Otherwise error; the user
                               1318                 :                :      * needs to fix the template database first.  Don't complain if a
                               1319                 :                :      * collation version was specified explicitly as a statement option; that
                               1320                 :                :      * is used by pg_upgrade to reproduce the old state exactly.
                               1321                 :                :      *
                               1322                 :                :      * (If the template database has no collation version, then either the
                               1323                 :                :      * platform/provider does not support collation versioning, or it's
                               1324                 :                :      * template0, for which we stipulate that it does not contain
                               1325                 :                :      * collation-using objects.)
                               1326                 :                :      */
  835 peter@eisentraut.org     1327   [ +  +  +  - ]:CBC         454 :     if (src_collversion && !collversionEl)
                               1328                 :                :     {
                               1329                 :                :         char       *actual_versionstr;
                               1330                 :                :         const char *locale;
                               1331                 :                : 
  990 jdavis@postgresql.or     1332         [ +  + ]:            181 :         if (dblocprovider == COLLPROVIDER_LIBC)
                               1333                 :            169 :             locale = dbcollate;
                               1334                 :                :         else
                               1335                 :             12 :             locale = dblocale;
                               1336                 :                : 
                               1337                 :            181 :         actual_versionstr = get_collation_actual_version(dblocprovider, locale);
 1748 peter@eisentraut.org     1338         [ -  + ]:            181 :         if (!actual_versionstr)
 1748 peter@eisentraut.org     1339         [ #  # ]:UBC           0 :             ereport(ERROR,
                               1340                 :                :                     (errmsg("template database \"%s\" has a collation version, but no actual collation version could be determined",
                               1341                 :                :                             dbtemplate)));
                               1342                 :                : 
 1748 peter@eisentraut.org     1343         [ -  + ]:CBC         181 :         if (strcmp(actual_versionstr, src_collversion) != 0)
 1748 peter@eisentraut.org     1344         [ #  # ]:UBC           0 :             ereport(ERROR,
                               1345                 :                :                     (errmsg("template database \"%s\" has a collation version mismatch",
                               1346                 :                :                             dbtemplate),
                               1347                 :                :                      errdetail("The template database was created using collation version %s, "
                               1348                 :                :                                "but the operating system provides version %s.",
                               1349                 :                :                                src_collversion, actual_versionstr),
                               1350                 :                :                      errhint("Rebuild all objects in the template database that use the default collation and run "
                               1351                 :                :                              "ALTER DATABASE %s REFRESH COLLATION VERSION, "
                               1352                 :                :                              "or build PostgreSQL with the right library version.",
                               1353                 :                :                              quote_identifier(dbtemplate))));
                               1354                 :                :     }
                               1355                 :                : 
 1748 peter@eisentraut.org     1356         [ +  + ]:CBC         454 :     if (dbcollversion == NULL)
                               1357                 :            420 :         dbcollversion = src_collversion;
                               1358                 :                : 
                               1359                 :                :     /*
                               1360                 :                :      * Normally, we copy the collation version from the template database.
                               1361                 :                :      * This last resort only applies if the template database does not have a
                               1362                 :                :      * collation version, which is normally only the case for template0.
                               1363                 :                :      */
                               1364         [ +  + ]:            454 :     if (dbcollversion == NULL)
                               1365                 :                :     {
                               1366                 :                :         const char *locale;
                               1367                 :                : 
  990 jdavis@postgresql.or     1368         [ +  + ]:            239 :         if (dblocprovider == COLLPROVIDER_LIBC)
                               1369                 :            215 :             locale = dbcollate;
                               1370                 :                :         else
                               1371                 :             24 :             locale = dblocale;
                               1372                 :                : 
                               1373                 :            239 :         dbcollversion = get_collation_actual_version(dblocprovider, locale);
                               1374                 :                :     }
                               1375                 :                : 
                               1376                 :                :     /* Resolve default tablespace for new database */
  835 peter@eisentraut.org     1377   [ +  +  +  - ]:            454 :     if (tablespacenameEl && tablespacenameEl->arg)
 8198 tgl@sss.pgh.pa.us        1378                 :             17 :     {
                               1379                 :                :         char       *tablespacename;
                               1380                 :                :         AclResult   aclresult;
                               1381                 :                : 
  835 peter@eisentraut.org     1382                 :             17 :         tablespacename = defGetString(tablespacenameEl);
 5959 rhaas@postgresql.org     1383                 :             17 :         dst_deftablespace = get_tablespace_oid(tablespacename, false);
                               1384                 :                :         /* check permissions */
 1476 peter@eisentraut.org     1385                 :             17 :         aclresult = object_aclcheck(TableSpaceRelationId, dst_deftablespace, GetUserId(),
                               1386                 :                :                                     ACL_CREATE);
 8126 bruce@momjian.us         1387         [ -  + ]:             17 :         if (aclresult != ACLCHECK_OK)
 3283 peter_e@gmx.net          1388                 :UBC           0 :             aclcheck_error(aclresult, OBJECT_TABLESPACE,
                               1389                 :                :                            tablespacename);
                               1390                 :                : 
                               1391                 :                :         /* pg_global must never be the default tablespace */
 6987 tgl@sss.pgh.pa.us        1392         [ -  + ]:CBC          17 :         if (dst_deftablespace == GLOBALTABLESPACE_OID)
 6987 tgl@sss.pgh.pa.us        1393         [ #  # ]:UBC           0 :             ereport(ERROR,
                               1394                 :                :                     (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
                               1395                 :                :                      errmsg("pg_global cannot be used as default tablespace")));
                               1396                 :                : 
                               1397                 :                :         /*
                               1398                 :                :          * If we are trying to change the default tablespace of the template,
                               1399                 :                :          * we require that the template not have any files in the new default
                               1400                 :                :          * tablespace.  This is necessary because otherwise the copied
                               1401                 :                :          * database would contain pg_class rows that refer to its default
                               1402                 :                :          * tablespace both explicitly (by OID) and implicitly (as zero), which
                               1403                 :                :          * would cause problems.  For example another CREATE DATABASE using
                               1404                 :                :          * the copied database as template, and trying to change its default
                               1405                 :                :          * tablespace again, would yield outright incorrect results (it would
                               1406                 :                :          * improperly move tables to the new default tablespace that should
                               1407                 :                :          * stay in the same tablespace).
                               1408                 :                :          */
 8077 tgl@sss.pgh.pa.us        1409         [ +  - ]:CBC          17 :         if (dst_deftablespace != src_deftablespace)
                               1410                 :                :         {
                               1411                 :                :             char       *srcpath;
                               1412                 :                :             struct stat st;
                               1413                 :                : 
                               1414                 :             17 :             srcpath = GetDatabasePath(src_dboid, dst_deftablespace);
                               1415                 :                : 
                               1416         [ -  + ]:             17 :             if (stat(srcpath, &st) == 0 &&
 8077 tgl@sss.pgh.pa.us        1417         [ #  # ]:UBC           0 :                 S_ISDIR(st.st_mode) &&
                               1418         [ #  # ]:              0 :                 !directory_is_empty(srcpath))
                               1419         [ #  # ]:              0 :                 ereport(ERROR,
                               1420                 :                :                         (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
                               1421                 :                :                          errmsg("cannot assign new default tablespace \"%s\"",
                               1422                 :                :                                 tablespacename),
                               1423                 :                :                          errdetail("There is a conflict because database \"%s\" already has some tables in this tablespace.",
                               1424                 :                :                                    dbtemplate)));
 8077 tgl@sss.pgh.pa.us        1425                 :CBC          17 :             pfree(srcpath);
                               1426                 :                :         }
                               1427                 :                :     }
                               1428                 :                :     else
                               1429                 :                :     {
                               1430                 :                :         /* Use template database's default tablespace */
 8198                          1431                 :            437 :         dst_deftablespace = src_deftablespace;
                               1432                 :                :         /* Note there is no additional permission check in this path */
                               1433                 :                :     }
                               1434                 :                : 
                               1435                 :                :     /*
                               1436                 :                :      * If built with appropriate switch, whine when regression-testing
                               1437                 :                :      * conventions for database names are violated.  But don't complain during
                               1438                 :                :      * initdb.
                               1439                 :                :      */
                               1440                 :                : #ifdef ENFORCE_REGRESSION_TEST_NAME_RESTRICTIONS
                               1441                 :                :     if (IsUnderPostmaster && strstr(dbname, "regression") == NULL)
                               1442                 :                :         elog(WARNING, "databases created by regression test cases should have names including \"regression\"");
                               1443                 :                : #endif
                               1444                 :                : 
                               1445                 :                :     /*
                               1446                 :                :      * Check for db name conflict.  This is just to give a more friendly error
                               1447                 :                :      * message than "unique index violation".  There's a race condition but
                               1448                 :                :      * we're willing to accept the less friendly message in that case.
                               1449                 :                :      */
 5959 rhaas@postgresql.org     1450         [ +  + ]:            454 :     if (OidIsValid(get_database_oid(dbname, true)))
 7513 tgl@sss.pgh.pa.us        1451         [ +  - ]:              1 :         ereport(ERROR,
                               1452                 :                :                 (errcode(ERRCODE_DUPLICATE_DATABASE),
                               1453                 :                :                  errmsg("database \"%s\" already exists", dbname)));
                               1454                 :                : 
                               1455                 :                :     /*
                               1456                 :                :      * The source DB can't have any active backends, except this one
                               1457                 :                :      * (exception is to allow CREATE DB while connected to template1).
                               1458                 :                :      * Otherwise we might copy inconsistent data.
                               1459                 :                :      *
                               1460                 :                :      * This should be last among the basic error checks, because it involves
                               1461                 :                :      * potential waiting; we may as well throw an error first if we're gonna
                               1462                 :                :      * throw one.
                               1463                 :                :      */
 6690                          1464         [ +  + ]:            453 :     if (CountOtherDBBackends(src_dboid, &notherbackends, &npreparedxacts))
 7120                          1465         [ +  - ]:              1 :         ereport(ERROR,
                               1466                 :                :                 (errcode(ERRCODE_OBJECT_IN_USE),
                               1467                 :                :                  errmsg("source database \"%s\" is being accessed by other users",
                               1468                 :                :                         dbtemplate),
                               1469                 :                :                  errdetail_busy_db(notherbackends, npreparedxacts)));
                               1470                 :                : 
                               1471                 :                :     /*
                               1472                 :                :      * Select an OID for the new database, checking that it doesn't have a
                               1473                 :                :      * filename conflict with anything already existing in the tablespace
                               1474                 :                :      * directories.
                               1475                 :                :      */
 2868 andres@anarazel.de       1476                 :            452 :     pg_database_rel = table_open(DatabaseRelationId, RowExclusiveLock);
                               1477                 :                : 
                               1478                 :                :     /*
                               1479                 :                :      * If database OID is configured, check if the OID is already in use or
                               1480                 :                :      * data directory already exists.
                               1481                 :                :      */
 1769 rhaas@postgresql.org     1482         [ +  + ]:            452 :     if (OidIsValid(dboid))
                               1483                 :                :     {
                               1484                 :            155 :         char       *existing_dbname = get_database_name(dboid);
                               1485                 :                : 
                               1486         [ -  + ]:            155 :         if (existing_dbname != NULL)
 1769 rhaas@postgresql.org     1487         [ #  # ]:UBC           0 :             ereport(ERROR,
                               1488                 :                :                     (errcode(ERRCODE_INVALID_PARAMETER_VALUE)),
                               1489                 :                :                     errmsg("database OID %u is already in use by database \"%s\"",
                               1490                 :                :                            dboid, existing_dbname));
                               1491                 :                : 
 1769 rhaas@postgresql.org     1492         [ -  + ]:CBC         155 :         if (check_db_file_conflict(dboid))
 1769 rhaas@postgresql.org     1493         [ #  # ]:UBC           0 :             ereport(ERROR,
                               1494                 :                :                     (errcode(ERRCODE_INVALID_PARAMETER_VALUE)),
                               1495                 :                :                     errmsg("data directory with the specified OID %u already exists", dboid));
                               1496                 :                :     }
                               1497                 :                :     else
                               1498                 :                :     {
                               1499                 :                :         /* Select an OID for the new database if is not explicitly configured. */
                               1500                 :                :         do
                               1501                 :                :         {
 1769 rhaas@postgresql.org     1502                 :CBC         297 :             dboid = GetNewOidWithIndex(pg_database_rel, DatabaseOidIndexId,
                               1503                 :                :                                        Anum_pg_database_oid);
                               1504         [ -  + ]:            297 :         } while (check_db_file_conflict(dboid));
                               1505                 :                :     }
                               1506                 :                : 
                               1507                 :                :     /*
                               1508                 :                :      * Insert a new tuple into pg_database.  This establishes our ownership of
                               1509                 :                :      * the new database name (anyone else trying to insert the same name will
                               1510                 :                :      * block on the unique index, and fail after we commit).
                               1511                 :                :      */
                               1512                 :                : 
  990 jdavis@postgresql.or     1513   [ +  +  -  +  :            452 :     Assert((dblocprovider != COLLPROVIDER_LIBC && dblocale) ||
                                        +  -  -  + ]
                               1514                 :                :            (dblocprovider == COLLPROVIDER_LIBC && !dblocale));
                               1515                 :                : 
                               1516                 :                :     /* Form tuple */
 2930 andres@anarazel.de       1517                 :            452 :     new_record[Anum_pg_database_oid - 1] = ObjectIdGetDatum(dboid);
 7513 tgl@sss.pgh.pa.us        1518                 :            452 :     new_record[Anum_pg_database_datname - 1] =
                               1519                 :            452 :         DirectFunctionCall1(namein, CStringGetDatum(dbname));
                               1520                 :            452 :     new_record[Anum_pg_database_datdba - 1] = ObjectIdGetDatum(datdba);
                               1521                 :            452 :     new_record[Anum_pg_database_encoding - 1] = Int32GetDatum(encoding);
 1717 peter@eisentraut.org     1522                 :            452 :     new_record[Anum_pg_database_datlocprovider - 1] = CharGetDatum(dblocprovider);
 4533 tgl@sss.pgh.pa.us        1523                 :            452 :     new_record[Anum_pg_database_datistemplate - 1] = BoolGetDatum(dbistemplate);
                               1524                 :            452 :     new_record[Anum_pg_database_datallowconn - 1] = BoolGetDatum(dballowconnections);
 1139 akorotkov@postgresql     1525                 :            452 :     new_record[Anum_pg_database_dathasloginevt - 1] = BoolGetDatum(src_hasloginevt);
 7513 tgl@sss.pgh.pa.us        1526                 :            452 :     new_record[Anum_pg_database_datconnlimit - 1] = Int32GetDatum(dbconnlimit);
 7328                          1527                 :            452 :     new_record[Anum_pg_database_datfrozenxid - 1] = TransactionIdGetDatum(src_frozenxid);
 5057 alvherre@alvh.no-ip.     1528                 :            452 :     new_record[Anum_pg_database_datminmxid - 1] = TransactionIdGetDatum(src_minmxid);
 7513 tgl@sss.pgh.pa.us        1529                 :            452 :     new_record[Anum_pg_database_dattablespace - 1] = ObjectIdGetDatum(dst_deftablespace);
 1760 peter@eisentraut.org     1530                 :            452 :     new_record[Anum_pg_database_datcollate - 1] = CStringGetTextDatum(dbcollate);
                               1531                 :            452 :     new_record[Anum_pg_database_datctype - 1] = CStringGetTextDatum(dbctype);
  994 jdavis@postgresql.or     1532         [ +  + ]:            452 :     if (dblocale)
                               1533                 :             42 :         new_record[Anum_pg_database_datlocale - 1] = CStringGetTextDatum(dblocale);
                               1534                 :                :     else
                               1535                 :            410 :         new_record_nulls[Anum_pg_database_datlocale - 1] = true;
 1361 peter@eisentraut.org     1536         [ +  + ]:            452 :     if (dbicurules)
                               1537                 :              3 :         new_record[Anum_pg_database_daticurules - 1] = CStringGetTextDatum(dbicurules);
                               1538                 :                :     else
                               1539                 :            449 :         new_record_nulls[Anum_pg_database_daticurules - 1] = true;
 1748                          1540         [ +  + ]:            452 :     if (dbcollversion)
                               1541                 :            388 :         new_record[Anum_pg_database_datcollversion - 1] = CStringGetTextDatum(dbcollversion);
                               1542                 :                :     else
                               1543                 :             64 :         new_record_nulls[Anum_pg_database_datcollversion - 1] = true;
                               1544                 :                : 
                               1545                 :                :     /*
                               1546                 :                :      * We deliberately set datacl to default (NULL), rather than copying it
                               1547                 :                :      * from the template database.  Copying it would be a bad idea when the
                               1548                 :                :      * owner is not the same as the template's owner.
                               1549                 :                :      */
 6600 tgl@sss.pgh.pa.us        1550                 :            452 :     new_record_nulls[Anum_pg_database_datacl - 1] = true;
                               1551                 :                : 
                               1552                 :            452 :     tuple = heap_form_tuple(RelationGetDescr(pg_database_rel),
                               1553                 :                :                             new_record, new_record_nulls);
                               1554                 :                : 
  123 dgustafsson@postgres     1555                 :            452 :     INJECTION_POINT("createdb-before-catalog-insert", NULL);
                               1556                 :                : 
 3588 alvherre@alvh.no-ip.     1557                 :            452 :     CatalogTupleInsert(pg_database_rel, tuple);
                               1558                 :                : 
                               1559                 :                :     /*
                               1560                 :                :      * Now generate additional catalog entries associated with the new DB
                               1561                 :                :      */
                               1562                 :                : 
                               1563                 :                :     /* Register owner dependency */
 7513 tgl@sss.pgh.pa.us        1564                 :            452 :     recordDependencyOnOwner(DatabaseRelationId, dboid, datdba);
                               1565                 :                : 
                               1566                 :                :     /* Create pg_shdepend entries for objects within database */
                               1567                 :            452 :     copyTemplateDependencies(src_dboid, dboid);
                               1568                 :                : 
                               1569                 :                :     /* Post creation hook for new database */
 5015 rhaas@postgresql.org     1570         [ -  + ]:            452 :     InvokeObjectPostCreateHook(DatabaseRelationId, dboid, 0);
                               1571                 :                : 
                               1572                 :                :     /*
                               1573                 :                :      * If we're going to be reading data for the to-be-created database into
                               1574                 :                :      * shared_buffers, take a lock on it. Nobody should know that this
                               1575                 :                :      * database exists yet, but it's good to maintain the invariant that an
                               1576                 :                :      * AccessExclusiveLock on the database is sufficient to drop all of its
                               1577                 :                :      * buffers without worrying about more being read later.
                               1578                 :                :      *
                               1579                 :                :      * Note that we need to do this before entering the
                               1580                 :                :      * PG_ENSURE_ERROR_CLEANUP block below, because createdb_failure_callback
                               1581                 :                :      * expects this lock to be held already.
                               1582                 :                :      */
 1705                          1583         [ +  + ]:            452 :     if (dbstrategy == CREATEDB_WAL_LOG)
                               1584                 :            291 :         LockSharedObject(DatabaseRelationId, dboid, 0, AccessShareLock);
                               1585                 :                : 
                               1586                 :                :     /*
                               1587                 :                :      * Once we start copying subdirectories, we need to be able to clean 'em
                               1588                 :                :      * up if we fail.  Use an ENSURE block to make sure this happens.  (This
                               1589                 :                :      * is not a 100% solution, because of the possibility of failure during
                               1590                 :                :      * transaction commit after we leave this routine, but it should handle
                               1591                 :                :      * most scenarios.)
                               1592                 :                :      */
 6800 tgl@sss.pgh.pa.us        1593                 :            452 :     fparms.src_dboid = src_dboid;
                               1594                 :            452 :     fparms.dest_dboid = dboid;
 1705 rhaas@postgresql.org     1595                 :            452 :     fparms.strategy = dbstrategy;
                               1596                 :                : 
 6800 tgl@sss.pgh.pa.us        1597         [ +  + ]:            452 :     PG_ENSURE_ERROR_CLEANUP(createdb_failure_callback,
                               1598                 :                :                             PointerGetDatum(&fparms));
                               1599                 :                :     {
                               1600                 :                :         /*
                               1601                 :                :          * If the user has asked to create a database with WAL_LOG strategy
                               1602                 :                :          * then call CreateDatabaseUsingWalLog, which will copy the database
                               1603                 :                :          * at the block level and it will WAL log each copied block.
                               1604                 :                :          * Otherwise, call CreateDatabaseUsingFileCopy that will copy the
                               1605                 :                :          * database file by file.
                               1606                 :                :          */
 1705 rhaas@postgresql.org     1607         [ +  + ]:            452 :         if (dbstrategy == CREATEDB_WAL_LOG)
                               1608                 :            291 :             CreateDatabaseUsingWalLog(src_dboid, dboid, src_deftablespace,
                               1609                 :                :                                       dst_deftablespace);
                               1610                 :                :         else
                               1611                 :            161 :             CreateDatabaseUsingFileCopy(src_dboid, dboid, src_deftablespace,
                               1612                 :                :                                         dst_deftablespace);
                               1613                 :                : 
                               1614                 :                :         /*
                               1615                 :                :          * Close pg_database, but keep lock till commit.
                               1616                 :                :          */
 2868 andres@anarazel.de       1617                 :            449 :         table_close(pg_database_rel, NoLock);
                               1618                 :                : 
                               1619                 :                :         /*
                               1620                 :                :          * Force synchronous commit, thus minimizing the window between
                               1621                 :                :          * creation of the database files and committal of the transaction. If
                               1622                 :                :          * we crash before committing, we'll have a DB that's taking up disk
                               1623                 :                :          * space but is not in pg_database, which is not good.
                               1624                 :                :          */
 6297 alvherre@alvh.no-ip.     1625                 :            449 :         ForceSyncCommit();
                               1626                 :                :     }
 6800 tgl@sss.pgh.pa.us        1627         [ -  + ]:            452 :     PG_END_ENSURE_ERROR_CLEANUP(createdb_failure_callback,
                               1628                 :                :                                 PointerGetDatum(&fparms));
                               1629                 :                : 
 5082 rhaas@postgresql.org     1630                 :            449 :     return dboid;
                               1631                 :                : }
                               1632                 :                : 
                               1633                 :                : /*
                               1634                 :                :  * Check whether chosen encoding matches chosen locale settings.  This
                               1635                 :                :  * restriction is necessary because libc's locale-specific code usually
                               1636                 :                :  * fails when presented with data in an encoding it's not expecting. We
                               1637                 :                :  * allow mismatch in four cases:
                               1638                 :                :  *
                               1639                 :                :  * 1. locale encoding = SQL_ASCII, which means that the locale is C/POSIX
                               1640                 :                :  * which works with any encoding.
                               1641                 :                :  *
                               1642                 :                :  * 2. locale encoding = -1, which means that we couldn't determine the
                               1643                 :                :  * locale's encoding and have to trust the user to get it right.
                               1644                 :                :  *
                               1645                 :                :  * 3. selected encoding is UTF8 and platform is win32. This is because
                               1646                 :                :  * UTF8 is a pseudo codepage that is supported in all locales since it's
                               1647                 :                :  * converted to UTF16 before being used.
                               1648                 :                :  *
                               1649                 :                :  * 4. selected encoding is SQL_ASCII, but only if you're a superuser. This
                               1650                 :                :  * is risky but we have historically allowed it --- notably, the
                               1651                 :                :  * regression tests require it.
                               1652                 :                :  *
                               1653                 :                :  * Note: if you change this policy, fix initdb to match.
                               1654                 :                :  */
                               1655                 :                : void
 5768 peter_e@gmx.net          1656                 :            479 : check_encoding_locale_matches(int encoding, const char *collate, const char *ctype)
                               1657                 :                : {
 5711 bruce@momjian.us         1658                 :            479 :     int         ctype_encoding = pg_get_encoding_from_locale(ctype, true);
                               1659                 :            479 :     int         collate_encoding = pg_get_encoding_from_locale(collate, true);
                               1660                 :                : 
 5768 peter_e@gmx.net          1661   [ +  +  +  +  :            483 :     if (!(ctype_encoding == encoding ||
                                              +  - ]
                               1662         [ +  - ]:              4 :           ctype_encoding == PG_SQL_ASCII ||
                               1663                 :                :           ctype_encoding == -1 ||
                               1664                 :                : #ifdef WIN32
                               1665                 :                :           encoding == PG_UTF8 ||
                               1666                 :                : #endif
                               1667         [ -  + ]:              4 :           (encoding == PG_SQL_ASCII && superuser())))
 5768 peter_e@gmx.net          1668         [ #  # ]:UBC           0 :         ereport(ERROR,
                               1669                 :                :                 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
                               1670                 :                :                  errmsg("encoding \"%s\" does not match locale \"%s\"",
                               1671                 :                :                         pg_encoding_to_char(encoding),
                               1672                 :                :                         ctype),
                               1673                 :                :                  errdetail("The chosen LC_CTYPE setting requires encoding \"%s\".",
                               1674                 :                :                            pg_encoding_to_char(ctype_encoding))));
                               1675                 :                : 
 5768 peter_e@gmx.net          1676   [ +  +  +  +  :CBC         483 :     if (!(collate_encoding == encoding ||
                                              +  - ]
                               1677         [ +  - ]:              4 :           collate_encoding == PG_SQL_ASCII ||
                               1678                 :                :           collate_encoding == -1 ||
                               1679                 :                : #ifdef WIN32
                               1680                 :                :           encoding == PG_UTF8 ||
                               1681                 :                : #endif
                               1682         [ -  + ]:              4 :           (encoding == PG_SQL_ASCII && superuser())))
 5768 peter_e@gmx.net          1683         [ #  # ]:UBC           0 :         ereport(ERROR,
                               1684                 :                :                 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
                               1685                 :                :                  errmsg("encoding \"%s\" does not match locale \"%s\"",
                               1686                 :                :                         pg_encoding_to_char(encoding),
                               1687                 :                :                         collate),
                               1688                 :                :                  errdetail("The chosen LC_COLLATE setting requires encoding \"%s\".",
                               1689                 :                :                            pg_encoding_to_char(collate_encoding))));
 5768 peter_e@gmx.net          1690                 :CBC         479 : }
                               1691                 :                : 
                               1692                 :                : /* Error cleanup callback for createdb */
                               1693                 :                : static void
 6800 tgl@sss.pgh.pa.us        1694                 :              3 : createdb_failure_callback(int code, Datum arg)
                               1695                 :                : {
                               1696                 :              3 :     createdb_failure_params *fparms = (createdb_failure_params *) DatumGetPointer(arg);
                               1697                 :                : 
                               1698                 :                :     /*
                               1699                 :                :      * If we were copying database at block levels then drop pages for the
                               1700                 :                :      * destination database that are in the shared buffer cache.  And tell
                               1701                 :                :      * checkpointer to forget any pending fsync and unlink requests for files
                               1702                 :                :      * in the database.  The reasoning behind doing this is same as explained
                               1703                 :                :      * in dropdb function.  But unlike dropdb we don't need to call
                               1704                 :                :      * pgstat_drop_database because this database is still not created so
                               1705                 :                :      * there should not be any stat for this.
                               1706                 :                :      */
 1705 rhaas@postgresql.org     1707         [ +  + ]:              3 :     if (fparms->strategy == CREATEDB_WAL_LOG)
                               1708                 :                :     {
                               1709                 :              2 :         DropDatabaseBuffers(fparms->dest_dboid);
                               1710                 :              2 :         ForgetDatabaseSyncRequests(fparms->dest_dboid);
                               1711                 :                : 
                               1712                 :                :         /* Release lock on the target database. */
                               1713                 :              2 :         UnlockSharedObject(DatabaseRelationId, fparms->dest_dboid, 0,
                               1714                 :                :                            AccessShareLock);
                               1715                 :                :     }
                               1716                 :                : 
                               1717                 :                :     /*
                               1718                 :                :      * Release lock on source database before doing recursive remove. This is
                               1719                 :                :      * not essential but it seems desirable to release the lock as soon as
                               1720                 :                :      * possible.
                               1721                 :                :      */
 6800 tgl@sss.pgh.pa.us        1722                 :              3 :     UnlockSharedObject(DatabaseRelationId, fparms->src_dboid, 0, ShareLock);
                               1723                 :                : 
                               1724                 :                :     /* Throw away any successfully copied subdirectories */
                               1725                 :              3 :     remove_dbtablespaces(fparms->dest_dboid);
 9510                          1726                 :              3 : }
                               1727                 :                : 
                               1728                 :                : 
                               1729                 :                : /*
                               1730                 :                :  * DROP DATABASE
                               1731                 :                :  */
                               1732                 :                : void
 2573 akapila@postgresql.o     1733                 :             89 : dropdb(const char *dbname, bool missing_ok, bool force)
                               1734                 :                : {
                               1735                 :                :     Oid         db_id;
                               1736                 :                :     bool        db_istemplate;
                               1737                 :                :     Relation    pgdbrel;
                               1738                 :                :     HeapTuple   tup;
                               1739                 :                :     ScanKeyData scankey;
                               1740                 :                :     void       *inplace_state;
                               1741                 :                :     Form_pg_database datform;
                               1742                 :                :     int         notherbackends;
                               1743                 :                :     int         npreparedxacts;
                               1744                 :                :     int         nslots,
                               1745                 :                :                 nslots_active;
                               1746                 :                :     int         nsubscriptions;
                               1747                 :                : 
                               1748                 :                :     /*
                               1749                 :                :      * Look up the target database's OID, and get exclusive lock on it. We
                               1750                 :                :      * need this to ensure that no new backend starts up in the target
                               1751                 :                :      * database while we are deleting it (see postinit.c), and that no one is
                               1752                 :                :      * using it as a CREATE DATABASE template or trying to delete it for
                               1753                 :                :      * themselves.
                               1754                 :                :      */
 2868 andres@anarazel.de       1755                 :             89 :     pgdbrel = table_open(DatabaseRelationId, RowExclusiveLock);
                               1756                 :                : 
 7513 tgl@sss.pgh.pa.us        1757         [ +  + ]:             89 :     if (!get_db_info(dbname, AccessExclusiveLock, &db_id, NULL, NULL,
                               1758                 :                :                      &db_istemplate, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL))
                               1759                 :                :     {
 7676 bruce@momjian.us         1760         [ +  + ]:             21 :         if (!missing_ok)
                               1761                 :                :         {
      andrew@dunslane.net      1762         [ +  - ]:             10 :             ereport(ERROR,
                               1763                 :                :                     (errcode(ERRCODE_UNDEFINED_DATABASE),
                               1764                 :                :                      errmsg("database \"%s\" does not exist", dbname)));
                               1765                 :                :         }
                               1766                 :                :         else
                               1767                 :                :         {
                               1768                 :                :             /* Close pg_database, release the lock, since we changed nothing */
 2868 andres@anarazel.de       1769                 :             11 :             table_close(pgdbrel, RowExclusiveLock);
 7676 bruce@momjian.us         1770         [ +  + ]:             11 :             ereport(NOTICE,
                               1771                 :                :                     (errmsg("database \"%s\" does not exist, skipping",
                               1772                 :                :                             dbname)));
      andrew@dunslane.net      1773                 :             11 :             return;
                               1774                 :                :         }
                               1775                 :                :     }
                               1776                 :                : 
                               1777                 :                :     /*
                               1778                 :                :      * Permission checks
                               1779                 :                :      */
 1476 peter@eisentraut.org     1780         [ -  + ]:             68 :     if (!object_ownercheck(DatabaseRelationId, db_id, GetUserId()))
 3283 peter_e@gmx.net          1781                 :UBC           0 :         aclcheck_error(ACLCHECK_NOT_OWNER, OBJECT_DATABASE,
                               1782                 :                :                        dbname);
                               1783                 :                : 
                               1784                 :                :     /* DROP hook for the database being removed */
 5015 rhaas@postgresql.org     1785         [ -  + ]:CBC          68 :     InvokeObjectDropHook(DatabaseRelationId, db_id, 0);
                               1786                 :                : 
                               1787                 :                :     /*
                               1788                 :                :      * Disallow dropping a DB that is marked istemplate.  This is just to
                               1789                 :                :      * prevent people from accidentally dropping template0 or template1; they
                               1790                 :                :      * can do so if they're really determined ...
                               1791                 :                :      */
 9510 tgl@sss.pgh.pa.us        1792         [ -  + ]:             68 :     if (db_istemplate)
 8534 tgl@sss.pgh.pa.us        1793         [ #  # ]:UBC           0 :         ereport(ERROR,
                               1794                 :                :                 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
                               1795                 :                :                  errmsg("cannot drop a template database")));
                               1796                 :                : 
                               1797                 :                :     /* Obviously can't drop my own database */
 7120 tgl@sss.pgh.pa.us        1798         [ -  + ]:CBC          68 :     if (db_id == MyDatabaseId)
 7120 tgl@sss.pgh.pa.us        1799         [ #  # ]:UBC           0 :         ereport(ERROR,
                               1800                 :                :                 (errcode(ERRCODE_OBJECT_IN_USE),
                               1801                 :                :                  errmsg("cannot drop the currently open database")));
                               1802                 :                : 
                               1803                 :                :     /*
                               1804                 :                :      * Check whether there are active logical slots that refer to the
                               1805                 :                :      * to-be-dropped database. The database lock we are holding prevents the
                               1806                 :                :      * creation of new slots using the database or existing slots becoming
                               1807                 :                :      * active.
                               1808                 :                :      */
 3532 simon@2ndQuadrant.co     1809                 :CBC          68 :     (void) ReplicationSlotsCountDBSlots(db_id, &nslots, &nslots_active);
                               1810         [ +  + ]:             68 :     if (nslots_active)
                               1811                 :                :     {
 4653 rhaas@postgresql.org     1812         [ +  - ]:              1 :         ereport(ERROR,
                               1813                 :                :                 (errcode(ERRCODE_OBJECT_IN_USE),
                               1814                 :                :                  errmsg("database \"%s\" is used by an active logical replication slot",
                               1815                 :                :                         dbname),
                               1816                 :                :                  errdetail_plural("There is %d active slot.",
                               1817                 :                :                                   "There are %d active slots.",
                               1818                 :                :                                   nslots_active, nslots_active)));
                               1819                 :                :     }
                               1820                 :                : 
                               1821                 :                :     /*
                               1822                 :                :      * Check if there are subscriptions defined in the target database.
                               1823                 :                :      *
                               1824                 :                :      * We can't drop them automatically because they might be holding
                               1825                 :                :      * resources in other databases/instances.
                               1826                 :                :      */
 3600 peter_e@gmx.net          1827         [ -  + ]:             67 :     if ((nsubscriptions = CountDBSubscriptions(db_id)) > 0)
 3600 peter_e@gmx.net          1828         [ #  # ]:UBC           0 :         ereport(ERROR,
                               1829                 :                :                 (errcode(ERRCODE_OBJECT_IN_USE),
                               1830                 :                :                  errmsg("database \"%s\" is being used by logical replication subscription",
                               1831                 :                :                         dbname),
                               1832                 :                :                  errdetail_plural("There is %d subscription.",
                               1833                 :                :                                   "There are %d subscriptions.",
                               1834                 :                :                                   nsubscriptions, nsubscriptions)));
                               1835                 :                : 
                               1836                 :                : 
                               1837                 :                :     /*
                               1838                 :                :      * Attempt to terminate all existing connections to the target database if
                               1839                 :                :      * the user has requested to do so.
                               1840                 :                :      */
 2573 akapila@postgresql.o     1841         [ +  + ]:CBC          67 :     if (force)
                               1842                 :              3 :         TerminateOtherDBBackends(db_id);
                               1843                 :                : 
                               1844                 :                :     /*
                               1845                 :                :      * Check for other backends in the target database.  (Because we hold the
                               1846                 :                :      * database lock, no new ones can start after this.)
                               1847                 :                :      *
                               1848                 :                :      * As in CREATE DATABASE, check this after other error conditions.
                               1849                 :                :      */
 2576                          1850         [ -  + ]:             67 :     if (CountOtherDBBackends(db_id, &notherbackends, &npreparedxacts))
 2576 akapila@postgresql.o     1851         [ #  # ]:UBC           0 :         ereport(ERROR,
                               1852                 :                :                 (errcode(ERRCODE_OBJECT_IN_USE),
                               1853                 :                :                  errmsg("database \"%s\" is being accessed by other users",
                               1854                 :                :                         dbname),
                               1855                 :                :                  errdetail_busy_db(notherbackends, npreparedxacts)));
                               1856                 :                : 
                               1857                 :                :     /*
                               1858                 :                :      * Delete any comments or security labels associated with the database.
                               1859                 :                :      */
 7594 bruce@momjian.us         1860                 :CBC          67 :     DeleteSharedComments(db_id, DatabaseRelationId);
 5610 rhaas@postgresql.org     1861                 :             67 :     DeleteSharedSecurityLabel(db_id, DatabaseRelationId);
                               1862                 :                : 
                               1863                 :                :     /*
                               1864                 :                :      * Remove settings associated with this database
                               1865                 :                :      */
 6261 alvherre@alvh.no-ip.     1866                 :             67 :     DropSetting(db_id, InvalidOid);
                               1867                 :                : 
                               1868                 :                :     /*
                               1869                 :                :      * Remove shared dependency references for the database.
                               1870                 :                :      */
 7719 tgl@sss.pgh.pa.us        1871                 :             67 :     dropDatabaseDependencies(db_id);
                               1872                 :                : 
                               1873                 :                :     /*
                               1874                 :                :      * Tell the cumulative stats system to forget it immediately, too.
                               1875                 :                :      */
 1234 andres@anarazel.de       1876                 :             67 :     pgstat_drop_database(db_id);
                               1877                 :                : 
                               1878                 :                :     /*
                               1879                 :                :      * Except for the deletion of the catalog row, subsequent actions are not
                               1880                 :                :      * transactional (consider DropDatabaseBuffers() discarding modified
                               1881                 :                :      * buffers). But we might crash or get interrupted below. To prevent
                               1882                 :                :      * accesses to a database with invalid contents, mark the database as
                               1883                 :                :      * invalid using an in-place update.
                               1884                 :                :      *
                               1885                 :                :      * We need to flush the WAL before continuing, to guarantee the
                               1886                 :                :      * modification is durable before performing irreversible filesystem
                               1887                 :                :      * operations.
                               1888                 :                :      */
  795 noah@leadboat.com        1889                 :             67 :     ScanKeyInit(&scankey,
                               1890                 :                :                 Anum_pg_database_datname,
                               1891                 :                :                 BTEqualStrategyNumber, F_NAMEEQ,
                               1892                 :                :                 CStringGetDatum(dbname));
                               1893                 :             67 :     systable_inplace_update_begin(pgdbrel, DatabaseNameIndexId, true,
                               1894                 :                :                                   NULL, 1, &scankey, &tup, &inplace_state);
                               1895         [ -  + ]:             67 :     if (!HeapTupleIsValid(tup))
  795 noah@leadboat.com        1896         [ #  # ]:UBC           0 :         elog(ERROR, "cache lookup failed for database %u", db_id);
  795 noah@leadboat.com        1897                 :CBC          67 :     datform = (Form_pg_database) GETSTRUCT(tup);
 1234 andres@anarazel.de       1898                 :             67 :     datform->datconnlimit = DATCONNLIMIT_INVALID_DB;
  795 noah@leadboat.com        1899                 :             67 :     systable_inplace_update_finish(inplace_state, tup);
 1234 andres@anarazel.de       1900                 :             67 :     XLogFlush(XactLastRecEnd);
                               1901                 :                : 
  117 dgustafsson@postgres     1902                 :GNC          67 :     INJECTION_POINT("dropdb-after-invalid-marker", NULL);
                               1903                 :                : 
                               1904                 :                :     /*
                               1905                 :                :      * Also delete the tuple - transactionally. If this transaction commits,
                               1906                 :                :      * the row will be gone, but if we fail, dropdb() can be invoked again.
                               1907                 :                :      */
 1234 andres@anarazel.de       1908                 :CBC          66 :     CatalogTupleDelete(pgdbrel, &tup->t_self);
  795 noah@leadboat.com        1909                 :             66 :     heap_freetuple(tup);
                               1910                 :                : 
                               1911                 :                :     /*
                               1912                 :                :      * Drop db-specific replication slots.
                               1913                 :                :      */
 3532 simon@2ndQuadrant.co     1914                 :             66 :     ReplicationSlotsDropDBSlots(db_id);
                               1915                 :                : 
                               1916                 :                :     /*
                               1917                 :                :      * Drop pages for this database that are in the shared buffer cache. This
                               1918                 :                :      * is important to ensure that no remaining backend tries to write out a
                               1919                 :                :      * dirty buffer to the dead database later...
                               1920                 :                :      */
 7549 tgl@sss.pgh.pa.us        1921                 :             66 :     DropDatabaseBuffers(db_id);
                               1922                 :                : 
                               1923                 :                :     /*
                               1924                 :                :      * Tell checkpointer to forget any pending fsync and unlink requests for
                               1925                 :                :      * files in the database; else the fsyncs will fail at next checkpoint, or
                               1926                 :                :      * worse, it will delete files that belong to a newly created database
                               1927                 :                :      * with the same OID.
                               1928                 :                :      */
 2795 tmunro@postgresql.or     1929                 :             66 :     ForgetDatabaseSyncRequests(db_id);
                               1930                 :                : 
                               1931                 :                :     /*
                               1932                 :                :      * Force a checkpoint to make sure the checkpointer has received the
                               1933                 :                :      * message sent by ForgetDatabaseSyncRequests.
                               1934                 :                :      */
  505 nathan@postgresql.or     1935                 :             66 :     RequestCheckpoint(CHECKPOINT_FAST | CHECKPOINT_FORCE | CHECKPOINT_WAIT);
                               1936                 :                : 
                               1937                 :                :     /* Close all smgr fds in all backends. */
 1750 tmunro@postgresql.or     1938                 :             66 :     WaitForProcSignalBarrier(EmitProcSignalBarrier(PROCSIGNAL_BARRIER_SMGRRELEASE));
                               1939                 :                : 
                               1940                 :                :     /*
                               1941                 :                :      * Remove all tablespace subdirs belonging to the database.
                               1942                 :                :      */
 8198 tgl@sss.pgh.pa.us        1943                 :             66 :     remove_dbtablespaces(db_id);
                               1944                 :                : 
                               1945                 :                :     /*
                               1946                 :                :      * Close pg_database, but keep lock till commit.
                               1947                 :                :      */
 2868 andres@anarazel.de       1948                 :             66 :     table_close(pgdbrel, NoLock);
                               1949                 :                : 
                               1950                 :                :     /*
                               1951                 :                :      * Force synchronous commit, thus minimizing the window between removal of
                               1952                 :                :      * the database files and committal of the transaction. If we crash before
                               1953                 :                :      * committing, we'll have a DB that's gone on disk but still there
                               1954                 :                :      * according to pg_database, which is not good.
                               1955                 :                :      */
 6297 alvherre@alvh.no-ip.     1956                 :             66 :     ForceSyncCommit();
                               1957                 :                : }
                               1958                 :                : 
                               1959                 :                : 
                               1960                 :                : /*
                               1961                 :                :  * Rename database
                               1962                 :                :  */
                               1963                 :                : ObjectAddress
 8555 peter_e@gmx.net          1964                 :              9 : RenameDatabase(const char *oldname, const char *newname)
                               1965                 :                : {
                               1966                 :                :     Oid         db_id;
                               1967                 :                :     HeapTuple   newtup;
                               1968                 :                :     ItemPointerData otid;
                               1969                 :                :     Relation    rel;
                               1970                 :                :     int         notherbackends;
                               1971                 :                :     int         npreparedxacts;
                               1972                 :                :     ObjectAddress address;
                               1973                 :                : 
                               1974                 :                :     /* Report error if name has \n or \r character. */
  280 andrew@dunslane.net      1975         [ -  + ]:              9 :     if (strpbrk(newname, "\n\r"))
  280 andrew@dunslane.net      1976         [ #  # ]:UBC           0 :         ereport(ERROR,
                               1977                 :                :                 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
                               1978                 :                :                  errmsg("database name \"%s\" contains a newline or carriage return character", newname)));
                               1979                 :                : 
                               1980                 :                :     /*
                               1981                 :                :      * Look up the target database's OID, and get exclusive lock on it. We
                               1982                 :                :      * need this for the same reasons as DROP DATABASE.
                               1983                 :                :      */
 2868 andres@anarazel.de       1984                 :CBC           9 :     rel = table_open(DatabaseRelationId, RowExclusiveLock);
                               1985                 :                : 
 1139 akorotkov@postgresql     1986         [ -  + ]:              9 :     if (!get_db_info(oldname, AccessExclusiveLock, &db_id, NULL, NULL, NULL,
                               1987                 :                :                      NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL))
 8555 peter_e@gmx.net          1988         [ #  # ]:UBC           0 :         ereport(ERROR,
                               1989                 :                :                 (errcode(ERRCODE_UNDEFINED_DATABASE),
                               1990                 :                :                  errmsg("database \"%s\" does not exist", oldname)));
                               1991                 :                : 
                               1992                 :                :     /* must be owner */
 1476 peter@eisentraut.org     1993         [ -  + ]:CBC           9 :     if (!object_ownercheck(DatabaseRelationId, db_id, GetUserId()))
 3283 peter_e@gmx.net          1994                 :UBC           0 :         aclcheck_error(ACLCHECK_NOT_OWNER, OBJECT_DATABASE,
                               1995                 :                :                        oldname);
                               1996                 :                : 
                               1997                 :                :     /* must have createdb rights */
 4358 alvherre@alvh.no-ip.     1998         [ -  + ]:CBC           9 :     if (!have_createdb_privilege())
 7120 tgl@sss.pgh.pa.us        1999         [ #  # ]:UBC           0 :         ereport(ERROR,
                               2000                 :                :                 (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
                               2001                 :                :                  errmsg("permission denied to rename database")));
                               2002                 :                : 
                               2003                 :                :     /*
                               2004                 :                :      * If built with appropriate switch, whine when regression-testing
                               2005                 :                :      * conventions for database names are violated.
                               2006                 :                :      */
                               2007                 :                : #ifdef ENFORCE_REGRESSION_TEST_NAME_RESTRICTIONS
                               2008                 :                :     if (strstr(newname, "regression") == NULL)
                               2009                 :                :         elog(WARNING, "databases created by regression test cases should have names including \"regression\"");
                               2010                 :                : #endif
                               2011                 :                : 
                               2012                 :                :     /*
                               2013                 :                :      * Make sure the new name doesn't exist.  See notes for same error in
                               2014                 :                :      * CREATE DATABASE.
                               2015                 :                :      */
 5959 rhaas@postgresql.org     2016         [ -  + ]:CBC           9 :     if (OidIsValid(get_database_oid(newname, true)))
 7120 tgl@sss.pgh.pa.us        2017         [ #  # ]:UBC           0 :         ereport(ERROR,
                               2018                 :                :                 (errcode(ERRCODE_DUPLICATE_DATABASE),
                               2019                 :                :                  errmsg("database \"%s\" already exists", newname)));
                               2020                 :                : 
                               2021                 :                :     /*
                               2022                 :                :      * XXX Client applications probably store the current database somewhere,
                               2023                 :                :      * so renaming it could cause confusion.  On the other hand, there may not
                               2024                 :                :      * be an actual problem besides a little confusion, so think about this
                               2025                 :                :      * and decide.
                               2026                 :                :      */
 7513 tgl@sss.pgh.pa.us        2027         [ -  + ]:CBC           9 :     if (db_id == MyDatabaseId)
 8555 peter_e@gmx.net          2028         [ #  # ]:UBC           0 :         ereport(ERROR,
                               2029                 :                :                 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
                               2030                 :                :                  errmsg("current database cannot be renamed")));
                               2031                 :                : 
                               2032                 :                :     /*
                               2033                 :                :      * Make sure the database does not have active sessions.  This is the same
                               2034                 :                :      * concern as above, but applied to other sessions.
                               2035                 :                :      *
                               2036                 :                :      * As in CREATE DATABASE, check this after other error conditions.
                               2037                 :                :      */
 6690 tgl@sss.pgh.pa.us        2038         [ -  + ]:CBC           9 :     if (CountOtherDBBackends(db_id, &notherbackends, &npreparedxacts))
 8534 tgl@sss.pgh.pa.us        2039         [ #  # ]:UBC           0 :         ereport(ERROR,
                               2040                 :                :                 (errcode(ERRCODE_OBJECT_IN_USE),
                               2041                 :                :                  errmsg("database \"%s\" is being accessed by other users",
                               2042                 :                :                         oldname),
                               2043                 :                :                  errdetail_busy_db(notherbackends, npreparedxacts)));
                               2044                 :                : 
                               2045                 :                :     /* rename */
  795 noah@leadboat.com        2046                 :CBC           9 :     newtup = SearchSysCacheLockedCopy1(DATABASEOID, ObjectIdGetDatum(db_id));
 7513 tgl@sss.pgh.pa.us        2047         [ -  + ]:              9 :     if (!HeapTupleIsValid(newtup))
 7513 tgl@sss.pgh.pa.us        2048         [ #  # ]:UBC           0 :         elog(ERROR, "cache lookup failed for database %u", db_id);
  795 noah@leadboat.com        2049                 :CBC           9 :     otid = newtup->t_self;
 8555 peter_e@gmx.net          2050                 :              9 :     namestrcpy(&(((Form_pg_database) GETSTRUCT(newtup))->datname), newname);
  795 noah@leadboat.com        2051                 :              9 :     CatalogTupleUpdate(rel, &otid, newtup);
                               2052                 :              9 :     UnlockTuple(rel, &otid, InplaceUpdateTupleLock);
                               2053                 :                : 
 5004 rhaas@postgresql.org     2054         [ -  + ]:              9 :     InvokeObjectPostAlterHook(DatabaseRelationId, db_id, 0);
                               2055                 :                : 
 4288 alvherre@alvh.no-ip.     2056                 :              9 :     ObjectAddressSet(address, DatabaseRelationId, db_id);
                               2057                 :                : 
                               2058                 :                :     /*
                               2059                 :                :      * Close pg_database, but keep lock till commit.
                               2060                 :                :      */
 2868 andres@anarazel.de       2061                 :              9 :     table_close(rel, NoLock);
                               2062                 :                : 
 4288 alvherre@alvh.no-ip.     2063                 :              9 :     return address;
                               2064                 :                : }
                               2065                 :                : 
                               2066                 :                : 
                               2067                 :                : /*
                               2068                 :                :  * ALTER DATABASE SET TABLESPACE
                               2069                 :                :  */
                               2070                 :                : static void
 6595 tgl@sss.pgh.pa.us        2071                 :             14 : movedb(const char *dbname, const char *tblspcname)
                               2072                 :                : {
                               2073                 :                :     Oid         db_id;
                               2074                 :                :     Relation    pgdbrel;
                               2075                 :                :     int         notherbackends;
                               2076                 :                :     int         npreparedxacts;
                               2077                 :                :     HeapTuple   oldtuple,
                               2078                 :                :                 newtuple;
                               2079                 :                :     Oid         src_tblspcoid,
                               2080                 :                :                 dst_tblspcoid;
                               2081                 :                :     ScanKeyData scankey;
                               2082                 :                :     SysScanDesc sysscan;
                               2083                 :                :     AclResult   aclresult;
                               2084                 :                :     char       *src_dbpath;
                               2085                 :                :     char       *dst_dbpath;
                               2086                 :                :     DIR        *dstdir;
                               2087                 :                :     struct dirent *xlde;
                               2088                 :                :     movedb_failure_params fparms;
                               2089                 :                : 
                               2090                 :                :     /*
                               2091                 :                :      * Look up the target database's OID, and get exclusive lock on it. We
                               2092                 :                :      * need this to ensure that no new backend starts up in the database while
                               2093                 :                :      * we are moving it, and that no one is using it as a CREATE DATABASE
                               2094                 :                :      * template or trying to delete it.
                               2095                 :                :      */
 2868 andres@anarazel.de       2096                 :             14 :     pgdbrel = table_open(DatabaseRelationId, RowExclusiveLock);
                               2097                 :                : 
 1139 akorotkov@postgresql     2098         [ -  + ]:             14 :     if (!get_db_info(dbname, AccessExclusiveLock, &db_id, NULL, NULL, NULL,
                               2099                 :                :                      NULL, NULL, NULL, NULL, &src_tblspcoid, NULL, NULL, NULL, NULL, NULL, NULL))
 6595 tgl@sss.pgh.pa.us        2100         [ #  # ]:UBC           0 :         ereport(ERROR,
                               2101                 :                :                 (errcode(ERRCODE_UNDEFINED_DATABASE),
                               2102                 :                :                  errmsg("database \"%s\" does not exist", dbname)));
                               2103                 :                : 
                               2104                 :                :     /*
                               2105                 :                :      * We actually need a session lock, so that the lock will persist across
                               2106                 :                :      * the commit/restart below.  (We could almost get away with letting the
                               2107                 :                :      * lock be released at commit, except that someone could try to move
                               2108                 :                :      * relations of the DB back into the old directory while we rmtree() it.)
                               2109                 :                :      */
 6595 tgl@sss.pgh.pa.us        2110                 :CBC          14 :     LockSharedObjectForSession(DatabaseRelationId, db_id, 0,
                               2111                 :                :                                AccessExclusiveLock);
                               2112                 :                : 
                               2113                 :                :     /*
                               2114                 :                :      * Permission checks
                               2115                 :                :      */
 1476 peter@eisentraut.org     2116         [ -  + ]:             14 :     if (!object_ownercheck(DatabaseRelationId, db_id, GetUserId()))
 3283 peter_e@gmx.net          2117                 :UBC           0 :         aclcheck_error(ACLCHECK_NOT_OWNER, OBJECT_DATABASE,
                               2118                 :                :                        dbname);
                               2119                 :                : 
                               2120                 :                :     /*
                               2121                 :                :      * Obviously can't move the tables of my own database
                               2122                 :                :      */
 6595 tgl@sss.pgh.pa.us        2123         [ -  + ]:CBC          14 :     if (db_id == MyDatabaseId)
 6595 tgl@sss.pgh.pa.us        2124         [ #  # ]:UBC           0 :         ereport(ERROR,
                               2125                 :                :                 (errcode(ERRCODE_OBJECT_IN_USE),
                               2126                 :                :                  errmsg("cannot change the tablespace of the currently open database")));
                               2127                 :                : 
                               2128                 :                :     /*
                               2129                 :                :      * Get tablespace's oid
                               2130                 :                :      */
 5959 rhaas@postgresql.org     2131                 :CBC          14 :     dst_tblspcoid = get_tablespace_oid(tblspcname, false);
                               2132                 :                : 
                               2133                 :                :     /*
                               2134                 :                :      * Permission checks
                               2135                 :                :      */
 1476 peter@eisentraut.org     2136                 :             14 :     aclresult = object_aclcheck(TableSpaceRelationId, dst_tblspcoid, GetUserId(),
                               2137                 :                :                                 ACL_CREATE);
 6595 tgl@sss.pgh.pa.us        2138         [ -  + ]:             14 :     if (aclresult != ACLCHECK_OK)
 3283 peter_e@gmx.net          2139                 :UBC           0 :         aclcheck_error(aclresult, OBJECT_TABLESPACE,
                               2140                 :                :                        tblspcname);
                               2141                 :                : 
                               2142                 :                :     /*
                               2143                 :                :      * pg_global must never be the default tablespace
                               2144                 :                :      */
 6595 tgl@sss.pgh.pa.us        2145         [ -  + ]:CBC          14 :     if (dst_tblspcoid == GLOBALTABLESPACE_OID)
 6595 tgl@sss.pgh.pa.us        2146         [ #  # ]:UBC           0 :         ereport(ERROR,
                               2147                 :                :                 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
                               2148                 :                :                  errmsg("pg_global cannot be used as default tablespace")));
                               2149                 :                : 
                               2150                 :                :     /*
                               2151                 :                :      * No-op if same tablespace
                               2152                 :                :      */
 6595 tgl@sss.pgh.pa.us        2153         [ -  + ]:CBC          14 :     if (src_tblspcoid == dst_tblspcoid)
                               2154                 :                :     {
 2868 andres@anarazel.de       2155                 :UBC           0 :         table_close(pgdbrel, NoLock);
 6595 tgl@sss.pgh.pa.us        2156                 :              0 :         UnlockSharedObjectForSession(DatabaseRelationId, db_id, 0,
                               2157                 :                :                                      AccessExclusiveLock);
                               2158                 :              0 :         return;
                               2159                 :                :     }
                               2160                 :                : 
                               2161                 :                :     /*
                               2162                 :                :      * Check for other backends in the target database.  (Because we hold the
                               2163                 :                :      * database lock, no new ones can start after this.)
                               2164                 :                :      *
                               2165                 :                :      * As in CREATE DATABASE, check this after other error conditions.
                               2166                 :                :      */
 6595 tgl@sss.pgh.pa.us        2167         [ -  + ]:CBC          14 :     if (CountOtherDBBackends(db_id, &notherbackends, &npreparedxacts))
 6595 tgl@sss.pgh.pa.us        2168         [ #  # ]:UBC           0 :         ereport(ERROR,
                               2169                 :                :                 (errcode(ERRCODE_OBJECT_IN_USE),
                               2170                 :                :                  errmsg("database \"%s\" is being accessed by other users",
                               2171                 :                :                         dbname),
                               2172                 :                :                  errdetail_busy_db(notherbackends, npreparedxacts)));
                               2173                 :                : 
                               2174                 :                :     /*
                               2175                 :                :      * Get old and new database paths
                               2176                 :                :      */
 6595 tgl@sss.pgh.pa.us        2177                 :CBC          14 :     src_dbpath = GetDatabasePath(db_id, src_tblspcoid);
                               2178                 :             14 :     dst_dbpath = GetDatabasePath(db_id, dst_tblspcoid);
                               2179                 :                : 
                               2180                 :                :     /*
                               2181                 :                :      * Force a checkpoint before proceeding. This will force all dirty
                               2182                 :                :      * buffers, including those of unlogged tables, out to disk, to ensure
                               2183                 :                :      * source database is up-to-date on disk for the copy.
                               2184                 :                :      * FlushDatabaseBuffers() would suffice for that, but we also want to
                               2185                 :                :      * process any pending unlink requests. Otherwise, the check for existing
                               2186                 :                :      * files in the target directory might fail unnecessarily, not to mention
                               2187                 :                :      * that the copy might fail due to source files getting deleted under it.
                               2188                 :                :      * On Windows, this also ensures that background procs don't hold any open
                               2189                 :                :      * files, which would cause rmdir() to fail.
                               2190                 :                :      */
  505 nathan@postgresql.or     2191                 :             14 :     RequestCheckpoint(CHECKPOINT_FAST | CHECKPOINT_FORCE | CHECKPOINT_WAIT
                               2192                 :                :                       | CHECKPOINT_FLUSH_UNLOGGED);
                               2193                 :                : 
                               2194                 :                :     /* Close all smgr fds in all backends. */
 1750 tmunro@postgresql.or     2195                 :             14 :     WaitForProcSignalBarrier(EmitProcSignalBarrier(PROCSIGNAL_BARRIER_SMGRRELEASE));
                               2196                 :                : 
                               2197                 :                :     /*
                               2198                 :                :      * Now drop all buffers holding data of the target database; they should
                               2199                 :                :      * no longer be dirty so DropDatabaseBuffers is safe.
                               2200                 :                :      *
                               2201                 :                :      * It might seem that we could just let these buffers age out of shared
                               2202                 :                :      * buffers naturally, since they should not get referenced anymore.  The
                               2203                 :                :      * problem with that is that if the user later moves the database back to
                               2204                 :                :      * its original tablespace, any still-surviving buffers would appear to
                               2205                 :                :      * contain valid data again --- but they'd be missing any changes made in
                               2206                 :                :      * the database while it was in the new tablespace.  In any case, freeing
                               2207                 :                :      * buffers that should never be used again seems worth the cycles.
                               2208                 :                :      *
                               2209                 :                :      * Note: it'd be sufficient to get rid of buffers matching db_id and
                               2210                 :                :      * src_tblspcoid, but bufmgr.c presently provides no API for that.
                               2211                 :                :      */
 4407 tgl@sss.pgh.pa.us        2212                 :             14 :     DropDatabaseBuffers(db_id);
                               2213                 :                : 
                               2214                 :                :     /*
                               2215                 :                :      * Check for existence of files in the target directory, i.e., objects of
                               2216                 :                :      * this database that are already in the target tablespace.  We can't
                               2217                 :                :      * allow the move in such a case, because we would need to change those
                               2218                 :                :      * relations' pg_class.reltablespace entries to zero, and we don't have
                               2219                 :                :      * access to the DB's pg_class to do so.
                               2220                 :                :      */
 6595                          2221                 :             14 :     dstdir = AllocateDir(dst_dbpath);
                               2222         [ -  + ]:             14 :     if (dstdir != NULL)
                               2223                 :                :     {
 6595 tgl@sss.pgh.pa.us        2224         [ #  # ]:UBC           0 :         while ((xlde = ReadDir(dstdir, dst_dbpath)) != NULL)
                               2225                 :                :         {
                               2226         [ #  # ]:              0 :             if (strcmp(xlde->d_name, ".") == 0 ||
                               2227         [ #  # ]:              0 :                 strcmp(xlde->d_name, "..") == 0)
                               2228                 :              0 :                 continue;
                               2229                 :                : 
                               2230         [ #  # ]:              0 :             ereport(ERROR,
                               2231                 :                :                     (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
                               2232                 :                :                      errmsg("some relations of database \"%s\" are already in tablespace \"%s\"",
                               2233                 :                :                             dbname, tblspcname),
                               2234                 :                :                      errhint("You must move them back to the database's default tablespace before using this command.")));
                               2235                 :                :         }
                               2236                 :                : 
                               2237                 :              0 :         FreeDir(dstdir);
                               2238                 :                : 
                               2239                 :                :         /*
                               2240                 :                :          * The directory exists but is empty. We must remove it before using
                               2241                 :                :          * the copydir function.
                               2242                 :                :          */
                               2243         [ #  # ]:              0 :         if (rmdir(dst_dbpath) != 0)
                               2244         [ #  # ]:              0 :             elog(ERROR, "could not remove directory \"%s\": %m",
                               2245                 :                :                  dst_dbpath);
                               2246                 :                :     }
                               2247                 :                : 
                               2248                 :                :     /*
                               2249                 :                :      * Use an ENSURE block to make sure we remove the debris if the copy fails
                               2250                 :                :      * (eg, due to out-of-disk-space).  This is not a 100% solution, because
                               2251                 :                :      * of the possibility of failure during transaction commit, but it should
                               2252                 :                :      * handle most scenarios.
                               2253                 :                :      */
 6595 tgl@sss.pgh.pa.us        2254                 :CBC          14 :     fparms.dest_dboid = db_id;
                               2255                 :             14 :     fparms.dest_tsoid = dst_tblspcoid;
                               2256         [ +  - ]:             14 :     PG_ENSURE_ERROR_CLEANUP(movedb_failure_callback,
                               2257                 :                :                             PointerGetDatum(&fparms));
                               2258                 :                :     {
 1596 peter@eisentraut.org     2259                 :             14 :         Datum       new_record[Natts_pg_database] = {0};
                               2260                 :             14 :         bool        new_record_nulls[Natts_pg_database] = {0};
                               2261                 :             14 :         bool        new_record_repl[Natts_pg_database] = {0};
                               2262                 :                : 
                               2263                 :                :         /*
                               2264                 :                :          * Copy files from the old tablespace to the new one
                               2265                 :                :          */
 6595 tgl@sss.pgh.pa.us        2266                 :             14 :         copydir(src_dbpath, dst_dbpath, false);
                               2267                 :                : 
                               2268                 :                :         /*
                               2269                 :                :          * Record the filesystem change in XLOG
                               2270                 :                :          */
                               2271                 :                :         {
                               2272                 :                :             xl_dbase_create_file_copy_rec xlrec;
                               2273                 :                : 
                               2274                 :             14 :             xlrec.db_id = db_id;
                               2275                 :             14 :             xlrec.tablespace_id = dst_tblspcoid;
                               2276                 :             14 :             xlrec.src_db_id = db_id;
                               2277                 :             14 :             xlrec.src_tablespace_id = src_tblspcoid;
                               2278                 :                : 
 4391 heikki.linnakangas@i     2279                 :             14 :             XLogBeginInsert();
  655 peter@eisentraut.org     2280                 :             14 :             XLogRegisterData(&xlrec,
                               2281                 :                :                              sizeof(xl_dbase_create_file_copy_rec));
                               2282                 :                : 
 4391 heikki.linnakangas@i     2283                 :             14 :             (void) XLogInsert(RM_DBASE_ID,
                               2284                 :                :                               XLOG_DBASE_CREATE_FILE_COPY | XLR_SPECIAL_REL_UPDATE);
                               2285                 :                :         }
                               2286                 :                : 
                               2287                 :                :         /*
                               2288                 :                :          * Update the database's pg_database tuple
                               2289                 :                :          */
 6595 tgl@sss.pgh.pa.us        2290                 :             14 :         ScanKeyInit(&scankey,
                               2291                 :                :                     Anum_pg_database_datname,
                               2292                 :                :                     BTEqualStrategyNumber, F_NAMEEQ,
                               2293                 :                :                     CStringGetDatum(dbname));
                               2294                 :             14 :         sysscan = systable_beginscan(pgdbrel, DatabaseNameIndexId, true,
                               2295                 :                :                                      NULL, 1, &scankey);
                               2296                 :             14 :         oldtuple = systable_getnext(sysscan);
 3447                          2297         [ -  + ]:             14 :         if (!HeapTupleIsValid(oldtuple))    /* shouldn't happen... */
 6595 tgl@sss.pgh.pa.us        2298         [ #  # ]:UBC           0 :             ereport(ERROR,
                               2299                 :                :                     (errcode(ERRCODE_UNDEFINED_DATABASE),
                               2300                 :                :                      errmsg("database \"%s\" does not exist", dbname)));
  795 noah@leadboat.com        2301                 :CBC          14 :         LockTuple(pgdbrel, &oldtuple->t_self, InplaceUpdateTupleLock);
                               2302                 :                : 
 6595 tgl@sss.pgh.pa.us        2303                 :             14 :         new_record[Anum_pg_database_dattablespace - 1] = ObjectIdGetDatum(dst_tblspcoid);
                               2304                 :             14 :         new_record_repl[Anum_pg_database_dattablespace - 1] = true;
                               2305                 :                : 
                               2306                 :             14 :         newtuple = heap_modify_tuple(oldtuple, RelationGetDescr(pgdbrel),
                               2307                 :                :                                      new_record,
                               2308                 :                :                                      new_record_nulls, new_record_repl);
 3588 alvherre@alvh.no-ip.     2309                 :             14 :         CatalogTupleUpdate(pgdbrel, &oldtuple->t_self, newtuple);
  795 noah@leadboat.com        2310                 :             14 :         UnlockTuple(pgdbrel, &oldtuple->t_self, InplaceUpdateTupleLock);
                               2311                 :                : 
 2930 andres@anarazel.de       2312         [ -  + ]:             14 :         InvokeObjectPostAlterHook(DatabaseRelationId, db_id, 0);
                               2313                 :                : 
 6595 tgl@sss.pgh.pa.us        2314                 :             14 :         systable_endscan(sysscan);
                               2315                 :                : 
                               2316                 :                :         /*
                               2317                 :                :          * Force another checkpoint here.  As in CREATE DATABASE, this is to
                               2318                 :                :          * ensure that we don't have to replay a committed
                               2319                 :                :          * XLOG_DBASE_CREATE_FILE_COPY operation, which would cause us to lose
                               2320                 :                :          * any unlogged operations done in the new DB tablespace before the
                               2321                 :                :          * next checkpoint.
                               2322                 :                :          */
  505 nathan@postgresql.or     2323                 :             14 :         RequestCheckpoint(CHECKPOINT_FAST | CHECKPOINT_FORCE | CHECKPOINT_WAIT);
                               2324                 :                : 
                               2325                 :                :         /*
                               2326                 :                :          * Force synchronous commit, thus minimizing the window between
                               2327                 :                :          * copying the database files and committal of the transaction. If we
                               2328                 :                :          * crash before committing, we'll leave an orphaned set of files on
                               2329                 :                :          * disk, which is not fatal but not good either.
                               2330                 :                :          */
 6297 alvherre@alvh.no-ip.     2331                 :             14 :         ForceSyncCommit();
                               2332                 :                : 
                               2333                 :                :         /*
                               2334                 :                :          * Close pg_database, but keep lock till commit.
                               2335                 :                :          */
 2868 andres@anarazel.de       2336                 :             14 :         table_close(pgdbrel, NoLock);
                               2337                 :                :     }
 6595 tgl@sss.pgh.pa.us        2338         [ -  + ]:             14 :     PG_END_ENSURE_ERROR_CLEANUP(movedb_failure_callback,
                               2339                 :                :                                 PointerGetDatum(&fparms));
                               2340                 :                : 
                               2341                 :                :     /*
                               2342                 :                :      * Commit the transaction so that the pg_database update is committed. If
                               2343                 :                :      * we crash while removing files, the database won't be corrupt, we'll
                               2344                 :                :      * just leave some orphaned files in the old directory.
                               2345                 :                :      *
                               2346                 :                :      * (This is OK because we know we aren't inside a transaction block.)
                               2347                 :                :      *
                               2348                 :                :      * XXX would it be safe/better to do this inside the ensure block?  Not
                               2349                 :                :      * convinced it's a good idea; consider elog just after the transaction
                               2350                 :                :      * really commits.
                               2351                 :                :      */
                               2352                 :             14 :     PopActiveSnapshot();
                               2353                 :             14 :     CommitTransactionCommand();
                               2354                 :                : 
                               2355                 :                :     /* Start new transaction for the remaining work; don't need a snapshot */
                               2356                 :             14 :     StartTransactionCommand();
                               2357                 :                : 
                               2358                 :                :     /*
                               2359                 :                :      * Remove files from the old tablespace
                               2360                 :                :      */
                               2361         [ -  + ]:             14 :     if (!rmtree(src_dbpath, true))
 6595 tgl@sss.pgh.pa.us        2362         [ #  # ]:UBC           0 :         ereport(WARNING,
                               2363                 :                :                 (errmsg("some useless files may be left behind in old database directory \"%s\"",
                               2364                 :                :                         src_dbpath)));
                               2365                 :                : 
                               2366                 :                :     /*
                               2367                 :                :      * Record the filesystem change in XLOG
                               2368                 :                :      */
                               2369                 :                :     {
                               2370                 :                :         xl_dbase_drop_rec xlrec;
                               2371                 :                : 
 6595 tgl@sss.pgh.pa.us        2372                 :CBC          14 :         xlrec.db_id = db_id;
 2564 fujii@postgresql.org     2373                 :             14 :         xlrec.ntablespaces = 1;
                               2374                 :                : 
 4391 heikki.linnakangas@i     2375                 :             14 :         XLogBeginInsert();
  655 peter@eisentraut.org     2376                 :             14 :         XLogRegisterData(&xlrec, sizeof(xl_dbase_drop_rec));
                               2377                 :             14 :         XLogRegisterData(&src_tblspcoid, sizeof(Oid));
                               2378                 :                : 
 4391 heikki.linnakangas@i     2379                 :             14 :         (void) XLogInsert(RM_DBASE_ID,
                               2380                 :                :                           XLOG_DBASE_DROP | XLR_SPECIAL_REL_UPDATE);
                               2381                 :                :     }
                               2382                 :                : 
                               2383                 :                :     /* Now it's safe to release the database lock */
 6595 tgl@sss.pgh.pa.us        2384                 :             14 :     UnlockSharedObjectForSession(DatabaseRelationId, db_id, 0,
                               2385                 :                :                                  AccessExclusiveLock);
                               2386                 :                : 
 1678 alvherre@alvh.no-ip.     2387                 :             14 :     pfree(src_dbpath);
                               2388                 :             14 :     pfree(dst_dbpath);
                               2389                 :                : }
                               2390                 :                : 
                               2391                 :                : /* Error cleanup callback for movedb */
                               2392                 :                : static void
 6595 tgl@sss.pgh.pa.us        2393                 :UBC           0 : movedb_failure_callback(int code, Datum arg)
                               2394                 :                : {
                               2395                 :              0 :     movedb_failure_params *fparms = (movedb_failure_params *) DatumGetPointer(arg);
                               2396                 :                :     char       *dstpath;
                               2397                 :                : 
                               2398                 :                :     /* Get rid of anything we managed to copy to the target directory */
                               2399                 :              0 :     dstpath = GetDatabasePath(fparms->dest_dboid, fparms->dest_tsoid);
                               2400                 :                : 
                               2401                 :              0 :     (void) rmtree(dstpath, true);
                               2402                 :                : 
 1678 alvherre@alvh.no-ip.     2403                 :              0 :     pfree(dstpath);
 6595 tgl@sss.pgh.pa.us        2404                 :              0 : }
                               2405                 :                : 
                               2406                 :                : /*
                               2407                 :                :  * Process options and call dropdb function.
                               2408                 :                :  */
                               2409                 :                : void
 2573 akapila@postgresql.o     2410                 :CBC          89 : DropDatabase(ParseState *pstate, DropdbStmt *stmt)
                               2411                 :                : {
                               2412                 :             89 :     bool        force = false;
                               2413                 :                :     ListCell   *lc;
                               2414                 :                : 
                               2415   [ +  +  +  +  :            108 :     foreach(lc, stmt->options)
                                              +  + ]
                               2416                 :                :     {
                               2417                 :             19 :         DefElem    *opt = (DefElem *) lfirst(lc);
                               2418                 :                : 
                               2419         [ +  - ]:             19 :         if (strcmp(opt->defname, "force") == 0)
                               2420                 :             19 :             force = true;
                               2421                 :                :         else
 2573 akapila@postgresql.o     2422         [ #  # ]:UBC           0 :             ereport(ERROR,
                               2423                 :                :                     (errcode(ERRCODE_SYNTAX_ERROR),
                               2424                 :                :                      errmsg("unrecognized %s option \"%s\"",
                               2425                 :                :                             "DROP DATABASE", opt->defname),
                               2426                 :                :                      parser_errposition(pstate, opt->location)));
                               2427                 :                :     }
                               2428                 :                : 
 2573 akapila@postgresql.o     2429                 :CBC          89 :     dropdb(stmt->dbname, stmt->missing_ok, force);
                               2430                 :             77 : }
                               2431                 :                : 
                               2432                 :                : /*
                               2433                 :                :  * ALTER DATABASE name ...
                               2434                 :                :  */
                               2435                 :                : Oid
 3735 peter_e@gmx.net          2436                 :             57 : AlterDatabase(ParseState *pstate, AlterDatabaseStmt *stmt, bool isTopLevel)
                               2437                 :                : {
                               2438                 :                :     Relation    rel;
                               2439                 :                :     Oid         dboid;
                               2440                 :                :     HeapTuple   tuple,
                               2441                 :                :                 newtuple;
                               2442                 :                :     Form_pg_database datform;
                               2443                 :                :     ScanKeyData scankey;
                               2444                 :                :     SysScanDesc scan;
                               2445                 :                :     ListCell   *option;
 4533 tgl@sss.pgh.pa.us        2446                 :             57 :     bool        dbistemplate = false;
                               2447                 :             57 :     bool        dballowconnections = true;
 1234 andres@anarazel.de       2448                 :             57 :     int         dbconnlimit = DATCONNLIMIT_UNLIMITED;
 4533 tgl@sss.pgh.pa.us        2449                 :             57 :     DefElem    *distemplate = NULL;
                               2450                 :             57 :     DefElem    *dallowconnections = NULL;
 7790                          2451                 :             57 :     DefElem    *dconnlimit = NULL;
 6595                          2452                 :             57 :     DefElem    *dtablespace = NULL;
 1596 peter@eisentraut.org     2453                 :             57 :     Datum       new_record[Natts_pg_database] = {0};
                               2454                 :             57 :     bool        new_record_nulls[Natts_pg_database] = {0};
                               2455                 :             57 :     bool        new_record_repl[Natts_pg_database] = {0};
                               2456                 :                : 
                               2457                 :                :     /* Extract options from the statement node tree */
 7790 tgl@sss.pgh.pa.us        2458   [ +  -  +  +  :            114 :     foreach(option, stmt->options)
                                              +  + ]
                               2459                 :                :     {
                               2460                 :             57 :         DefElem    *defel = (DefElem *) lfirst(option);
                               2461                 :                : 
 4533                          2462         [ +  + ]:             57 :         if (strcmp(defel->defname, "is_template") == 0)
                               2463                 :                :         {
                               2464         [ -  + ]:             15 :             if (distemplate)
 1962 dean.a.rasheed@gmail     2465                 :UBC           0 :                 errorConflictingDefElem(defel, pstate);
 4533 tgl@sss.pgh.pa.us        2466                 :CBC          15 :             distemplate = defel;
                               2467                 :                :         }
                               2468         [ +  + ]:             42 :         else if (strcmp(defel->defname, "allow_connections") == 0)
                               2469                 :                :         {
                               2470         [ -  + ]:             22 :             if (dallowconnections)
 1962 dean.a.rasheed@gmail     2471                 :UBC           0 :                 errorConflictingDefElem(defel, pstate);
 4533 tgl@sss.pgh.pa.us        2472                 :CBC          22 :             dallowconnections = defel;
                               2473                 :                :         }
                               2474         [ +  + ]:             20 :         else if (strcmp(defel->defname, "connection_limit") == 0)
                               2475                 :                :         {
 7790                          2476         [ -  + ]:              6 :             if (dconnlimit)
 1962 dean.a.rasheed@gmail     2477                 :UBC           0 :                 errorConflictingDefElem(defel, pstate);
 7790 tgl@sss.pgh.pa.us        2478                 :CBC           6 :             dconnlimit = defel;
                               2479                 :                :         }
 6595                          2480         [ +  - ]:             14 :         else if (strcmp(defel->defname, "tablespace") == 0)
                               2481                 :                :         {
                               2482         [ -  + ]:             14 :             if (dtablespace)
 1962 dean.a.rasheed@gmail     2483                 :UBC           0 :                 errorConflictingDefElem(defel, pstate);
 6595 tgl@sss.pgh.pa.us        2484                 :CBC          14 :             dtablespace = defel;
                               2485                 :                :         }
                               2486                 :                :         else
 4533 tgl@sss.pgh.pa.us        2487         [ #  # ]:UBC           0 :             ereport(ERROR,
                               2488                 :                :                     (errcode(ERRCODE_SYNTAX_ERROR),
                               2489                 :                :                      errmsg("option \"%s\" not recognized", defel->defname),
                               2490                 :                :                      parser_errposition(pstate, defel->location)));
                               2491                 :                :     }
                               2492                 :                : 
 6595 tgl@sss.pgh.pa.us        2493         [ +  + ]:CBC          57 :     if (dtablespace)
                               2494                 :                :     {
                               2495                 :                :         /*
                               2496                 :                :          * While the SET TABLESPACE syntax doesn't allow any other options,
                               2497                 :                :          * somebody could write "WITH TABLESPACE ...".  Forbid any other
                               2498                 :                :          * options from being specified in that case.
                               2499                 :                :          */
 4533                          2500         [ -  + ]:             14 :         if (list_length(stmt->options) != 1)
 4533 tgl@sss.pgh.pa.us        2501         [ #  # ]:UBC           0 :             ereport(ERROR,
                               2502                 :                :                     (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
                               2503                 :                :                      errmsg("option \"%s\" cannot be specified with other options",
                               2504                 :                :                             dtablespace->defname),
                               2505                 :                :                      parser_errposition(pstate, dtablespace->location)));
                               2506                 :                :         /* this case isn't allowed within a transaction block */
 3207 peter_e@gmx.net          2507                 :CBC          14 :         PreventInTransactionBlock(isTopLevel, "ALTER DATABASE SET TABLESPACE");
 4533 tgl@sss.pgh.pa.us        2508                 :             14 :         movedb(stmt->dbname, defGetString(dtablespace));
 5082 rhaas@postgresql.org     2509                 :             14 :         return InvalidOid;
                               2510                 :                :     }
                               2511                 :                : 
 4533 tgl@sss.pgh.pa.us        2512   [ +  +  +  - ]:             43 :     if (distemplate && distemplate->arg)
                               2513                 :             15 :         dbistemplate = defGetBoolean(distemplate);
                               2514   [ +  +  +  - ]:             43 :     if (dallowconnections && dallowconnections->arg)
                               2515                 :             22 :         dballowconnections = defGetBoolean(dallowconnections);
                               2516   [ +  +  +  - ]:             43 :     if (dconnlimit && dconnlimit->arg)
                               2517                 :                :     {
                               2518                 :              6 :         dbconnlimit = defGetInt32(dconnlimit);
 1234 andres@anarazel.de       2519         [ -  + ]:              6 :         if (dbconnlimit < DATCONNLIMIT_UNLIMITED)
 6511 heikki.linnakangas@i     2520         [ #  # ]:UBC           0 :             ereport(ERROR,
                               2521                 :                :                     (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
                               2522                 :                :                      errmsg("invalid connection limit: %d", dbconnlimit)));
                               2523                 :                :     }
                               2524                 :                : 
                               2525                 :                :     /*
                               2526                 :                :      * Get the old tuple.  We don't need a lock on the database per se,
                               2527                 :                :      * because we're not going to do anything that would mess up incoming
                               2528                 :                :      * connections.
                               2529                 :                :      */
 2868 andres@anarazel.de       2530                 :CBC          43 :     rel = table_open(DatabaseRelationId, RowExclusiveLock);
 7790 tgl@sss.pgh.pa.us        2531                 :             43 :     ScanKeyInit(&scankey,
                               2532                 :                :                 Anum_pg_database_datname,
                               2533                 :                :                 BTEqualStrategyNumber, F_NAMEEQ,
 3728                          2534                 :             43 :                 CStringGetDatum(stmt->dbname));
 7790                          2535                 :             43 :     scan = systable_beginscan(rel, DatabaseNameIndexId, true,
                               2536                 :                :                               NULL, 1, &scankey);
                               2537                 :             43 :     tuple = systable_getnext(scan);
                               2538         [ -  + ]:             43 :     if (!HeapTupleIsValid(tuple))
 7790 tgl@sss.pgh.pa.us        2539         [ #  # ]:UBC           0 :         ereport(ERROR,
                               2540                 :                :                 (errcode(ERRCODE_UNDEFINED_DATABASE),
                               2541                 :                :                  errmsg("database \"%s\" does not exist", stmt->dbname)));
  795 noah@leadboat.com        2542                 :CBC          43 :     LockTuple(rel, &tuple->t_self, InplaceUpdateTupleLock);
                               2543                 :                : 
 2930 andres@anarazel.de       2544                 :             43 :     datform = (Form_pg_database) GETSTRUCT(tuple);
                               2545                 :             43 :     dboid = datform->oid;
                               2546                 :                : 
 1234                          2547         [ +  + ]:             43 :     if (database_is_invalid_form(datform))
                               2548                 :                :     {
                               2549         [ +  - ]:              1 :         ereport(FATAL,
                               2550                 :                :                 errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
                               2551                 :                :                 errmsg("cannot alter invalid database \"%s\"", stmt->dbname),
                               2552                 :                :                 errhint("Use DROP DATABASE to drop invalid databases."));
                               2553                 :                :     }
                               2554                 :                : 
 1476 peter@eisentraut.org     2555         [ -  + ]:             42 :     if (!object_ownercheck(DatabaseRelationId, dboid, GetUserId()))
 3283 peter_e@gmx.net          2556                 :UBC           0 :         aclcheck_error(ACLCHECK_NOT_OWNER, OBJECT_DATABASE,
 7790 tgl@sss.pgh.pa.us        2557                 :              0 :                        stmt->dbname);
                               2558                 :                : 
                               2559                 :                :     /*
                               2560                 :                :      * In order to avoid getting locked out and having to go through
                               2561                 :                :      * standalone mode, we refuse to disallow connections to the database
                               2562                 :                :      * we're currently connected to.  Lockout can still happen with concurrent
                               2563                 :                :      * sessions but the likeliness of that is not high enough to worry about.
                               2564                 :                :      */
 4533 tgl@sss.pgh.pa.us        2565   [ +  +  -  + ]:CBC          42 :     if (!dballowconnections && dboid == MyDatabaseId)
 4533 tgl@sss.pgh.pa.us        2566         [ #  # ]:UBC           0 :         ereport(ERROR,
                               2567                 :                :                 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
                               2568                 :                :                  errmsg("cannot disallow connections for current database")));
                               2569                 :                : 
                               2570                 :                :     /*
                               2571                 :                :      * Build an updated tuple, perusing the information just obtained
                               2572                 :                :      */
 4533 tgl@sss.pgh.pa.us        2573         [ +  + ]:CBC          42 :     if (distemplate)
                               2574                 :                :     {
                               2575                 :             15 :         new_record[Anum_pg_database_datistemplate - 1] = BoolGetDatum(dbistemplate);
                               2576                 :             15 :         new_record_repl[Anum_pg_database_datistemplate - 1] = true;
                               2577                 :                :     }
                               2578         [ +  + ]:             42 :     if (dallowconnections)
                               2579                 :                :     {
                               2580                 :             22 :         new_record[Anum_pg_database_datallowconn - 1] = BoolGetDatum(dballowconnections);
                               2581                 :             22 :         new_record_repl[Anum_pg_database_datallowconn - 1] = true;
                               2582                 :                :     }
 7790                          2583         [ +  + ]:             42 :     if (dconnlimit)
                               2584                 :                :     {
 4533                          2585                 :              5 :         new_record[Anum_pg_database_datconnlimit - 1] = Int32GetDatum(dbconnlimit);
 6600                          2586                 :              5 :         new_record_repl[Anum_pg_database_datconnlimit - 1] = true;
                               2587                 :                :     }
                               2588                 :                : 
                               2589                 :             42 :     newtuple = heap_modify_tuple(tuple, RelationGetDescr(rel), new_record,
                               2590                 :                :                                  new_record_nulls, new_record_repl);
 3588 alvherre@alvh.no-ip.     2591                 :             42 :     CatalogTupleUpdate(rel, &tuple->t_self, newtuple);
  795 noah@leadboat.com        2592                 :             42 :     UnlockTuple(rel, &tuple->t_self, InplaceUpdateTupleLock);
                               2593                 :                : 
 2930 andres@anarazel.de       2594         [ -  + ]:             42 :     InvokeObjectPostAlterHook(DatabaseRelationId, dboid, 0);
                               2595                 :                : 
 7790 tgl@sss.pgh.pa.us        2596                 :             42 :     systable_endscan(scan);
                               2597                 :                : 
                               2598                 :                :     /* Close pg_database, but keep lock till commit */
 2868 andres@anarazel.de       2599                 :             42 :     table_close(rel, NoLock);
                               2600                 :                : 
 5082 rhaas@postgresql.org     2601                 :             42 :     return dboid;
                               2602                 :                : }
                               2603                 :                : 
                               2604                 :                : 
                               2605                 :                : /*
                               2606                 :                :  * ALTER DATABASE name REFRESH COLLATION VERSION
                               2607                 :                :  */
                               2608                 :                : ObjectAddress
 1748 peter@eisentraut.org     2609                 :              4 : AlterDatabaseRefreshColl(AlterDatabaseRefreshCollStmt *stmt)
                               2610                 :                : {
                               2611                 :                :     Relation    rel;
                               2612                 :                :     ScanKeyData scankey;
                               2613                 :                :     SysScanDesc scan;
                               2614                 :                :     Oid         db_id;
                               2615                 :                :     HeapTuple   tuple;
                               2616                 :                :     Form_pg_database datForm;
                               2617                 :                :     ObjectAddress address;
                               2618                 :                :     Datum       datum;
                               2619                 :                :     bool        isnull;
                               2620                 :                :     char       *oldversion;
                               2621                 :                :     char       *newversion;
                               2622                 :                : 
                               2623                 :              4 :     rel = table_open(DatabaseRelationId, RowExclusiveLock);
                               2624                 :              4 :     ScanKeyInit(&scankey,
                               2625                 :                :                 Anum_pg_database_datname,
                               2626                 :                :                 BTEqualStrategyNumber, F_NAMEEQ,
                               2627                 :              4 :                 CStringGetDatum(stmt->dbname));
                               2628                 :              4 :     scan = systable_beginscan(rel, DatabaseNameIndexId, true,
                               2629                 :                :                               NULL, 1, &scankey);
                               2630                 :              4 :     tuple = systable_getnext(scan);
                               2631         [ -  + ]:              4 :     if (!HeapTupleIsValid(tuple))
 1748 peter@eisentraut.org     2632         [ #  # ]:UBC           0 :         ereport(ERROR,
                               2633                 :                :                 (errcode(ERRCODE_UNDEFINED_DATABASE),
                               2634                 :                :                  errmsg("database \"%s\" does not exist", stmt->dbname)));
                               2635                 :                : 
 1748 peter@eisentraut.org     2636                 :CBC           4 :     datForm = (Form_pg_database) GETSTRUCT(tuple);
                               2637                 :              4 :     db_id = datForm->oid;
                               2638                 :                : 
 1476                          2639         [ -  + ]:              4 :     if (!object_ownercheck(DatabaseRelationId, db_id, GetUserId()))
 1748 peter@eisentraut.org     2640                 :UBC           0 :         aclcheck_error(ACLCHECK_NOT_OWNER, OBJECT_DATABASE,
                               2641                 :              0 :                        stmt->dbname);
  795 noah@leadboat.com        2642                 :CBC           4 :     LockTuple(rel, &tuple->t_self, InplaceUpdateTupleLock);
                               2643                 :                : 
 1748 peter@eisentraut.org     2644                 :              4 :     datum = heap_getattr(tuple, Anum_pg_database_datcollversion, RelationGetDescr(rel), &isnull);
                               2645         [ +  - ]:              4 :     oldversion = isnull ? NULL : TextDatumGetCString(datum);
                               2646                 :                : 
  990 jdavis@postgresql.or     2647         [ +  + ]:              4 :     if (datForm->datlocprovider == COLLPROVIDER_LIBC)
                               2648                 :                :     {
                               2649                 :              3 :         datum = heap_getattr(tuple, Anum_pg_database_datcollate, RelationGetDescr(rel), &isnull);
                               2650         [ -  + ]:              3 :         if (isnull)
  990 jdavis@postgresql.or     2651         [ #  # ]:UBC           0 :             elog(ERROR, "unexpected null in pg_database");
                               2652                 :                :     }
                               2653                 :                :     else
                               2654                 :                :     {
  990 jdavis@postgresql.or     2655                 :CBC           1 :         datum = heap_getattr(tuple, Anum_pg_database_datlocale, RelationGetDescr(rel), &isnull);
                               2656         [ -  + ]:              1 :         if (isnull)
  990 jdavis@postgresql.or     2657         [ #  # ]:UBC           0 :             elog(ERROR, "unexpected null in pg_database");
                               2658                 :                :     }
                               2659                 :                : 
  990 jdavis@postgresql.or     2660                 :CBC           4 :     newversion = get_collation_actual_version(datForm->datlocprovider,
                               2661                 :              4 :                                               TextDatumGetCString(datum));
                               2662                 :                : 
                               2663                 :                :     /* cannot change from NULL to non-NULL or vice versa */
 1748 peter@eisentraut.org     2664   [ -  +  -  -  :              4 :     if ((!oldversion && newversion) || (oldversion && !newversion))
                                        +  -  -  + ]
 1748 peter@eisentraut.org     2665         [ #  # ]:UBC           0 :         elog(ERROR, "invalid collation version change");
 1748 peter@eisentraut.org     2666   [ +  -  +  -  :CBC           4 :     else if (oldversion && newversion && strcmp(newversion, oldversion) != 0)
                                              -  + ]
 1748 peter@eisentraut.org     2667                 :UBC           0 :     {
                               2668                 :              0 :         bool        nulls[Natts_pg_database] = {0};
                               2669                 :              0 :         bool        replaces[Natts_pg_database] = {0};
                               2670                 :              0 :         Datum       values[Natts_pg_database] = {0};
                               2671                 :                :         HeapTuple   newtuple;
                               2672                 :                : 
                               2673         [ #  # ]:              0 :         ereport(NOTICE,
                               2674                 :                :                 (errmsg("changing version from %s to %s",
                               2675                 :                :                         oldversion, newversion)));
                               2676                 :                : 
                               2677                 :              0 :         values[Anum_pg_database_datcollversion - 1] = CStringGetTextDatum(newversion);
                               2678                 :              0 :         replaces[Anum_pg_database_datcollversion - 1] = true;
                               2679                 :                : 
  795 noah@leadboat.com        2680                 :              0 :         newtuple = heap_modify_tuple(tuple, RelationGetDescr(rel),
                               2681                 :                :                                      values, nulls, replaces);
                               2682                 :              0 :         CatalogTupleUpdate(rel, &tuple->t_self, newtuple);
                               2683                 :              0 :         heap_freetuple(newtuple);
                               2684                 :                :     }
                               2685                 :                :     else
 1748 peter@eisentraut.org     2686         [ +  - ]:CBC           4 :         ereport(NOTICE,
                               2687                 :                :                 (errmsg("version has not changed")));
  795 noah@leadboat.com        2688                 :              4 :     UnlockTuple(rel, &tuple->t_self, InplaceUpdateTupleLock);
                               2689                 :                : 
 1748 peter@eisentraut.org     2690         [ -  + ]:              4 :     InvokeObjectPostAlterHook(DatabaseRelationId, db_id, 0);
                               2691                 :                : 
                               2692                 :              4 :     ObjectAddressSet(address, DatabaseRelationId, db_id);
                               2693                 :                : 
                               2694                 :              4 :     systable_endscan(scan);
                               2695                 :                : 
                               2696                 :              4 :     table_close(rel, NoLock);
                               2697                 :                : 
                               2698                 :              4 :     return address;
                               2699                 :                : }
                               2700                 :                : 
                               2701                 :                : 
                               2702                 :                : /*
                               2703                 :                :  * ALTER DATABASE name SET ...
                               2704                 :                :  */
                               2705                 :                : Oid
 9038 peter_e@gmx.net          2706                 :            682 : AlterDatabaseSet(AlterDatabaseSetStmt *stmt)
                               2707                 :                : {
 5959 rhaas@postgresql.org     2708                 :            682 :     Oid         datid = get_database_oid(stmt->dbname, false);
                               2709                 :                : 
                               2710                 :                :     /*
                               2711                 :                :      * Obtain a lock on the database and make sure it didn't go away in the
                               2712                 :                :      * meantime.
                               2713                 :                :      */
 6261 alvherre@alvh.no-ip.     2714                 :            682 :     shdepLockAndCheckObject(DatabaseRelationId, datid);
                               2715                 :                : 
 1476 peter@eisentraut.org     2716         [ -  + ]:            682 :     if (!object_ownercheck(DatabaseRelationId, datid, GetUserId()))
 3283 peter_e@gmx.net          2717                 :UBC           0 :         aclcheck_error(ACLCHECK_NOT_OWNER, OBJECT_DATABASE,
 6119 bruce@momjian.us         2718                 :              0 :                        stmt->dbname);
                               2719                 :                : 
 6261 alvherre@alvh.no-ip.     2720                 :CBC         682 :     AlterSetting(datid, InvalidOid, stmt->setstmt);
                               2721                 :                : 
                               2722                 :            680 :     UnlockSharedObject(DatabaseRelationId, datid, 0, AccessShareLock);
                               2723                 :                : 
 5082 rhaas@postgresql.org     2724                 :            680 :     return datid;
                               2725                 :                : }
                               2726                 :                : 
                               2727                 :                : 
                               2728                 :                : /*
                               2729                 :                :  * ALTER DATABASE name OWNER TO newowner
                               2730                 :                :  */
                               2731                 :                : ObjectAddress
 7823 tgl@sss.pgh.pa.us        2732                 :             69 : AlterDatabaseOwner(const char *dbname, Oid newOwnerId)
                               2733                 :                : {
                               2734                 :                :     Oid         db_id;
                               2735                 :                :     HeapTuple   tuple;
                               2736                 :                :     Relation    rel;
                               2737                 :                :     ScanKeyData scankey;
                               2738                 :                :     SysScanDesc scan;
                               2739                 :                :     Form_pg_database datForm;
                               2740                 :                :     ObjectAddress address;
                               2741                 :                : 
                               2742                 :                :     /*
                               2743                 :                :      * Get the old tuple.  We don't need a lock on the database per se,
                               2744                 :                :      * because we're not going to do anything that would mess up incoming
                               2745                 :                :      * connections.
                               2746                 :                :      */
 2868 andres@anarazel.de       2747                 :             69 :     rel = table_open(DatabaseRelationId, RowExclusiveLock);
 8221 bruce@momjian.us         2748                 :             69 :     ScanKeyInit(&scankey,
                               2749                 :                :                 Anum_pg_database_datname,
                               2750                 :                :                 BTEqualStrategyNumber, F_NAMEEQ,
                               2751                 :                :                 CStringGetDatum(dbname));
 7898 tgl@sss.pgh.pa.us        2752                 :             69 :     scan = systable_beginscan(rel, DatabaseNameIndexId, true,
                               2753                 :                :                               NULL, 1, &scankey);
 8221 bruce@momjian.us         2754                 :             69 :     tuple = systable_getnext(scan);
                               2755         [ -  + ]:             69 :     if (!HeapTupleIsValid(tuple))
 8221 bruce@momjian.us         2756         [ #  # ]:UBC           0 :         ereport(ERROR,
                               2757                 :                :                 (errcode(ERRCODE_UNDEFINED_DATABASE),
                               2758                 :                :                  errmsg("database \"%s\" does not exist", dbname)));
                               2759                 :                : 
 8154 tgl@sss.pgh.pa.us        2760                 :CBC          69 :     datForm = (Form_pg_database) GETSTRUCT(tuple);
 2930 andres@anarazel.de       2761                 :             69 :     db_id = datForm->oid;
                               2762                 :                : 
                               2763                 :                :     /*
                               2764                 :                :      * If the new owner is the same as the existing owner, consider the
                               2765                 :                :      * command to have succeeded.  This is to be consistent with other
                               2766                 :                :      * objects.
                               2767                 :                :      */
 7823 tgl@sss.pgh.pa.us        2768         [ +  + ]:             69 :     if (datForm->datdba != newOwnerId)
                               2769                 :                :     {
                               2770                 :                :         Datum       repl_val[Natts_pg_database];
 1596 peter@eisentraut.org     2771                 :             27 :         bool        repl_null[Natts_pg_database] = {0};
                               2772                 :             27 :         bool        repl_repl[Natts_pg_database] = {0};
                               2773                 :                :         Acl        *newAcl;
                               2774                 :                :         Datum       aclDatum;
                               2775                 :                :         bool        isNull;
                               2776                 :                :         HeapTuple   newtuple;
                               2777                 :                : 
                               2778                 :                :         /* Otherwise, must be owner of the existing object */
 1476                          2779         [ -  + ]:             27 :         if (!object_ownercheck(DatabaseRelationId, db_id, GetUserId()))
 3283 peter_e@gmx.net          2780                 :UBC           0 :             aclcheck_error(ACLCHECK_NOT_OWNER, OBJECT_DATABASE,
                               2781                 :                :                            dbname);
                               2782                 :                : 
                               2783                 :                :         /* Must be able to become new owner */
 1471 rhaas@postgresql.org     2784                 :CBC          27 :         check_can_set_role(GetUserId(), newOwnerId);
                               2785                 :                : 
                               2786                 :                :         /*
                               2787                 :                :          * must have createdb rights
                               2788                 :                :          *
                               2789                 :                :          * NOTE: This is different from other alter-owner checks in that the
                               2790                 :                :          * current user is checked for createdb privileges instead of the
                               2791                 :                :          * destination owner.  This is consistent with the CREATE case for
                               2792                 :                :          * databases.  Because superusers will always have this right, we need
                               2793                 :                :          * no special case for them.
                               2794                 :                :          */
 4358 alvherre@alvh.no-ip.     2795         [ +  + ]:             27 :         if (!have_createdb_privilege())
 8191 tgl@sss.pgh.pa.us        2796         [ +  - ]:              4 :             ereport(ERROR,
                               2797                 :                :                     (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
                               2798                 :                :                      errmsg("permission denied to change owner of database")));
                               2799                 :                : 
  795 noah@leadboat.com        2800                 :             23 :         LockTuple(rel, &tuple->t_self, InplaceUpdateTupleLock);
                               2801                 :                : 
 6600 tgl@sss.pgh.pa.us        2802                 :             23 :         repl_repl[Anum_pg_database_datdba - 1] = true;
 7823                          2803                 :             23 :         repl_val[Anum_pg_database_datdba - 1] = ObjectIdGetDatum(newOwnerId);
                               2804                 :                : 
                               2805                 :                :         /*
                               2806                 :                :          * Determine the modified ACL for the new owner.  This is only
                               2807                 :                :          * necessary when the ACL is non-null.
                               2808                 :                :          */
 8154                          2809                 :             23 :         aclDatum = heap_getattr(tuple,
                               2810                 :                :                                 Anum_pg_database_datacl,
                               2811                 :                :                                 RelationGetDescr(rel),
                               2812                 :                :                                 &isNull);
                               2813         [ -  + ]:             23 :         if (!isNull)
                               2814                 :                :         {
 8154 tgl@sss.pgh.pa.us        2815                 :UBC           0 :             newAcl = aclnewowner(DatumGetAclP(aclDatum),
                               2816                 :                :                                  datForm->datdba, newOwnerId);
 6600                          2817                 :              0 :             repl_repl[Anum_pg_database_datacl - 1] = true;
 8154                          2818                 :              0 :             repl_val[Anum_pg_database_datacl - 1] = PointerGetDatum(newAcl);
                               2819                 :                :         }
                               2820                 :                : 
 6600 tgl@sss.pgh.pa.us        2821                 :CBC          23 :         newtuple = heap_modify_tuple(tuple, RelationGetDescr(rel), repl_val, repl_null, repl_repl);
 3588 alvherre@alvh.no-ip.     2822                 :             23 :         CatalogTupleUpdate(rel, &newtuple->t_self, newtuple);
  795 noah@leadboat.com        2823                 :             23 :         UnlockTuple(rel, &tuple->t_self, InplaceUpdateTupleLock);
                               2824                 :                : 
 8154 tgl@sss.pgh.pa.us        2825                 :             23 :         heap_freetuple(newtuple);
                               2826                 :                : 
                               2827                 :                :         /* Update owner dependency reference */
 2930 andres@anarazel.de       2828                 :             23 :         changeDependencyOnOwner(DatabaseRelationId, db_id, newOwnerId);
                               2829                 :                :     }
                               2830                 :                : 
                               2831         [ -  + ]:             65 :     InvokeObjectPostAlterHook(DatabaseRelationId, db_id, 0);
                               2832                 :                : 
 4288 alvherre@alvh.no-ip.     2833                 :             65 :     ObjectAddressSet(address, DatabaseRelationId, db_id);
                               2834                 :                : 
 7945 tgl@sss.pgh.pa.us        2835                 :             65 :     systable_endscan(scan);
                               2836                 :                : 
                               2837                 :                :     /* Close pg_database, but keep lock till commit */
 2868 andres@anarazel.de       2838                 :             65 :     table_close(rel, NoLock);
                               2839                 :                : 
 4288 alvherre@alvh.no-ip.     2840                 :             65 :     return address;
                               2841                 :                : }
                               2842                 :                : 
                               2843                 :                : 
                               2844                 :                : Datum
 1748 peter@eisentraut.org     2845                 :             58 : pg_database_collation_actual_version(PG_FUNCTION_ARGS)
                               2846                 :                : {
                               2847                 :             58 :     Oid         dbid = PG_GETARG_OID(0);
                               2848                 :                :     HeapTuple   tp;
                               2849                 :                :     char        datlocprovider;
                               2850                 :                :     Datum       datum;
                               2851                 :                :     char       *version;
                               2852                 :                : 
                               2853                 :             58 :     tp = SearchSysCache1(DATABASEOID, ObjectIdGetDatum(dbid));
                               2854         [ -  + ]:             58 :     if (!HeapTupleIsValid(tp))
 1748 peter@eisentraut.org     2855         [ #  # ]:UBC           0 :         ereport(ERROR,
                               2856                 :                :                 (errcode(ERRCODE_UNDEFINED_OBJECT),
                               2857                 :                :                  errmsg("database with OID %u does not exist", dbid)));
                               2858                 :                : 
 1717 peter@eisentraut.org     2859                 :CBC          58 :     datlocprovider = ((Form_pg_database) GETSTRUCT(tp))->datlocprovider;
                               2860                 :                : 
  990 jdavis@postgresql.or     2861         [ +  + ]:             58 :     if (datlocprovider == COLLPROVIDER_LIBC)
                               2862                 :             50 :         datum = SysCacheGetAttrNotNull(DATABASEOID, tp, Anum_pg_database_datcollate);
                               2863                 :                :     else
                               2864                 :              8 :         datum = SysCacheGetAttrNotNull(DATABASEOID, tp, Anum_pg_database_datlocale);
                               2865                 :                : 
                               2866                 :             58 :     version = get_collation_actual_version(datlocprovider,
                               2867                 :             58 :                                            TextDatumGetCString(datum));
                               2868                 :                : 
 1748 peter@eisentraut.org     2869                 :             58 :     ReleaseSysCache(tp);
                               2870                 :                : 
                               2871         [ +  + ]:             58 :     if (version)
                               2872                 :             44 :         PG_RETURN_TEXT_P(cstring_to_text(version));
                               2873                 :                :     else
                               2874                 :             14 :         PG_RETURN_NULL();
                               2875                 :                : }
                               2876                 :                : 
                               2877                 :                : 
                               2878                 :                : /*
                               2879                 :                :  * Helper functions
                               2880                 :                :  */
                               2881                 :                : 
                               2882                 :                : /*
                               2883                 :                :  * Look up info about the database named "name".  If the database exists,
                               2884                 :                :  * obtain the specified lock type on it, fill in any of the remaining
                               2885                 :                :  * parameters that aren't NULL, and return true.  If no such database,
                               2886                 :                :  * return false.
                               2887                 :                :  */
                               2888                 :                : static bool
 7513 tgl@sss.pgh.pa.us        2889                 :            579 : get_db_info(const char *name, LOCKMODE lockmode,
                               2890                 :                :             Oid *dbIdP, Oid *ownerIdP,
                               2891                 :                :             int *encodingP, bool *dbIsTemplateP, bool *dbAllowConnP, bool *dbHasLoginEvtP,
                               2892                 :                :             TransactionId *dbFrozenXidP, MultiXactId *dbMinMultiP,
                               2893                 :                :             Oid *dbTablespace, char **dbCollate, char **dbCtype, char **dbLocale,
                               2894                 :                :             char **dbIcurules,
                               2895                 :                :             char *dbLocProvider,
                               2896                 :                :             char **dbCollversion)
                               2897                 :                : {
                               2898                 :            579 :     bool        result = false;
                               2899                 :                :     Relation    relation;
                               2900                 :                : 
 1492 peter@eisentraut.org     2901         [ -  + ]:            579 :     Assert(name);
                               2902                 :                : 
                               2903                 :                :     /* Caller may wish to grab a better lock on pg_database beforehand... */
 2868 andres@anarazel.de       2904                 :            579 :     relation = table_open(DatabaseRelationId, AccessShareLock);
                               2905                 :                : 
                               2906                 :                :     /*
                               2907                 :                :      * Loop covers the rare case where the database is renamed before we can
                               2908                 :                :      * lock it.  We try again just in case we can find a new one of the same
                               2909                 :                :      * name.
                               2910                 :                :      */
                               2911                 :                :     for (;;)
 7513 tgl@sss.pgh.pa.us        2912                 :UBC           0 :     {
                               2913                 :                :         ScanKeyData scanKey;
                               2914                 :                :         SysScanDesc scan;
                               2915                 :                :         HeapTuple   tuple;
                               2916                 :                :         Oid         dbOid;
                               2917                 :                : 
                               2918                 :                :         /*
                               2919                 :                :          * there's no syscache for database-indexed-by-name, so must do it the
                               2920                 :                :          * hard way
                               2921                 :                :          */
 7513 tgl@sss.pgh.pa.us        2922                 :CBC         579 :         ScanKeyInit(&scanKey,
                               2923                 :                :                     Anum_pg_database_datname,
                               2924                 :                :                     BTEqualStrategyNumber, F_NAMEEQ,
                               2925                 :                :                     CStringGetDatum(name));
                               2926                 :                : 
                               2927                 :            579 :         scan = systable_beginscan(relation, DatabaseNameIndexId, true,
                               2928                 :                :                                   NULL, 1, &scanKey);
                               2929                 :                : 
                               2930                 :            579 :         tuple = systable_getnext(scan);
                               2931                 :                : 
                               2932         [ +  + ]:            579 :         if (!HeapTupleIsValid(tuple))
                               2933                 :                :         {
                               2934                 :                :             /* definitely no database of that name */
                               2935                 :             21 :             systable_endscan(scan);
                               2936                 :             21 :             break;
                               2937                 :                :         }
                               2938                 :                : 
 2930 andres@anarazel.de       2939                 :            558 :         dbOid = ((Form_pg_database) GETSTRUCT(tuple))->oid;
                               2940                 :                : 
 7513 tgl@sss.pgh.pa.us        2941                 :            558 :         systable_endscan(scan);
                               2942                 :                : 
                               2943                 :                :         /*
                               2944                 :                :          * Now that we have a database OID, we can try to lock the DB.
                               2945                 :                :          */
                               2946         [ +  - ]:            558 :         if (lockmode != NoLock)
                               2947                 :            558 :             LockSharedObject(DatabaseRelationId, dbOid, 0, lockmode);
                               2948                 :                : 
                               2949                 :                :         /*
                               2950                 :                :          * And now, re-fetch the tuple by OID.  If it's still there and still
                               2951                 :                :          * the same name, we win; else, drop the lock and loop back to try
                               2952                 :                :          * again.
                               2953                 :                :          */
 6131 rhaas@postgresql.org     2954                 :            558 :         tuple = SearchSysCache1(DATABASEOID, ObjectIdGetDatum(dbOid));
 7513 tgl@sss.pgh.pa.us        2955         [ +  - ]:            558 :         if (HeapTupleIsValid(tuple))
                               2956                 :                :         {
                               2957                 :            558 :             Form_pg_database dbform = (Form_pg_database) GETSTRUCT(tuple);
                               2958                 :                : 
                               2959         [ +  - ]:            558 :             if (strcmp(name, NameStr(dbform->datname)) == 0)
                               2960                 :                :             {
                               2961                 :                :                 Datum       datum;
                               2962                 :                :                 bool        isnull;
                               2963                 :                : 
                               2964                 :                :                 /* oid of the database */
                               2965         [ +  - ]:            558 :                 if (dbIdP)
                               2966                 :            558 :                     *dbIdP = dbOid;
                               2967                 :                :                 /* oid of the owner */
                               2968         [ +  + ]:            558 :                 if (ownerIdP)
                               2969                 :            467 :                     *ownerIdP = dbform->datdba;
                               2970                 :                :                 /* character encoding */
                               2971         [ +  + ]:            558 :                 if (encodingP)
                               2972                 :            467 :                     *encodingP = dbform->encoding;
                               2973                 :                :                 /* allowed as template? */
                               2974         [ +  + ]:            558 :                 if (dbIsTemplateP)
                               2975                 :            535 :                     *dbIsTemplateP = dbform->datistemplate;
                               2976                 :                :                 /* Has on login event trigger? */
 1139 akorotkov@postgresql     2977         [ +  + ]:            558 :                 if (dbHasLoginEvtP)
                               2978                 :            467 :                     *dbHasLoginEvtP = dbform->dathasloginevt;
                               2979                 :                :                 /* allowing connections? */
 7513 tgl@sss.pgh.pa.us        2980         [ +  + ]:            558 :                 if (dbAllowConnP)
                               2981                 :            467 :                     *dbAllowConnP = dbform->datallowconn;
                               2982                 :                :                 /* limit of frozen XIDs */
 7328                          2983         [ +  + ]:            558 :                 if (dbFrozenXidP)
                               2984                 :            467 :                     *dbFrozenXidP = dbform->datfrozenxid;
                               2985                 :                :                 /* minimum MultiXactId */
 5057 alvherre@alvh.no-ip.     2986         [ +  + ]:            558 :                 if (dbMinMultiP)
                               2987                 :            467 :                     *dbMinMultiP = dbform->datminmxid;
                               2988                 :                :                 /* default tablespace for this database */
 7513 tgl@sss.pgh.pa.us        2989         [ +  + ]:            558 :                 if (dbTablespace)
                               2990                 :            481 :                     *dbTablespace = dbform->dattablespace;
                               2991                 :                :                 /* default locale settings for this database */
 1717 peter@eisentraut.org     2992         [ +  + ]:            558 :                 if (dbLocProvider)
                               2993                 :            467 :                     *dbLocProvider = dbform->datlocprovider;
 6379 bruce@momjian.us         2994         [ +  + ]:            558 :                 if (dbCollate)
                               2995                 :                :                 {
 1344 dgustafsson@postgres     2996                 :            467 :                     datum = SysCacheGetAttrNotNull(DATABASEOID, tuple, Anum_pg_database_datcollate);
 1766 peter@eisentraut.org     2997                 :            467 :                     *dbCollate = TextDatumGetCString(datum);
                               2998                 :                :                 }
 6379 bruce@momjian.us         2999         [ +  + ]:            558 :                 if (dbCtype)
                               3000                 :                :                 {
 1344 dgustafsson@postgres     3001                 :            467 :                     datum = SysCacheGetAttrNotNull(DATABASEOID, tuple, Anum_pg_database_datctype);
 1766 peter@eisentraut.org     3002                 :            467 :                     *dbCtype = TextDatumGetCString(datum);
                               3003                 :                :                 }
  994 jdavis@postgresql.or     3004         [ +  + ]:            558 :                 if (dbLocale)
                               3005                 :                :                 {
                               3006                 :            467 :                     datum = SysCacheGetAttr(DATABASEOID, tuple, Anum_pg_database_datlocale, &isnull);
 1717 peter@eisentraut.org     3007         [ +  + ]:            467 :                     if (isnull)
  994 jdavis@postgresql.or     3008                 :            432 :                         *dbLocale = NULL;
                               3009                 :                :                     else
                               3010                 :             35 :                         *dbLocale = TextDatumGetCString(datum);
                               3011                 :                :                 }
 1361 peter@eisentraut.org     3012         [ +  + ]:            558 :                 if (dbIcurules)
                               3013                 :                :                 {
                               3014                 :            467 :                     datum = SysCacheGetAttr(DATABASEOID, tuple, Anum_pg_database_daticurules, &isnull);
                               3015         [ +  + ]:            467 :                     if (isnull)
                               3016                 :            462 :                         *dbIcurules = NULL;
                               3017                 :                :                     else
                               3018                 :              5 :                         *dbIcurules = TextDatumGetCString(datum);
                               3019                 :                :                 }
 1748                          3020         [ +  + ]:            558 :                 if (dbCollversion)
                               3021                 :                :                 {
                               3022                 :            467 :                     datum = SysCacheGetAttr(DATABASEOID, tuple, Anum_pg_database_datcollversion, &isnull);
                               3023         [ +  + ]:            467 :                     if (isnull)
                               3024                 :            280 :                         *dbCollversion = NULL;
                               3025                 :                :                     else
                               3026                 :            187 :                         *dbCollversion = TextDatumGetCString(datum);
                               3027                 :                :                 }
 7513 tgl@sss.pgh.pa.us        3028                 :            558 :                 ReleaseSysCache(tuple);
                               3029                 :            558 :                 result = true;
                               3030                 :            558 :                 break;
                               3031                 :                :             }
                               3032                 :                :             /* can only get here if it was just renamed */
 7513 tgl@sss.pgh.pa.us        3033                 :UBC           0 :             ReleaseSysCache(tuple);
                               3034                 :                :         }
                               3035                 :                : 
                               3036         [ #  # ]:              0 :         if (lockmode != NoLock)
                               3037                 :              0 :             UnlockSharedObject(DatabaseRelationId, dbOid, 0, lockmode);
                               3038                 :                :     }
                               3039                 :                : 
 2868 andres@anarazel.de       3040                 :CBC         579 :     table_close(relation, AccessShareLock);
                               3041                 :                : 
 7513 tgl@sss.pgh.pa.us        3042                 :            579 :     return result;
                               3043                 :                : }
                               3044                 :                : 
                               3045                 :                : /* Check if current user has createdb privileges */
                               3046                 :                : bool
 4358 alvherre@alvh.no-ip.     3047                 :            539 : have_createdb_privilege(void)
                               3048                 :                : {
                               3049                 :            539 :     bool        result = false;
                               3050                 :                :     HeapTuple   utup;
                               3051                 :                : 
                               3052                 :                :     /* Superusers can always do everything */
                               3053         [ +  + ]:            539 :     if (superuser())
                               3054                 :            503 :         return true;
                               3055                 :                : 
                               3056                 :             36 :     utup = SearchSysCache1(AUTHOID, ObjectIdGetDatum(GetUserId()));
                               3057         [ +  - ]:             36 :     if (HeapTupleIsValid(utup))
                               3058                 :                :     {
                               3059                 :             36 :         result = ((Form_pg_authid) GETSTRUCT(utup))->rolcreatedb;
                               3060                 :             36 :         ReleaseSysCache(utup);
                               3061                 :                :     }
                               3062                 :             36 :     return result;
                               3063                 :                : }
                               3064                 :                : 
                               3065                 :                : /*
                               3066                 :                :  * Remove tablespace directories
                               3067                 :                :  *
                               3068                 :                :  * We don't know what tablespaces db_id is using, so iterate through all
                               3069                 :                :  * tablespaces removing <tablespace>/db_id
                               3070                 :                :  */
                               3071                 :                : static void
 8198 tgl@sss.pgh.pa.us        3072                 :             69 : remove_dbtablespaces(Oid db_id)
                               3073                 :                : {
                               3074                 :                :     Relation    rel;
                               3075                 :                :     TableScanDesc scan;
                               3076                 :                :     HeapTuple   tuple;
 2389                          3077                 :             69 :     List       *ltblspc = NIL;
                               3078                 :                :     ListCell   *cell;
                               3079                 :                :     int         ntblspc;
                               3080                 :                :     int         i;
                               3081                 :                :     Oid        *tablespace_ids;
                               3082                 :                : 
 2868 andres@anarazel.de       3083                 :             69 :     rel = table_open(TableSpaceRelationId, AccessShareLock);
 2819                          3084                 :             69 :     scan = table_beginscan_catalog(rel, 0, NULL);
 8198 tgl@sss.pgh.pa.us        3085         [ +  + ]:            243 :     while ((tuple = heap_getnext(scan, ForwardScanDirection)) != NULL)
                               3086                 :                :     {
 2930 andres@anarazel.de       3087                 :            174 :         Form_pg_tablespace spcform = (Form_pg_tablespace) GETSTRUCT(tuple);
                               3088                 :            174 :         Oid         dsttablespace = spcform->oid;
                               3089                 :                :         char       *dstpath;
                               3090                 :                :         struct stat st;
                               3091                 :                : 
                               3092                 :                :         /* Don't mess with the global tablespace */
 8198 tgl@sss.pgh.pa.us        3093         [ +  + ]:            174 :         if (dsttablespace == GLOBALTABLESPACE_OID)
                               3094                 :            105 :             continue;
                               3095                 :                : 
                               3096                 :            105 :         dstpath = GetDatabasePath(db_id, dsttablespace);
                               3097                 :                : 
 7346                          3098   [ +  +  -  + ]:            105 :         if (lstat(dstpath, &st) < 0 || !S_ISDIR(st.st_mode))
                               3099                 :                :         {
                               3100                 :                :             /* Assume we can ignore it */
 8198                          3101                 :             36 :             pfree(dstpath);
                               3102                 :             36 :             continue;
                               3103                 :                :         }
                               3104                 :                : 
 8154 bruce@momjian.us         3105         [ -  + ]:             69 :         if (!rmtree(dstpath, true))
 8198 tgl@sss.pgh.pa.us        3106         [ #  # ]:UBC           0 :             ereport(WARNING,
                               3107                 :                :                     (errmsg("some useless files may be left behind in old database directory \"%s\"",
                               3108                 :                :                             dstpath)));
                               3109                 :                : 
 2564 fujii@postgresql.org     3110                 :CBC          69 :         ltblspc = lappend_oid(ltblspc, dsttablespace);
                               3111                 :             69 :         pfree(dstpath);
                               3112                 :                :     }
                               3113                 :                : 
                               3114                 :             69 :     ntblspc = list_length(ltblspc);
                               3115         [ +  + ]:             69 :     if (ntblspc == 0)
                               3116                 :                :     {
 2564 fujii@postgresql.org     3117                 :GBC           1 :         table_endscan(scan);
                               3118                 :              1 :         table_close(rel, AccessShareLock);
                               3119                 :              1 :         return;
                               3120                 :                :     }
                               3121                 :                : 
  103 michael@paquier.xyz      3122                 :GNC          68 :     tablespace_ids = palloc_array(Oid, ntblspc);
 2564 fujii@postgresql.org     3123                 :CBC          68 :     i = 0;
                               3124   [ +  -  +  +  :            137 :     foreach(cell, ltblspc)
                                              +  + ]
                               3125                 :             69 :         tablespace_ids[i++] = lfirst_oid(cell);
                               3126                 :                : 
                               3127                 :                :     /* Record the filesystem change in XLOG */
                               3128                 :                :     {
                               3129                 :                :         xl_dbase_drop_rec xlrec;
                               3130                 :                : 
                               3131                 :             68 :         xlrec.db_id = db_id;
                               3132                 :             68 :         xlrec.ntablespaces = ntblspc;
                               3133                 :                : 
                               3134                 :             68 :         XLogBeginInsert();
  655 peter@eisentraut.org     3135                 :             68 :         XLogRegisterData(&xlrec, MinSizeOfDbaseDropRec);
                               3136                 :             68 :         XLogRegisterData(tablespace_ids, ntblspc * sizeof(Oid));
                               3137                 :                : 
 2564 fujii@postgresql.org     3138                 :             68 :         (void) XLogInsert(RM_DBASE_ID,
                               3139                 :                :                           XLOG_DBASE_DROP | XLR_SPECIAL_REL_UPDATE);
                               3140                 :                :     }
                               3141                 :                : 
                               3142                 :             68 :     list_free(ltblspc);
                               3143                 :             68 :     pfree(tablespace_ids);
                               3144                 :                : 
 2819 andres@anarazel.de       3145                 :             68 :     table_endscan(scan);
 2868                          3146                 :             68 :     table_close(rel, AccessShareLock);
                               3147                 :                : }
                               3148                 :                : 
                               3149                 :                : /*
                               3150                 :                :  * Check for existing files that conflict with a proposed new DB OID;
                               3151                 :                :  * return true if there are any
                               3152                 :                :  *
                               3153                 :                :  * If there were a subdirectory in any tablespace matching the proposed new
                               3154                 :                :  * OID, we'd get a create failure due to the duplicate name ... and then we'd
                               3155                 :                :  * try to remove that already-existing subdirectory during the cleanup in
                               3156                 :                :  * remove_dbtablespaces.  Nuking existing files seems like a bad idea, so
                               3157                 :                :  * instead we make this extra check before settling on the OID of the new
                               3158                 :                :  * database.  This exactly parallels what GetNewRelFileNumber() does for table
                               3159                 :                :  * relfilenumber values.
                               3160                 :                :  */
                               3161                 :                : static bool
 7346 tgl@sss.pgh.pa.us        3162                 :            452 : check_db_file_conflict(Oid db_id)
                               3163                 :                : {
                               3164                 :            452 :     bool        result = false;
                               3165                 :                :     Relation    rel;
                               3166                 :                :     TableScanDesc scan;
                               3167                 :                :     HeapTuple   tuple;
                               3168                 :                : 
 2868 andres@anarazel.de       3169                 :            452 :     rel = table_open(TableSpaceRelationId, AccessShareLock);
 2819                          3170                 :            452 :     scan = table_beginscan_catalog(rel, 0, NULL);
 7346 tgl@sss.pgh.pa.us        3171         [ +  + ]:           1428 :     while ((tuple = heap_getnext(scan, ForwardScanDirection)) != NULL)
                               3172                 :                :     {
 2930 andres@anarazel.de       3173                 :            976 :         Form_pg_tablespace spcform = (Form_pg_tablespace) GETSTRUCT(tuple);
                               3174                 :            976 :         Oid         dsttablespace = spcform->oid;
                               3175                 :                :         char       *dstpath;
                               3176                 :                :         struct stat st;
                               3177                 :                : 
                               3178                 :                :         /* Don't mess with the global tablespace */
 7346 tgl@sss.pgh.pa.us        3179         [ +  + ]:            976 :         if (dsttablespace == GLOBALTABLESPACE_OID)
                               3180                 :            452 :             continue;
                               3181                 :                : 
                               3182                 :            524 :         dstpath = GetDatabasePath(db_id, dsttablespace);
                               3183                 :                : 
                               3184         [ -  + ]:            524 :         if (lstat(dstpath, &st) == 0)
                               3185                 :                :         {
                               3186                 :                :             /* Found a conflicting file (or directory, whatever) */
 7346 tgl@sss.pgh.pa.us        3187                 :UBC           0 :             pfree(dstpath);
                               3188                 :              0 :             result = true;
                               3189                 :              0 :             break;
                               3190                 :                :         }
                               3191                 :                : 
 7346 tgl@sss.pgh.pa.us        3192                 :CBC         524 :         pfree(dstpath);
                               3193                 :                :     }
                               3194                 :                : 
 2819 andres@anarazel.de       3195                 :            452 :     table_endscan(scan);
 2868                          3196                 :            452 :     table_close(rel, AccessShareLock);
                               3197                 :                : 
 7346 tgl@sss.pgh.pa.us        3198                 :            452 :     return result;
                               3199                 :                : }
                               3200                 :                : 
                               3201                 :                : /*
                               3202                 :                :  * Issue a suitable errdetail message for a busy database
                               3203                 :                :  */
                               3204                 :                : static int
 6690                          3205                 :              1 : errdetail_busy_db(int notherbackends, int npreparedxacts)
                               3206                 :                : {
                               3207   [ +  -  -  + ]:              1 :     if (notherbackends > 0 && npreparedxacts > 0)
                               3208                 :                : 
                               3209                 :                :         /*
                               3210                 :                :          * We don't deal with singular versus plural here, since gettext
                               3211                 :                :          * doesn't support multiple plurals in one string.
                               3212                 :                :          */
 6690 tgl@sss.pgh.pa.us        3213                 :UBC           0 :         errdetail("There are %d other session(s) and %d prepared transaction(s) using the database.",
                               3214                 :                :                   notherbackends, npreparedxacts);
 6690 tgl@sss.pgh.pa.us        3215         [ +  - ]:CBC           1 :     else if (notherbackends > 0)
 5279 peter_e@gmx.net          3216                 :              1 :         errdetail_plural("There is %d other session using the database.",
                               3217                 :                :                          "There are %d other sessions using the database.",
                               3218                 :                :                          notherbackends,
                               3219                 :                :                          notherbackends);
                               3220                 :                :     else
 5279 peter_e@gmx.net          3221                 :UBC           0 :         errdetail_plural("There is %d prepared transaction using the database.",
                               3222                 :                :                          "There are %d prepared transactions using the database.",
                               3223                 :                :                          npreparedxacts,
                               3224                 :                :                          npreparedxacts);
 6690 tgl@sss.pgh.pa.us        3225                 :CBC           1 :     return 0;                   /* just to keep ereport macro happy */
                               3226                 :                : }
                               3227                 :                : 
                               3228                 :                : /*
                               3229                 :                :  * get_database_oid - given a database name, look up the OID
                               3230                 :                :  *
                               3231                 :                :  * If missing_ok is false, throw an error if database name not found.  If
                               3232                 :                :  * true, just return InvalidOid.
                               3233                 :                :  */
                               3234                 :                : Oid
 5959 rhaas@postgresql.org     3235                 :           1789 : get_database_oid(const char *dbname, bool missing_ok)
                               3236                 :                : {
                               3237                 :                :     Relation    pg_database;
                               3238                 :                :     ScanKeyData entry[1];
                               3239                 :                :     SysScanDesc scan;
                               3240                 :                :     HeapTuple   dbtuple;
                               3241                 :                :     Oid         oid;
                               3242                 :                : 
                               3243                 :                :     /*
                               3244                 :                :      * There's no syscache for pg_database indexed by name, so we must look
                               3245                 :                :      * the hard way.
                               3246                 :                :      */
 2868 andres@anarazel.de       3247                 :           1789 :     pg_database = table_open(DatabaseRelationId, AccessShareLock);
 8417 tgl@sss.pgh.pa.us        3248                 :           1789 :     ScanKeyInit(&entry[0],
                               3249                 :                :                 Anum_pg_database_datname,
                               3250                 :                :                 BTEqualStrategyNumber, F_NAMEEQ,
                               3251                 :                :                 CStringGetDatum(dbname));
 7898                          3252                 :           1789 :     scan = systable_beginscan(pg_database, DatabaseNameIndexId, true,
                               3253                 :                :                               NULL, 1, entry);
                               3254                 :                : 
 8555 peter_e@gmx.net          3255                 :           1789 :     dbtuple = systable_getnext(scan);
                               3256                 :                : 
                               3257                 :                :     /* We assume that there can be at most one matching tuple */
 8877 tgl@sss.pgh.pa.us        3258         [ +  + ]:           1789 :     if (HeapTupleIsValid(dbtuple))
 2747                          3259                 :           1302 :         oid = ((Form_pg_database) GETSTRUCT(dbtuple))->oid;
                               3260                 :                :     else
 8877                          3261                 :            487 :         oid = InvalidOid;
                               3262                 :                : 
 8555 peter_e@gmx.net          3263                 :           1789 :     systable_endscan(scan);
 2868 andres@anarazel.de       3264                 :           1789 :     table_close(pg_database, AccessShareLock);
                               3265                 :                : 
 5959 rhaas@postgresql.org     3266   [ +  +  +  + ]:           1789 :     if (!OidIsValid(oid) && !missing_ok)
 5711 bruce@momjian.us         3267         [ +  - ]:              4 :         ereport(ERROR,
                               3268                 :                :                 (errcode(ERRCODE_UNDEFINED_DATABASE),
                               3269                 :                :                  errmsg("database \"%s\" does not exist",
                               3270                 :                :                         dbname)));
                               3271                 :                : 
 8877 tgl@sss.pgh.pa.us        3272                 :           1785 :     return oid;
                               3273                 :                : }
                               3274                 :                : 
                               3275                 :                : 
                               3276                 :                : /*
                               3277                 :                :  * While dropping a database the pg_database row is marked invalid, but the
                               3278                 :                :  * catalog contents still exist. Connections to such a database are not
                               3279                 :                :  * allowed.
                               3280                 :                :  */
                               3281                 :                : bool
 1234 andres@anarazel.de       3282                 :          22040 : database_is_invalid_form(Form_pg_database datform)
                               3283                 :                : {
                               3284                 :          22040 :     return datform->datconnlimit == DATCONNLIMIT_INVALID_DB;
                               3285                 :                : }
                               3286                 :                : 
                               3287                 :                : 
                               3288                 :                : /*
                               3289                 :                :  * Convenience wrapper around database_is_invalid_form()
                               3290                 :                :  */
                               3291                 :                : bool
                               3292                 :            467 : database_is_invalid_oid(Oid dboid)
                               3293                 :                : {
                               3294                 :                :     HeapTuple   dbtup;
                               3295                 :                :     Form_pg_database dbform;
                               3296                 :                :     bool        invalid;
                               3297                 :                : 
                               3298                 :            467 :     dbtup = SearchSysCache1(DATABASEOID, ObjectIdGetDatum(dboid));
                               3299         [ -  + ]:            467 :     if (!HeapTupleIsValid(dbtup))
 1234 andres@anarazel.de       3300         [ #  # ]:UBC           0 :         elog(ERROR, "cache lookup failed for database %u", dboid);
 1234 andres@anarazel.de       3301                 :CBC         467 :     dbform = (Form_pg_database) GETSTRUCT(dbtup);
                               3302                 :                : 
                               3303                 :            467 :     invalid = database_is_invalid_form(dbform);
                               3304                 :                : 
                               3305                 :            467 :     ReleaseSysCache(dbtup);
                               3306                 :                : 
                               3307                 :            467 :     return invalid;
                               3308                 :                : }
                               3309                 :                : 
                               3310                 :                : 
                               3311                 :                : /*
                               3312                 :                :  * recovery_create_dbdir()
                               3313                 :                :  *
                               3314                 :                :  * During recovery, there's a case where we validly need to recover a missing
                               3315                 :                :  * tablespace directory so that recovery can continue.  This happens when
                               3316                 :                :  * recovery wants to create a database but the holding tablespace has been
                               3317                 :                :  * removed before the server stopped.  Since we expect that the directory will
                               3318                 :                :  * be gone before reaching recovery consistency, and we have no knowledge about
                               3319                 :                :  * the tablespace other than its OID here, we create a real directory under
                               3320                 :                :  * pg_tblspc here instead of restoring the symlink.
                               3321                 :                :  *
                               3322                 :                :  * If only_tblspc is true, then the requested directory must be in pg_tblspc/
                               3323                 :                :  */
                               3324                 :                : static void
 1584 alvherre@alvh.no-ip.     3325                 :             23 : recovery_create_dbdir(char *path, bool only_tblspc)
                               3326                 :                : {
                               3327                 :                :     struct stat st;
                               3328                 :                : 
                               3329         [ -  + ]:             23 :     Assert(RecoveryInProgress());
                               3330                 :                : 
                               3331         [ +  - ]:             23 :     if (stat(path, &st) == 0)
                               3332                 :             23 :         return;
                               3333                 :                : 
  816 michael@paquier.xyz      3334   [ #  #  #  # ]:UBC           0 :     if (only_tblspc && strstr(path, PG_TBLSPC_DIR_SLASH) == NULL)
 1584 alvherre@alvh.no-ip.     3335         [ #  # ]:              0 :         elog(PANIC, "requested to created invalid directory: %s", path);
                               3336                 :                : 
                               3337   [ #  #  #  # ]:              0 :     if (reachedConsistency && !allow_in_place_tablespaces)
                               3338         [ #  # ]:              0 :         ereport(PANIC,
                               3339                 :                :                 errmsg("missing directory \"%s\"", path));
                               3340                 :                : 
                               3341   [ #  #  #  # ]:              0 :     elog(reachedConsistency ? WARNING : DEBUG1,
                               3342                 :                :          "creating missing directory: %s", path);
                               3343                 :                : 
                               3344         [ #  # ]:              0 :     if (pg_mkdir_p(path, pg_dir_create_mode) != 0)
                               3345         [ #  # ]:              0 :         ereport(PANIC,
                               3346                 :                :                 errmsg("could not create missing directory \"%s\": %m", path));
                               3347                 :                : }
                               3348                 :                : 
                               3349                 :                : 
                               3350                 :                : /*
                               3351                 :                :  * DATABASE resource manager's routines
                               3352                 :                :  */
                               3353                 :                : void
 4391 heikki.linnakangas@i     3354                 :CBC          43 : dbase_redo(XLogReaderState *record)
                               3355                 :                : {
                               3356                 :             43 :     uint8       info = XLogRecGetInfo(record) & ~XLR_INFO_MASK;
                               3357                 :                : 
                               3358                 :                :     /* Backup blocks are not used in dbase records */
                               3359         [ -  + ]:             43 :     Assert(!XLogRecHasAnyBlockRefs(record));
                               3360                 :                : 
 1705 rhaas@postgresql.org     3361         [ +  + ]:             43 :     if (info == XLOG_DBASE_CREATE_FILE_COPY)
                               3362                 :                :     {
                               3363                 :              5 :         xl_dbase_create_file_copy_rec *xlrec =
 1289 tgl@sss.pgh.pa.us        3364                 :              5 :             (xl_dbase_create_file_copy_rec *) XLogRecGetData(record);
                               3365                 :                :         char       *src_path;
                               3366                 :                :         char       *dst_path;
                               3367                 :                :         char       *parent_path;
                               3368                 :                :         struct stat st;
                               3369                 :                : 
 7920                          3370                 :              5 :         src_path = GetDatabasePath(xlrec->src_db_id, xlrec->src_tablespace_id);
                               3371                 :              5 :         dst_path = GetDatabasePath(xlrec->db_id, xlrec->tablespace_id);
                               3372                 :                : 
                               3373                 :                :         /*
                               3374                 :                :          * Our theory for replaying a CREATE is to forcibly drop the target
                               3375                 :                :          * subdirectory if present, then re-copy the source data. This may be
                               3376                 :                :          * more work than needed, but it is simple to implement.
                               3377                 :                :          */
                               3378   [ -  +  -  - ]:              5 :         if (stat(dst_path, &st) == 0 && S_ISDIR(st.st_mode))
                               3379                 :                :         {
 7920 tgl@sss.pgh.pa.us        3380         [ #  # ]:UBC           0 :             if (!rmtree(dst_path, true))
                               3381                 :                :                 /* If this failed, copydir() below is going to error. */
                               3382         [ #  # ]:              0 :                 ereport(WARNING,
                               3383                 :                :                         (errmsg("some useless files may be left behind in old database directory \"%s\"",
                               3384                 :                :                                 dst_path)));
                               3385                 :                :         }
                               3386                 :                : 
                               3387                 :                :         /*
                               3388                 :                :          * If the parent of the target path doesn't exist, create it now. This
                               3389                 :                :          * enables us to create the target underneath later.
                               3390                 :                :          */
 1584 alvherre@alvh.no-ip.     3391                 :CBC           5 :         parent_path = pstrdup(dst_path);
                               3392                 :              5 :         get_parent_directory(parent_path);
                               3393         [ -  + ]:              5 :         if (stat(parent_path, &st) < 0)
                               3394                 :                :         {
 1584 alvherre@alvh.no-ip.     3395         [ #  # ]:UBC           0 :             if (errno != ENOENT)
                               3396         [ #  # ]:              0 :                 ereport(FATAL,
                               3397                 :                :                         errmsg("could not stat directory \"%s\": %m",
                               3398                 :                :                                dst_path));
                               3399                 :                : 
                               3400                 :                :             /* create the parent directory if needed and valid */
                               3401                 :              0 :             recovery_create_dbdir(parent_path, true);
                               3402                 :                :         }
 1584 alvherre@alvh.no-ip.     3403                 :CBC           5 :         pfree(parent_path);
                               3404                 :                : 
                               3405                 :                :         /*
                               3406                 :                :          * There's a case where the copy source directory is missing for the
                               3407                 :                :          * same reason above.  Create the empty source directory so that
                               3408                 :                :          * copydir below doesn't fail.  The directory will be dropped soon by
                               3409                 :                :          * recovery.
                               3410                 :                :          */
                               3411   [ -  +  -  - ]:              5 :         if (stat(src_path, &st) < 0 && errno == ENOENT)
 1584 alvherre@alvh.no-ip.     3412                 :UBC           0 :             recovery_create_dbdir(src_path, false);
                               3413                 :                : 
                               3414                 :                :         /*
                               3415                 :                :          * Force dirty buffers out to disk, to ensure source database is
                               3416                 :                :          * up-to-date for the copy.
                               3417                 :                :          */
 7093 tgl@sss.pgh.pa.us        3418                 :CBC           5 :         FlushDatabaseBuffers(xlrec->src_db_id);
                               3419                 :                : 
                               3420                 :                :         /* Close all smgr fds in all backends. */
 1666 tmunro@postgresql.or     3421                 :              5 :         WaitForProcSignalBarrier(EmitProcSignalBarrier(PROCSIGNAL_BARRIER_SMGRRELEASE));
                               3422                 :                : 
                               3423                 :                :         /*
                               3424                 :                :          * Copy this subdirectory to the new location
                               3425                 :                :          *
                               3426                 :                :          * We don't need to copy subdirectories
                               3427                 :                :          */
 7788 tgl@sss.pgh.pa.us        3428                 :              5 :         copydir(src_path, dst_path, false);
                               3429                 :                : 
 1678 alvherre@alvh.no-ip.     3430                 :              5 :         pfree(src_path);
                               3431                 :              5 :         pfree(dst_path);
                               3432                 :                :     }
 1705 rhaas@postgresql.org     3433         [ +  + ]:             38 :     else if (info == XLOG_DBASE_CREATE_WAL_LOG)
                               3434                 :                :     {
                               3435                 :             23 :         xl_dbase_create_wal_log_rec *xlrec =
 1289 tgl@sss.pgh.pa.us        3436                 :             23 :             (xl_dbase_create_wal_log_rec *) XLogRecGetData(record);
                               3437                 :                :         char       *dbpath;
                               3438                 :                :         char       *parent_path;
                               3439                 :                : 
 1705 rhaas@postgresql.org     3440                 :             23 :         dbpath = GetDatabasePath(xlrec->db_id, xlrec->tablespace_id);
                               3441                 :                : 
                               3442                 :                :         /* create the parent directory if needed and valid */
 1584 alvherre@alvh.no-ip.     3443                 :             23 :         parent_path = pstrdup(dbpath);
                               3444                 :             23 :         get_parent_directory(parent_path);
                               3445                 :             23 :         recovery_create_dbdir(parent_path, true);
  413 alvherre@kurilemu.de     3446                 :             23 :         pfree(parent_path);
                               3447                 :                : 
                               3448                 :                :         /* Create the database directory with the version file. */
 1705 rhaas@postgresql.org     3449                 :             23 :         CreateDirAndVersionFile(dbpath, xlrec->db_id, xlrec->tablespace_id,
                               3450                 :                :                                 true);
 1678 alvherre@alvh.no-ip.     3451                 :             23 :         pfree(dbpath);
                               3452                 :                :     }
 7920 tgl@sss.pgh.pa.us        3453         [ +  - ]:             15 :     else if (info == XLOG_DBASE_DROP)
                               3454                 :                :     {
                               3455                 :             15 :         xl_dbase_drop_rec *xlrec = (xl_dbase_drop_rec *) XLogRecGetData(record);
                               3456                 :                :         char       *dst_path;
                               3457                 :                :         int         i;
                               3458                 :                : 
 6188 simon@2ndQuadrant.co     3459         [ +  - ]:             15 :         if (InHotStandby)
                               3460                 :                :         {
                               3461                 :                :             /*
                               3462                 :                :              * Lock database while we resolve conflicts to ensure that
                               3463                 :                :              * InitPostgres() cannot fully re-execute concurrently. This
                               3464                 :                :              * avoids backends re-connecting automatically to same database,
                               3465                 :                :              * which can happen in some cases.
                               3466                 :                :              *
                               3467                 :                :              * This will lock out walsenders trying to connect to db-specific
                               3468                 :                :              * slots for logical decoding too, so it's safe for us to drop
                               3469                 :                :              * slots.
                               3470                 :                :              */
 6160                          3471                 :             15 :             LockSharedObjectForSession(DatabaseRelationId, xlrec->db_id, 0, AccessExclusiveLock);
 6162                          3472                 :             15 :             ResolveRecoveryConflictWithDatabase(xlrec->db_id);
                               3473                 :                :         }
                               3474                 :                : 
                               3475                 :                :         /* Drop any database-specific replication slots */
 3532                          3476                 :             15 :         ReplicationSlotsDropDBSlots(xlrec->db_id);
                               3477                 :                : 
                               3478                 :                :         /* Drop pages for this database that are in the shared buffer cache */
 7549 tgl@sss.pgh.pa.us        3479                 :             15 :         DropDatabaseBuffers(xlrec->db_id);
                               3480                 :                : 
                               3481                 :                :         /* Also, clean out any fsync requests that might be pending in md.c */
 2795 tmunro@postgresql.or     3482                 :             15 :         ForgetDatabaseSyncRequests(xlrec->db_id);
                               3483                 :                : 
                               3484                 :                :         /* Clean out the xlog relcache too */
 7549 tgl@sss.pgh.pa.us        3485                 :             15 :         XLogDropDatabase(xlrec->db_id);
                               3486                 :                : 
                               3487                 :                :         /* Close all smgr fds in all backends. */
 1750 tmunro@postgresql.or     3488                 :             15 :         WaitForProcSignalBarrier(EmitProcSignalBarrier(PROCSIGNAL_BARRIER_SMGRRELEASE));
                               3489                 :                : 
 2564 fujii@postgresql.org     3490         [ +  + ]:             30 :         for (i = 0; i < xlrec->ntablespaces; i++)
                               3491                 :                :         {
                               3492                 :             15 :             dst_path = GetDatabasePath(xlrec->db_id, xlrec->tablespace_ids[i]);
                               3493                 :                : 
                               3494                 :                :             /* And remove the physical files */
                               3495         [ +  + ]:             15 :             if (!rmtree(dst_path, true))
                               3496         [ +  - ]:              1 :                 ereport(WARNING,
                               3497                 :                :                         (errmsg("some useless files may be left behind in old database directory \"%s\"",
                               3498                 :                :                                 dst_path)));
                               3499                 :             15 :             pfree(dst_path);
                               3500                 :                :         }
                               3501                 :                : 
 6160 simon@2ndQuadrant.co     3502         [ +  - ]:             15 :         if (InHotStandby)
                               3503                 :                :         {
                               3504                 :                :             /*
                               3505                 :                :              * Release locks prior to commit. XXX There is a race condition
                               3506                 :                :              * here that may allow backends to reconnect, but the window for
                               3507                 :                :              * this is small because the gap between here and commit is mostly
                               3508                 :                :              * fairly small and it is unlikely that people will be dropping
                               3509                 :                :              * databases that we are trying to connect to anyway.
                               3510                 :                :              */
                               3511                 :             15 :             UnlockSharedObjectForSession(DatabaseRelationId, xlrec->db_id, 0, AccessExclusiveLock);
                               3512                 :                :         }
                               3513                 :                :     }
                               3514                 :                :     else
 8126 tgl@sss.pgh.pa.us        3515         [ #  # ]:UBC           0 :         elog(PANIC, "dbase_redo: unknown op code %u", info);
 8126 tgl@sss.pgh.pa.us        3516                 :CBC          43 : }
        

Generated by: LCOV version 2.0-1