LCOV - code coverage report
Current view: top level - src/backend/commands - extension.c (source / functions) Hit Total Coverage
Test: PostgreSQL 13beta1 Lines: 746 1035 72.1 %
Date: 2020-06-01 09:07:10 Functions: 40 43 93.0 %
Legend: Lines: hit not hit

          Line data    Source code
       1             : /*-------------------------------------------------------------------------
       2             :  *
       3             :  * extension.c
       4             :  *    Commands to manipulate extensions
       5             :  *
       6             :  * Extensions in PostgreSQL allow management of collections of SQL objects.
       7             :  *
       8             :  * All we need internally to manage an extension is an OID so that the
       9             :  * dependent objects can be associated with it.  An extension is created by
      10             :  * populating the pg_extension catalog from a "control" file.
      11             :  * The extension control file is parsed with the same parser we use for
      12             :  * postgresql.conf.  An extension also has an installation script file,
      13             :  * containing SQL commands to create the extension's objects.
      14             :  *
      15             :  * Portions Copyright (c) 1996-2020, PostgreSQL Global Development Group
      16             :  * Portions Copyright (c) 1994, Regents of the University of California
      17             :  *
      18             :  *
      19             :  * IDENTIFICATION
      20             :  *    src/backend/commands/extension.c
      21             :  *
      22             :  *-------------------------------------------------------------------------
      23             :  */
      24             : #include "postgres.h"
      25             : 
      26             : #include <dirent.h>
      27             : #include <limits.h>
      28             : #include <sys/file.h>
      29             : #include <sys/stat.h>
      30             : #include <unistd.h>
      31             : 
      32             : #include "access/genam.h"
      33             : #include "access/htup_details.h"
      34             : #include "access/relation.h"
      35             : #include "access/sysattr.h"
      36             : #include "access/table.h"
      37             : #include "access/xact.h"
      38             : #include "catalog/catalog.h"
      39             : #include "catalog/dependency.h"
      40             : #include "catalog/indexing.h"
      41             : #include "catalog/namespace.h"
      42             : #include "catalog/objectaccess.h"
      43             : #include "catalog/pg_authid.h"
      44             : #include "catalog/pg_collation.h"
      45             : #include "catalog/pg_depend.h"
      46             : #include "catalog/pg_extension.h"
      47             : #include "catalog/pg_namespace.h"
      48             : #include "catalog/pg_type.h"
      49             : #include "commands/alter.h"
      50             : #include "commands/comment.h"
      51             : #include "commands/defrem.h"
      52             : #include "commands/extension.h"
      53             : #include "commands/schemacmds.h"
      54             : #include "funcapi.h"
      55             : #include "mb/pg_wchar.h"
      56             : #include "miscadmin.h"
      57             : #include "nodes/makefuncs.h"
      58             : #include "storage/fd.h"
      59             : #include "tcop/utility.h"
      60             : #include "utils/acl.h"
      61             : #include "utils/builtins.h"
      62             : #include "utils/fmgroids.h"
      63             : #include "utils/lsyscache.h"
      64             : #include "utils/memutils.h"
      65             : #include "utils/rel.h"
      66             : #include "utils/snapmgr.h"
      67             : #include "utils/varlena.h"
      68             : 
      69             : 
      70             : /* Globally visible state variables */
      71             : bool        creating_extension = false;
      72             : Oid         CurrentExtensionObject = InvalidOid;
      73             : 
      74             : /*
      75             :  * Internal data structure to hold the results of parsing a control file
      76             :  */
      77             : typedef struct ExtensionControlFile
      78             : {
      79             :     char       *name;           /* name of the extension */
      80             :     char       *directory;      /* directory for script files */
      81             :     char       *default_version;    /* default install target version, if any */
      82             :     char       *module_pathname;    /* string to substitute for
      83             :                                      * MODULE_PATHNAME */
      84             :     char       *comment;        /* comment, if any */
      85             :     char       *schema;         /* target schema (allowed if !relocatable) */
      86             :     bool        relocatable;    /* is ALTER EXTENSION SET SCHEMA supported? */
      87             :     bool        superuser;      /* must be superuser to install? */
      88             :     bool        trusted;        /* allow becoming superuser on the fly? */
      89             :     int         encoding;       /* encoding of the script file, or -1 */
      90             :     List       *requires;       /* names of prerequisite extensions */
      91             : } ExtensionControlFile;
      92             : 
      93             : /*
      94             :  * Internal data structure for update path information
      95             :  */
      96             : typedef struct ExtensionVersionInfo
      97             : {
      98             :     char       *name;           /* name of the starting version */
      99             :     List       *reachable;      /* List of ExtensionVersionInfo's */
     100             :     bool        installable;    /* does this version have an install script? */
     101             :     /* working state for Dijkstra's algorithm: */
     102             :     bool        distance_known; /* is distance from start known yet? */
     103             :     int         distance;       /* current worst-case distance estimate */
     104             :     struct ExtensionVersionInfo *previous;  /* current best predecessor */
     105             : } ExtensionVersionInfo;
     106             : 
     107             : /* Local functions */
     108             : static List *find_update_path(List *evi_list,
     109             :                               ExtensionVersionInfo *evi_start,
     110             :                               ExtensionVersionInfo *evi_target,
     111             :                               bool reject_indirect,
     112             :                               bool reinitialize);
     113             : static Oid  get_required_extension(char *reqExtensionName,
     114             :                                    char *extensionName,
     115             :                                    char *origSchemaName,
     116             :                                    bool cascade,
     117             :                                    List *parents,
     118             :                                    bool is_create);
     119             : static void get_available_versions_for_extension(ExtensionControlFile *pcontrol,
     120             :                                                  Tuplestorestate *tupstore,
     121             :                                                  TupleDesc tupdesc);
     122             : static Datum convert_requires_to_datum(List *requires);
     123             : static void ApplyExtensionUpdates(Oid extensionOid,
     124             :                                   ExtensionControlFile *pcontrol,
     125             :                                   const char *initialVersion,
     126             :                                   List *updateVersions,
     127             :                                   char *origSchemaName,
     128             :                                   bool cascade,
     129             :                                   bool is_create);
     130             : static char *read_whole_file(const char *filename, int *length);
     131             : 
     132             : 
     133             : /*
     134             :  * get_extension_oid - given an extension name, look up the OID
     135             :  *
     136             :  * If missing_ok is false, throw an error if extension name not found.  If
     137             :  * true, just return InvalidOid.
     138             :  */
     139             : Oid
     140        2436 : get_extension_oid(const char *extname, bool missing_ok)
     141             : {
     142             :     Oid         result;
     143             :     Relation    rel;
     144             :     SysScanDesc scandesc;
     145             :     HeapTuple   tuple;
     146             :     ScanKeyData entry[1];
     147             : 
     148        2436 :     rel = table_open(ExtensionRelationId, AccessShareLock);
     149             : 
     150        2436 :     ScanKeyInit(&entry[0],
     151             :                 Anum_pg_extension_extname,
     152             :                 BTEqualStrategyNumber, F_NAMEEQ,
     153             :                 CStringGetDatum(extname));
     154             : 
     155        2436 :     scandesc = systable_beginscan(rel, ExtensionNameIndexId, true,
     156             :                                   NULL, 1, entry);
     157             : 
     158        2436 :     tuple = systable_getnext(scandesc);
     159             : 
     160             :     /* We assume that there can be at most one matching tuple */
     161        2436 :     if (HeapTupleIsValid(tuple))
     162        1822 :         result = ((Form_pg_extension) GETSTRUCT(tuple))->oid;
     163             :     else
     164         614 :         result = InvalidOid;
     165             : 
     166        2436 :     systable_endscan(scandesc);
     167             : 
     168        2436 :     table_close(rel, AccessShareLock);
     169             : 
     170        2436 :     if (!OidIsValid(result) && !missing_ok)
     171           8 :         ereport(ERROR,
     172             :                 (errcode(ERRCODE_UNDEFINED_OBJECT),
     173             :                  errmsg("extension \"%s\" does not exist",
     174             :                         extname)));
     175             : 
     176        2428 :     return result;
     177             : }
     178             : 
     179             : /*
     180             :  * get_extension_name - given an extension OID, look up the name
     181             :  *
     182             :  * Returns a palloc'd string, or NULL if no such extension.
     183             :  */
     184             : char *
     185          50 : get_extension_name(Oid ext_oid)
     186             : {
     187             :     char       *result;
     188             :     Relation    rel;
     189             :     SysScanDesc scandesc;
     190             :     HeapTuple   tuple;
     191             :     ScanKeyData entry[1];
     192             : 
     193          50 :     rel = table_open(ExtensionRelationId, AccessShareLock);
     194             : 
     195          50 :     ScanKeyInit(&entry[0],
     196             :                 Anum_pg_extension_oid,
     197             :                 BTEqualStrategyNumber, F_OIDEQ,
     198             :                 ObjectIdGetDatum(ext_oid));
     199             : 
     200          50 :     scandesc = systable_beginscan(rel, ExtensionOidIndexId, true,
     201             :                                   NULL, 1, entry);
     202             : 
     203          50 :     tuple = systable_getnext(scandesc);
     204             : 
     205             :     /* We assume that there can be at most one matching tuple */
     206          50 :     if (HeapTupleIsValid(tuple))
     207          50 :         result = pstrdup(NameStr(((Form_pg_extension) GETSTRUCT(tuple))->extname));
     208             :     else
     209           0 :         result = NULL;
     210             : 
     211          50 :     systable_endscan(scandesc);
     212             : 
     213          50 :     table_close(rel, AccessShareLock);
     214             : 
     215          50 :     return result;
     216             : }
     217             : 
     218             : /*
     219             :  * get_extension_schema - given an extension OID, fetch its extnamespace
     220             :  *
     221             :  * Returns InvalidOid if no such extension.
     222             :  */
     223             : static Oid
     224          56 : get_extension_schema(Oid ext_oid)
     225             : {
     226             :     Oid         result;
     227             :     Relation    rel;
     228             :     SysScanDesc scandesc;
     229             :     HeapTuple   tuple;
     230             :     ScanKeyData entry[1];
     231             : 
     232          56 :     rel = table_open(ExtensionRelationId, AccessShareLock);
     233             : 
     234          56 :     ScanKeyInit(&entry[0],
     235             :                 Anum_pg_extension_oid,
     236             :                 BTEqualStrategyNumber, F_OIDEQ,
     237             :                 ObjectIdGetDatum(ext_oid));
     238             : 
     239          56 :     scandesc = systable_beginscan(rel, ExtensionOidIndexId, true,
     240             :                                   NULL, 1, entry);
     241             : 
     242          56 :     tuple = systable_getnext(scandesc);
     243             : 
     244             :     /* We assume that there can be at most one matching tuple */
     245          56 :     if (HeapTupleIsValid(tuple))
     246          56 :         result = ((Form_pg_extension) GETSTRUCT(tuple))->extnamespace;
     247             :     else
     248           0 :         result = InvalidOid;
     249             : 
     250          56 :     systable_endscan(scandesc);
     251             : 
     252          56 :     table_close(rel, AccessShareLock);
     253             : 
     254          56 :     return result;
     255             : }
     256             : 
     257             : /*
     258             :  * Utility functions to check validity of extension and version names
     259             :  */
     260             : static void
     261         590 : check_valid_extension_name(const char *extensionname)
     262             : {
     263         590 :     int         namelen = strlen(extensionname);
     264             : 
     265             :     /*
     266             :      * Disallow empty names (the parser rejects empty identifiers anyway, but
     267             :      * let's check).
     268             :      */
     269         590 :     if (namelen == 0)
     270           0 :         ereport(ERROR,
     271             :                 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
     272             :                  errmsg("invalid extension name: \"%s\"", extensionname),
     273             :                  errdetail("Extension names must not be empty.")));
     274             : 
     275             :     /*
     276             :      * No double dashes, since that would make script filenames ambiguous.
     277             :      */
     278         590 :     if (strstr(extensionname, "--"))
     279           0 :         ereport(ERROR,
     280             :                 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
     281             :                  errmsg("invalid extension name: \"%s\"", extensionname),
     282             :                  errdetail("Extension names must not contain \"--\".")));
     283             : 
     284             :     /*
     285             :      * No leading or trailing dash either.  (We could probably allow this, but
     286             :      * it would require much care in filename parsing and would make filenames
     287             :      * visually if not formally ambiguous.  Since there's no real-world use
     288             :      * case, let's just forbid it.)
     289             :      */
     290         590 :     if (extensionname[0] == '-' || extensionname[namelen - 1] == '-')
     291           0 :         ereport(ERROR,
     292             :                 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
     293             :                  errmsg("invalid extension name: \"%s\"", extensionname),
     294             :                  errdetail("Extension names must not begin or end with \"-\".")));
     295             : 
     296             :     /*
     297             :      * No directory separators either (this is sufficient to prevent ".."
     298             :      * style attacks).
     299             :      */
     300         590 :     if (first_dir_separator(extensionname) != NULL)
     301           0 :         ereport(ERROR,
     302             :                 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
     303             :                  errmsg("invalid extension name: \"%s\"", extensionname),
     304             :                  errdetail("Extension names must not contain directory separator characters.")));
     305         590 : }
     306             : 
     307             : static void
     308         588 : check_valid_version_name(const char *versionname)
     309             : {
     310         588 :     int         namelen = strlen(versionname);
     311             : 
     312             :     /*
     313             :      * Disallow empty names (we could possibly allow this, but there seems
     314             :      * little point).
     315             :      */
     316         588 :     if (namelen == 0)
     317           0 :         ereport(ERROR,
     318             :                 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
     319             :                  errmsg("invalid extension version name: \"%s\"", versionname),
     320             :                  errdetail("Version names must not be empty.")));
     321             : 
     322             :     /*
     323             :      * No double dashes, since that would make script filenames ambiguous.
     324             :      */
     325         588 :     if (strstr(versionname, "--"))
     326           0 :         ereport(ERROR,
     327             :                 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
     328             :                  errmsg("invalid extension version name: \"%s\"", versionname),
     329             :                  errdetail("Version names must not contain \"--\".")));
     330             : 
     331             :     /*
     332             :      * No leading or trailing dash either.
     333             :      */
     334         588 :     if (versionname[0] == '-' || versionname[namelen - 1] == '-')
     335           0 :         ereport(ERROR,
     336             :                 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
     337             :                  errmsg("invalid extension version name: \"%s\"", versionname),
     338             :                  errdetail("Version names must not begin or end with \"-\".")));
     339             : 
     340             :     /*
     341             :      * No directory separators either (this is sufficient to prevent ".."
     342             :      * style attacks).
     343             :      */
     344         588 :     if (first_dir_separator(versionname) != NULL)
     345           0 :         ereport(ERROR,
     346             :                 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
     347             :                  errmsg("invalid extension version name: \"%s\"", versionname),
     348             :                  errdetail("Version names must not contain directory separator characters.")));
     349         588 : }
     350             : 
     351             : /*
     352             :  * Utility functions to handle extension-related path names
     353             :  */
     354             : static bool
     355        2128 : is_extension_control_filename(const char *filename)
     356             : {
     357        2128 :     const char *extension = strrchr(filename, '.');
     358             : 
     359        2128 :     return (extension != NULL) && (strcmp(extension, ".control") == 0);
     360             : }
     361             : 
     362             : static bool
     363      107996 : is_extension_script_filename(const char *filename)
     364             : {
     365      107996 :     const char *extension = strrchr(filename, '.');
     366             : 
     367      107996 :     return (extension != NULL) && (strcmp(extension, ".sql") == 0);
     368             : }
     369             : 
     370             : static char *
     371        2920 : get_extension_control_directory(void)
     372             : {
     373             :     char        sharepath[MAXPGPATH];
     374             :     char       *result;
     375             : 
     376        2920 :     get_share_path(my_exec_path, sharepath);
     377        2920 :     result = (char *) palloc(MAXPGPATH);
     378        2920 :     snprintf(result, MAXPGPATH, "%s/extension", sharepath);
     379             : 
     380        2920 :     return result;
     381             : }
     382             : 
     383             : static char *
     384        1284 : get_extension_control_filename(const char *extname)
     385             : {
     386             :     char        sharepath[MAXPGPATH];
     387             :     char       *result;
     388             : 
     389        1284 :     get_share_path(my_exec_path, sharepath);
     390        1284 :     result = (char *) palloc(MAXPGPATH);
     391        1284 :     snprintf(result, MAXPGPATH, "%s/extension/%s.control",
     392             :              sharepath, extname);
     393             : 
     394        1284 :     return result;
     395             : }
     396             : 
     397             : static char *
     398        2912 : get_extension_script_directory(ExtensionControlFile *control)
     399             : {
     400             :     char        sharepath[MAXPGPATH];
     401             :     char       *result;
     402             : 
     403             :     /*
     404             :      * The directory parameter can be omitted, absolute, or relative to the
     405             :      * installation's share directory.
     406             :      */
     407        2912 :     if (!control->directory)
     408        2912 :         return get_extension_control_directory();
     409             : 
     410           0 :     if (is_absolute_path(control->directory))
     411           0 :         return pstrdup(control->directory);
     412             : 
     413           0 :     get_share_path(my_exec_path, sharepath);
     414           0 :     result = (char *) palloc(MAXPGPATH);
     415           0 :     snprintf(result, MAXPGPATH, "%s/%s", sharepath, control->directory);
     416             : 
     417           0 :     return result;
     418             : }
     419             : 
     420             : static char *
     421        1218 : get_extension_aux_control_filename(ExtensionControlFile *control,
     422             :                                    const char *version)
     423             : {
     424             :     char       *result;
     425             :     char       *scriptdir;
     426             : 
     427        1218 :     scriptdir = get_extension_script_directory(control);
     428             : 
     429        1218 :     result = (char *) palloc(MAXPGPATH);
     430        1218 :     snprintf(result, MAXPGPATH, "%s/%s--%s.control",
     431             :              scriptdir, control->name, version);
     432             : 
     433        1218 :     pfree(scriptdir);
     434             : 
     435        1218 :     return result;
     436             : }
     437             : 
     438             : static char *
     439        1288 : get_extension_script_filename(ExtensionControlFile *control,
     440             :                               const char *from_version, const char *version)
     441             : {
     442             :     char       *result;
     443             :     char       *scriptdir;
     444             : 
     445        1288 :     scriptdir = get_extension_script_directory(control);
     446             : 
     447        1288 :     result = (char *) palloc(MAXPGPATH);
     448        1288 :     if (from_version)
     449         136 :         snprintf(result, MAXPGPATH, "%s/%s--%s--%s.sql",
     450             :                  scriptdir, control->name, from_version, version);
     451             :     else
     452        1152 :         snprintf(result, MAXPGPATH, "%s/%s--%s.sql",
     453             :                  scriptdir, control->name, version);
     454             : 
     455        1288 :     pfree(scriptdir);
     456             : 
     457        1288 :     return result;
     458             : }
     459             : 
     460             : 
     461             : /*
     462             :  * Parse contents of primary or auxiliary control file, and fill in
     463             :  * fields of *control.  We parse primary file if version == NULL,
     464             :  * else the optional auxiliary file for that version.
     465             :  *
     466             :  * Control files are supposed to be very short, half a dozen lines,
     467             :  * so we don't worry about memory allocation risks here.  Also we don't
     468             :  * worry about what encoding it's in; all values are expected to be ASCII.
     469             :  */
     470             : static void
     471        2502 : parse_extension_control_file(ExtensionControlFile *control,
     472             :                              const char *version)
     473             : {
     474             :     char       *filename;
     475             :     FILE       *file;
     476             :     ConfigVariable *item,
     477        2502 :                *head = NULL,
     478        2502 :                *tail = NULL;
     479             : 
     480             :     /*
     481             :      * Locate the file to read.  Auxiliary files are optional.
     482             :      */
     483        2502 :     if (version)
     484        1218 :         filename = get_extension_aux_control_filename(control, version);
     485             :     else
     486        1284 :         filename = get_extension_control_filename(control->name);
     487             : 
     488        2502 :     if ((file = AllocateFile(filename, "r")) == NULL)
     489             :     {
     490        1218 :         if (version && errno == ENOENT)
     491             :         {
     492             :             /* no auxiliary file for this version */
     493        1218 :             pfree(filename);
     494        1218 :             return;
     495             :         }
     496           0 :         ereport(ERROR,
     497             :                 (errcode_for_file_access(),
     498             :                  errmsg("could not open extension control file \"%s\": %m",
     499             :                         filename)));
     500             :     }
     501             : 
     502             :     /*
     503             :      * Parse the file content, using GUC's file parsing code.  We need not
     504             :      * check the return value since any errors will be thrown at ERROR level.
     505             :      */
     506        1284 :     (void) ParseConfigFp(file, filename, 0, ERROR, &head, &tail);
     507             : 
     508        1284 :     FreeFile(file);
     509             : 
     510             :     /*
     511             :      * Convert the ConfigVariable list into ExtensionControlFile entries.
     512             :      */
     513        8132 :     for (item = head; item != NULL; item = item->next)
     514             :     {
     515        6848 :         if (strcmp(item->name, "directory") == 0)
     516             :         {
     517           0 :             if (version)
     518           0 :                 ereport(ERROR,
     519             :                         (errcode(ERRCODE_SYNTAX_ERROR),
     520             :                          errmsg("parameter \"%s\" cannot be set in a secondary extension control file",
     521             :                                 item->name)));
     522             : 
     523           0 :             control->directory = pstrdup(item->value);
     524             :         }
     525        6848 :         else if (strcmp(item->name, "default_version") == 0)
     526             :         {
     527        1284 :             if (version)
     528           0 :                 ereport(ERROR,
     529             :                         (errcode(ERRCODE_SYNTAX_ERROR),
     530             :                          errmsg("parameter \"%s\" cannot be set in a secondary extension control file",
     531             :                                 item->name)));
     532             : 
     533        1284 :             control->default_version = pstrdup(item->value);
     534             :         }
     535        5564 :         else if (strcmp(item->name, "module_pathname") == 0)
     536             :         {
     537        1138 :             control->module_pathname = pstrdup(item->value);
     538             :         }
     539        4426 :         else if (strcmp(item->name, "comment") == 0)
     540             :         {
     541        1284 :             control->comment = pstrdup(item->value);
     542             :         }
     543        3142 :         else if (strcmp(item->name, "schema") == 0)
     544             :         {
     545         522 :             control->schema = pstrdup(item->value);
     546             :         }
     547        2620 :         else if (strcmp(item->name, "relocatable") == 0)
     548             :         {
     549        1284 :             if (!parse_bool(item->value, &control->relocatable))
     550           0 :                 ereport(ERROR,
     551             :                         (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
     552             :                          errmsg("parameter \"%s\" requires a Boolean value",
     553             :                                 item->name)));
     554             :         }
     555        1336 :         else if (strcmp(item->name, "superuser") == 0)
     556             :         {
     557         470 :             if (!parse_bool(item->value, &control->superuser))
     558           0 :                 ereport(ERROR,
     559             :                         (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
     560             :                          errmsg("parameter \"%s\" requires a Boolean value",
     561             :                                 item->name)));
     562             :         }
     563         866 :         else if (strcmp(item->name, "trusted") == 0)
     564             :         {
     565         648 :             if (!parse_bool(item->value, &control->trusted))
     566           0 :                 ereport(ERROR,
     567             :                         (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
     568             :                          errmsg("parameter \"%s\" requires a Boolean value",
     569             :                                 item->name)));
     570             :         }
     571         218 :         else if (strcmp(item->name, "encoding") == 0)
     572             :         {
     573           0 :             control->encoding = pg_valid_server_encoding(item->value);
     574           0 :             if (control->encoding < 0)
     575           0 :                 ereport(ERROR,
     576             :                         (errcode(ERRCODE_UNDEFINED_OBJECT),
     577             :                          errmsg("\"%s\" is not a valid encoding name",
     578             :                                 item->value)));
     579             :         }
     580         218 :         else if (strcmp(item->name, "requires") == 0)
     581             :         {
     582             :             /* Need a modifiable copy of string */
     583         218 :             char       *rawnames = pstrdup(item->value);
     584             : 
     585             :             /* Parse string into list of identifiers */
     586         218 :             if (!SplitIdentifierString(rawnames, ',', &control->requires))
     587             :             {
     588             :                 /* syntax error in name list */
     589           0 :                 ereport(ERROR,
     590             :                         (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
     591             :                          errmsg("parameter \"%s\" must be a list of extension names",
     592             :                                 item->name)));
     593             :             }
     594             :         }
     595             :         else
     596           0 :             ereport(ERROR,
     597             :                     (errcode(ERRCODE_SYNTAX_ERROR),
     598             :                      errmsg("unrecognized parameter \"%s\" in file \"%s\"",
     599             :                             item->name, filename)));
     600             :     }
     601             : 
     602        1284 :     FreeConfigVariables(head);
     603             : 
     604        1284 :     if (control->relocatable && control->schema != NULL)
     605           0 :         ereport(ERROR,
     606             :                 (errcode(ERRCODE_SYNTAX_ERROR),
     607             :                  errmsg("parameter \"schema\" cannot be specified when \"relocatable\" is true")));
     608             : 
     609        1284 :     pfree(filename);
     610             : }
     611             : 
     612             : /*
     613             :  * Read the primary control file for the specified extension.
     614             :  */
     615             : static ExtensionControlFile *
     616        1284 : read_extension_control_file(const char *extname)
     617             : {
     618             :     ExtensionControlFile *control;
     619             : 
     620             :     /*
     621             :      * Set up default values.  Pointer fields are initially null.
     622             :      */
     623        1284 :     control = (ExtensionControlFile *) palloc0(sizeof(ExtensionControlFile));
     624        1284 :     control->name = pstrdup(extname);
     625        1284 :     control->relocatable = false;
     626        1284 :     control->superuser = true;
     627        1284 :     control->trusted = false;
     628        1284 :     control->encoding = -1;
     629             : 
     630             :     /*
     631             :      * Parse the primary control file.
     632             :      */
     633        1284 :     parse_extension_control_file(control, NULL);
     634             : 
     635        1284 :     return control;
     636             : }
     637             : 
     638             : /*
     639             :  * Read the auxiliary control file for the specified extension and version.
     640             :  *
     641             :  * Returns a new modified ExtensionControlFile struct; the original struct
     642             :  * (reflecting just the primary control file) is not modified.
     643             :  */
     644             : static ExtensionControlFile *
     645        1218 : read_extension_aux_control_file(const ExtensionControlFile *pcontrol,
     646             :                                 const char *version)
     647             : {
     648             :     ExtensionControlFile *acontrol;
     649             : 
     650             :     /*
     651             :      * Flat-copy the struct.  Pointer fields share values with original.
     652             :      */
     653        1218 :     acontrol = (ExtensionControlFile *) palloc(sizeof(ExtensionControlFile));
     654        1218 :     memcpy(acontrol, pcontrol, sizeof(ExtensionControlFile));
     655             : 
     656             :     /*
     657             :      * Parse the auxiliary control file, overwriting struct fields
     658             :      */
     659        1218 :     parse_extension_control_file(acontrol, version);
     660             : 
     661        1218 :     return acontrol;
     662             : }
     663             : 
     664             : /*
     665             :  * Read an SQL script file into a string, and convert to database encoding
     666             :  */
     667             : static char *
     668         702 : read_extension_script_file(const ExtensionControlFile *control,
     669             :                            const char *filename)
     670             : {
     671             :     int         src_encoding;
     672             :     char       *src_str;
     673             :     char       *dest_str;
     674             :     int         len;
     675             : 
     676         702 :     src_str = read_whole_file(filename, &len);
     677             : 
     678             :     /* use database encoding if not given */
     679         702 :     if (control->encoding < 0)
     680         702 :         src_encoding = GetDatabaseEncoding();
     681             :     else
     682           0 :         src_encoding = control->encoding;
     683             : 
     684             :     /* make sure that source string is valid in the expected encoding */
     685         702 :     pg_verify_mbstr_len(src_encoding, src_str, len, false);
     686             : 
     687             :     /*
     688             :      * Convert the encoding to the database encoding. read_whole_file
     689             :      * null-terminated the string, so if no conversion happens the string is
     690             :      * valid as is.
     691             :      */
     692         702 :     dest_str = pg_any_to_server(src_str, len, src_encoding);
     693             : 
     694         702 :     return dest_str;
     695             : }
     696             : 
     697             : /*
     698             :  * Execute given SQL string.
     699             :  *
     700             :  * Note: it's tempting to just use SPI to execute the string, but that does
     701             :  * not work very well.  The really serious problem is that SPI will parse,
     702             :  * analyze, and plan the whole string before executing any of it; of course
     703             :  * this fails if there are any plannable statements referring to objects
     704             :  * created earlier in the script.  A lesser annoyance is that SPI insists
     705             :  * on printing the whole string as errcontext in case of any error, and that
     706             :  * could be very long.
     707             :  */
     708             : static void
     709         702 : execute_sql_string(const char *sql)
     710             : {
     711             :     List       *raw_parsetree_list;
     712             :     DestReceiver *dest;
     713             :     ListCell   *lc1;
     714             : 
     715             :     /*
     716             :      * Parse the SQL string into a list of raw parse trees.
     717             :      */
     718         702 :     raw_parsetree_list = pg_parse_query(sql);
     719             : 
     720             :     /* All output from SELECTs goes to the bit bucket */
     721         702 :     dest = CreateDestReceiver(DestNone);
     722             : 
     723             :     /*
     724             :      * Do parse analysis, rule rewrite, planning, and execution for each raw
     725             :      * parsetree.  We must fully execute each query before beginning parse
     726             :      * analysis on the next one, since there may be interdependencies.
     727             :      */
     728        9140 :     foreach(lc1, raw_parsetree_list)
     729             :     {
     730        8438 :         RawStmt    *parsetree = lfirst_node(RawStmt, lc1);
     731             :         MemoryContext per_parsetree_context,
     732             :                     oldcontext;
     733             :         List       *stmt_list;
     734             :         ListCell   *lc2;
     735             : 
     736             :         /*
     737             :          * We do the work for each parsetree in a short-lived context, to
     738             :          * limit the memory used when there are many commands in the string.
     739             :          */
     740             :         per_parsetree_context =
     741        8438 :             AllocSetContextCreate(CurrentMemoryContext,
     742             :                                   "execute_sql_string per-statement context",
     743             :                                   ALLOCSET_DEFAULT_SIZES);
     744        8438 :         oldcontext = MemoryContextSwitchTo(per_parsetree_context);
     745             : 
     746             :         /* Be sure parser can see any DDL done so far */
     747        8438 :         CommandCounterIncrement();
     748             : 
     749        8438 :         stmt_list = pg_analyze_and_rewrite(parsetree,
     750             :                                            sql,
     751             :                                            NULL,
     752             :                                            0,
     753             :                                            NULL);
     754        8438 :         stmt_list = pg_plan_queries(stmt_list, sql, CURSOR_OPT_PARALLEL_OK, NULL);
     755             : 
     756       16876 :         foreach(lc2, stmt_list)
     757             :         {
     758        8438 :             PlannedStmt *stmt = lfirst_node(PlannedStmt, lc2);
     759             : 
     760        8438 :             CommandCounterIncrement();
     761             : 
     762        8438 :             PushActiveSnapshot(GetTransactionSnapshot());
     763             : 
     764        8438 :             if (stmt->utilityStmt == NULL)
     765             :             {
     766             :                 QueryDesc  *qdesc;
     767             : 
     768          22 :                 qdesc = CreateQueryDesc(stmt,
     769             :                                         sql,
     770             :                                         GetActiveSnapshot(), NULL,
     771             :                                         dest, NULL, NULL, 0);
     772             : 
     773          22 :                 ExecutorStart(qdesc, 0);
     774          22 :                 ExecutorRun(qdesc, ForwardScanDirection, 0, true);
     775          22 :                 ExecutorFinish(qdesc);
     776          22 :                 ExecutorEnd(qdesc);
     777             : 
     778          22 :                 FreeQueryDesc(qdesc);
     779             :             }
     780             :             else
     781             :             {
     782        8416 :                 if (IsA(stmt->utilityStmt, TransactionStmt))
     783           0 :                     ereport(ERROR,
     784             :                             (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
     785             :                              errmsg("transaction control statements are not allowed within an extension script")));
     786             : 
     787        8416 :                 ProcessUtility(stmt,
     788             :                                sql,
     789             :                                PROCESS_UTILITY_QUERY,
     790             :                                NULL,
     791             :                                NULL,
     792             :                                dest,
     793             :                                NULL);
     794             :             }
     795             : 
     796        8438 :             PopActiveSnapshot();
     797             :         }
     798             : 
     799             :         /* Clean up per-parsetree context. */
     800        8438 :         MemoryContextSwitchTo(oldcontext);
     801        8438 :         MemoryContextDelete(per_parsetree_context);
     802             :     }
     803             : 
     804             :     /* Be sure to advance the command counter after the last script command */
     805         702 :     CommandCounterIncrement();
     806         702 : }
     807             : 
     808             : /*
     809             :  * Policy function: is the given extension trusted for installation by a
     810             :  * non-superuser?
     811             :  *
     812             :  * (Update the errhint logic below if you change this.)
     813             :  */
     814             : static bool
     815           8 : extension_is_trusted(ExtensionControlFile *control)
     816             : {
     817             :     AclResult   aclresult;
     818             : 
     819             :     /* Never trust unless extension's control file says it's okay */
     820           8 :     if (!control->trusted)
     821           4 :         return false;
     822             :     /* Allow if user has CREATE privilege on current database */
     823           4 :     aclresult = pg_database_aclcheck(MyDatabaseId, GetUserId(), ACL_CREATE);
     824           4 :     if (aclresult == ACLCHECK_OK)
     825           2 :         return true;
     826           2 :     return false;
     827             : }
     828             : 
     829             : /*
     830             :  * Execute the appropriate script file for installing or updating the extension
     831             :  *
     832             :  * If from_version isn't NULL, it's an update
     833             :  */
     834             : static void
     835         708 : execute_extension_script(Oid extensionOid, ExtensionControlFile *control,
     836             :                          const char *from_version,
     837             :                          const char *version,
     838             :                          List *requiredSchemas,
     839             :                          const char *schemaName, Oid schemaOid)
     840             : {
     841         708 :     bool        switch_to_superuser = false;
     842             :     char       *filename;
     843         708 :     Oid         save_userid = 0;
     844         708 :     int         save_sec_context = 0;
     845             :     int         save_nestlevel;
     846             :     StringInfoData pathbuf;
     847             :     ListCell   *lc;
     848             : 
     849             :     /*
     850             :      * Enforce superuser-ness if appropriate.  We postpone these checks until
     851             :      * here so that the control flags are correctly associated with the right
     852             :      * script(s) if they happen to be set in secondary control files.
     853             :      */
     854         708 :     if (control->superuser && !superuser())
     855             :     {
     856           8 :         if (extension_is_trusted(control))
     857           2 :             switch_to_superuser = true;
     858           6 :         else if (from_version == NULL)
     859           6 :             ereport(ERROR,
     860             :                     (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
     861             :                      errmsg("permission denied to create extension \"%s\"",
     862             :                             control->name),
     863             :                      control->trusted
     864             :                      ? errhint("Must have CREATE privilege on current database to create this extension.")
     865             :                      : errhint("Must be superuser to create this extension.")));
     866             :         else
     867           0 :             ereport(ERROR,
     868             :                     (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
     869             :                      errmsg("permission denied to update extension \"%s\"",
     870             :                             control->name),
     871             :                      control->trusted
     872             :                      ? errhint("Must have CREATE privilege on current database to update this extension.")
     873             :                      : errhint("Must be superuser to update this extension.")));
     874             :     }
     875             : 
     876         702 :     filename = get_extension_script_filename(control, from_version, version);
     877             : 
     878             :     /*
     879             :      * If installing a trusted extension on behalf of a non-superuser, become
     880             :      * the bootstrap superuser.  (This switch will be cleaned up automatically
     881             :      * if the transaction aborts, as will the GUC changes below.)
     882             :      */
     883         702 :     if (switch_to_superuser)
     884             :     {
     885           2 :         GetUserIdAndSecContext(&save_userid, &save_sec_context);
     886           2 :         SetUserIdAndSecContext(BOOTSTRAP_SUPERUSERID,
     887             :                                save_sec_context | SECURITY_LOCAL_USERID_CHANGE);
     888             :     }
     889             : 
     890             :     /*
     891             :      * Force client_min_messages and log_min_messages to be at least WARNING,
     892             :      * so that we won't spam the user with useless NOTICE messages from common
     893             :      * script actions like creating shell types.
     894             :      *
     895             :      * We use the equivalent of a function SET option to allow the setting to
     896             :      * persist for exactly the duration of the script execution.  guc.c also
     897             :      * takes care of undoing the setting on error.
     898             :      */
     899         702 :     save_nestlevel = NewGUCNestLevel();
     900             : 
     901         702 :     if (client_min_messages < WARNING)
     902         698 :         (void) set_config_option("client_min_messages", "warning",
     903             :                                  PGC_USERSET, PGC_S_SESSION,
     904             :                                  GUC_ACTION_SAVE, true, 0, false);
     905         702 :     if (log_min_messages < WARNING)
     906           0 :         (void) set_config_option("log_min_messages", "warning",
     907             :                                  PGC_SUSET, PGC_S_SESSION,
     908             :                                  GUC_ACTION_SAVE, true, 0, false);
     909             : 
     910             :     /*
     911             :      * Set up the search path to contain the target schema, then the schemas
     912             :      * of any prerequisite extensions, and nothing else.  In particular this
     913             :      * makes the target schema be the default creation target namespace.
     914             :      *
     915             :      * Note: it might look tempting to use PushOverrideSearchPath for this,
     916             :      * but we cannot do that.  We have to actually set the search_path GUC in
     917             :      * case the extension script examines or changes it.  In any case, the
     918             :      * GUC_ACTION_SAVE method is just as convenient.
     919             :      */
     920         702 :     initStringInfo(&pathbuf);
     921         702 :     appendStringInfoString(&pathbuf, quote_identifier(schemaName));
     922         756 :     foreach(lc, requiredSchemas)
     923             :     {
     924          54 :         Oid         reqschema = lfirst_oid(lc);
     925          54 :         char       *reqname = get_namespace_name(reqschema);
     926             : 
     927          54 :         if (reqname)
     928          54 :             appendStringInfo(&pathbuf, ", %s", quote_identifier(reqname));
     929             :     }
     930             : 
     931         702 :     (void) set_config_option("search_path", pathbuf.data,
     932             :                              PGC_USERSET, PGC_S_SESSION,
     933             :                              GUC_ACTION_SAVE, true, 0, false);
     934             : 
     935             :     /*
     936             :      * Set creating_extension and related variables so that
     937             :      * recordDependencyOnCurrentExtension and other functions do the right
     938             :      * things.  On failure, ensure we reset these variables.
     939             :      */
     940         702 :     creating_extension = true;
     941         702 :     CurrentExtensionObject = extensionOid;
     942         702 :     PG_TRY();
     943             :     {
     944         702 :         char       *c_sql = read_extension_script_file(control, filename);
     945             :         Datum       t_sql;
     946             : 
     947             :         /* We use various functions that want to operate on text datums */
     948         702 :         t_sql = CStringGetTextDatum(c_sql);
     949             : 
     950             :         /*
     951             :          * Reduce any lines beginning with "\echo" to empty.  This allows
     952             :          * scripts to contain messages telling people not to run them via
     953             :          * psql, which has been found to be necessary due to old habits.
     954             :          */
     955        2808 :         t_sql = DirectFunctionCall4Coll(textregexreplace,
     956             :                                         C_COLLATION_OID,
     957             :                                         t_sql,
     958         702 :                                         CStringGetTextDatum("^\\\\echo.*$"),
     959         702 :                                         CStringGetTextDatum(""),
     960         702 :                                         CStringGetTextDatum("ng"));
     961             : 
     962             :         /*
     963             :          * If the script uses @extowner@, substitute the calling username.
     964             :          */
     965         702 :         if (strstr(c_sql, "@extowner@"))
     966             :         {
     967         372 :             Oid         uid = switch_to_superuser ? save_userid : GetUserId();
     968         372 :             const char *userName = GetUserNameFromId(uid, false);
     969         372 :             const char *qUserName = quote_identifier(userName);
     970             : 
     971         372 :             t_sql = DirectFunctionCall3Coll(replace_text,
     972             :                                             C_COLLATION_OID,
     973             :                                             t_sql,
     974         372 :                                             CStringGetTextDatum("@extowner@"),
     975         372 :                                             CStringGetTextDatum(qUserName));
     976             :         }
     977             : 
     978             :         /*
     979             :          * If it's not relocatable, substitute the target schema name for
     980             :          * occurrences of @extschema@.
     981             :          *
     982             :          * For a relocatable extension, we needn't do this.  There cannot be
     983             :          * any need for @extschema@, else it wouldn't be relocatable.
     984             :          */
     985         702 :         if (!control->relocatable)
     986             :         {
     987         420 :             const char *qSchemaName = quote_identifier(schemaName);
     988             : 
     989         420 :             t_sql = DirectFunctionCall3Coll(replace_text,
     990             :                                             C_COLLATION_OID,
     991             :                                             t_sql,
     992         420 :                                             CStringGetTextDatum("@extschema@"),
     993         420 :                                             CStringGetTextDatum(qSchemaName));
     994             :         }
     995             : 
     996             :         /*
     997             :          * If module_pathname was set in the control file, substitute its
     998             :          * value for occurrences of MODULE_PATHNAME.
     999             :          */
    1000         702 :         if (control->module_pathname)
    1001             :         {
    1002         664 :             t_sql = DirectFunctionCall3Coll(replace_text,
    1003             :                                             C_COLLATION_OID,
    1004             :                                             t_sql,
    1005         664 :                                             CStringGetTextDatum("MODULE_PATHNAME"),
    1006         664 :                                             CStringGetTextDatum(control->module_pathname));
    1007             :         }
    1008             : 
    1009             :         /* And now back to C string */
    1010         702 :         c_sql = text_to_cstring(DatumGetTextPP(t_sql));
    1011             : 
    1012         702 :         execute_sql_string(c_sql);
    1013             :     }
    1014           0 :     PG_FINALLY();
    1015             :     {
    1016         702 :         creating_extension = false;
    1017         702 :         CurrentExtensionObject = InvalidOid;
    1018             :     }
    1019         702 :     PG_END_TRY();
    1020             : 
    1021             :     /*
    1022             :      * Restore the GUC variables we set above.
    1023             :      */
    1024         702 :     AtEOXact_GUC(true, save_nestlevel);
    1025             : 
    1026             :     /*
    1027             :      * Restore authentication state if needed.
    1028             :      */
    1029         702 :     if (switch_to_superuser)
    1030           2 :         SetUserIdAndSecContext(save_userid, save_sec_context);
    1031         702 : }
    1032             : 
    1033             : /*
    1034             :  * Find or create an ExtensionVersionInfo for the specified version name
    1035             :  *
    1036             :  * Currently, we just use a List of the ExtensionVersionInfo's.  Searching
    1037             :  * for them therefore uses about O(N^2) time when there are N versions of
    1038             :  * the extension.  We could change the data structure to a hash table if
    1039             :  * this ever becomes a bottleneck.
    1040             :  */
    1041             : static ExtensionVersionInfo *
    1042        1770 : get_ext_ver_info(const char *versionname, List **evi_list)
    1043             : {
    1044             :     ExtensionVersionInfo *evi;
    1045             :     ListCell   *lc;
    1046             : 
    1047        5572 :     foreach(lc, *evi_list)
    1048             :     {
    1049        4516 :         evi = (ExtensionVersionInfo *) lfirst(lc);
    1050        4516 :         if (strcmp(evi->name, versionname) == 0)
    1051         714 :             return evi;
    1052             :     }
    1053             : 
    1054        1056 :     evi = (ExtensionVersionInfo *) palloc(sizeof(ExtensionVersionInfo));
    1055        1056 :     evi->name = pstrdup(versionname);
    1056        1056 :     evi->reachable = NIL;
    1057        1056 :     evi->installable = false;
    1058             :     /* initialize for later application of Dijkstra's algorithm */
    1059        1056 :     evi->distance_known = false;
    1060        1056 :     evi->distance = INT_MAX;
    1061        1056 :     evi->previous = NULL;
    1062             : 
    1063        1056 :     *evi_list = lappend(*evi_list, evi);
    1064             : 
    1065        1056 :     return evi;
    1066             : }
    1067             : 
    1068             : /*
    1069             :  * Locate the nearest unprocessed ExtensionVersionInfo
    1070             :  *
    1071             :  * This part of the algorithm is also about O(N^2).  A priority queue would
    1072             :  * make it much faster, but for now there's no need.
    1073             :  */
    1074             : static ExtensionVersionInfo *
    1075        1354 : get_nearest_unprocessed_vertex(List *evi_list)
    1076             : {
    1077        1354 :     ExtensionVersionInfo *evi = NULL;
    1078             :     ListCell   *lc;
    1079             : 
    1080        9584 :     foreach(lc, evi_list)
    1081             :     {
    1082        8230 :         ExtensionVersionInfo *evi2 = (ExtensionVersionInfo *) lfirst(lc);
    1083             : 
    1084             :         /* only vertices whose distance is still uncertain are candidates */
    1085        8230 :         if (evi2->distance_known)
    1086        1784 :             continue;
    1087             :         /* remember the closest such vertex */
    1088        6446 :         if (evi == NULL ||
    1089        5092 :             evi->distance > evi2->distance)
    1090        2196 :             evi = evi2;
    1091             :     }
    1092             : 
    1093        1354 :     return evi;
    1094             : }
    1095             : 
    1096             : /*
    1097             :  * Obtain information about the set of update scripts available for the
    1098             :  * specified extension.  The result is a List of ExtensionVersionInfo
    1099             :  * structs, each with a subsidiary list of the ExtensionVersionInfos for
    1100             :  * the versions that can be reached in one step from that version.
    1101             :  */
    1102             : static List *
    1103         406 : get_ext_ver_list(ExtensionControlFile *control)
    1104             : {
    1105         406 :     List       *evi_list = NIL;
    1106         406 :     int         extnamelen = strlen(control->name);
    1107             :     char       *location;
    1108             :     DIR        *dir;
    1109             :     struct dirent *de;
    1110             : 
    1111         406 :     location = get_extension_script_directory(control);
    1112         406 :     dir = AllocateDir(location);
    1113      108402 :     while ((de = ReadDir(dir, location)) != NULL)
    1114             :     {
    1115             :         char       *vername;
    1116             :         char       *vername2;
    1117             :         ExtensionVersionInfo *evi;
    1118             :         ExtensionVersionInfo *evi2;
    1119             : 
    1120             :         /* must be a .sql file ... */
    1121      107996 :         if (!is_extension_script_filename(de->d_name))
    1122       36134 :             continue;
    1123             : 
    1124             :         /* ... matching extension name followed by separator */
    1125       71862 :         if (strncmp(de->d_name, control->name, extnamelen) != 0 ||
    1126        1190 :             de->d_name[extnamelen] != '-' ||
    1127        1056 :             de->d_name[extnamelen + 1] != '-')
    1128       70806 :             continue;
    1129             : 
    1130             :         /* extract version name(s) from 'extname--something.sql' filename */
    1131        1056 :         vername = pstrdup(de->d_name + extnamelen + 2);
    1132        1056 :         *strrchr(vername, '.') = '\0';
    1133        1056 :         vername2 = strstr(vername, "--");
    1134        1056 :         if (!vername2)
    1135             :         {
    1136             :             /* It's an install, not update, script; record its version name */
    1137         402 :             evi = get_ext_ver_info(vername, &evi_list);
    1138         402 :             evi->installable = true;
    1139         402 :             continue;
    1140             :         }
    1141         654 :         *vername2 = '\0';       /* terminate first version */
    1142         654 :         vername2 += 2;          /* and point to second */
    1143             : 
    1144             :         /* if there's a third --, it's bogus, ignore it */
    1145         654 :         if (strstr(vername2, "--"))
    1146           0 :             continue;
    1147             : 
    1148             :         /* Create ExtensionVersionInfos and link them together */
    1149         654 :         evi = get_ext_ver_info(vername, &evi_list);
    1150         654 :         evi2 = get_ext_ver_info(vername2, &evi_list);
    1151         654 :         evi->reachable = lappend(evi->reachable, evi2);
    1152             :     }
    1153         406 :     FreeDir(dir);
    1154             : 
    1155         406 :     return evi_list;
    1156             : }
    1157             : 
    1158             : /*
    1159             :  * Given an initial and final version name, identify the sequence of update
    1160             :  * scripts that have to be applied to perform that update.
    1161             :  *
    1162             :  * Result is a List of names of versions to transition through (the initial
    1163             :  * version is *not* included).
    1164             :  */
    1165             : static List *
    1166           2 : identify_update_path(ExtensionControlFile *control,
    1167             :                      const char *oldVersion, const char *newVersion)
    1168             : {
    1169             :     List       *result;
    1170             :     List       *evi_list;
    1171             :     ExtensionVersionInfo *evi_start;
    1172             :     ExtensionVersionInfo *evi_target;
    1173             : 
    1174             :     /* Extract the version update graph from the script directory */
    1175           2 :     evi_list = get_ext_ver_list(control);
    1176             : 
    1177             :     /* Initialize start and end vertices */
    1178           2 :     evi_start = get_ext_ver_info(oldVersion, &evi_list);
    1179           2 :     evi_target = get_ext_ver_info(newVersion, &evi_list);
    1180             : 
    1181             :     /* Find shortest path */
    1182           2 :     result = find_update_path(evi_list, evi_start, evi_target, false, false);
    1183             : 
    1184           2 :     if (result == NIL)
    1185           0 :         ereport(ERROR,
    1186             :                 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
    1187             :                  errmsg("extension \"%s\" has no update path from version \"%s\" to version \"%s\"",
    1188             :                         control->name, oldVersion, newVersion)));
    1189             : 
    1190           2 :     return result;
    1191             : }
    1192             : 
    1193             : /*
    1194             :  * Apply Dijkstra's algorithm to find the shortest path from evi_start to
    1195             :  * evi_target.
    1196             :  *
    1197             :  * If reject_indirect is true, ignore paths that go through installable
    1198             :  * versions.  This saves work when the caller will consider starting from
    1199             :  * all installable versions anyway.
    1200             :  *
    1201             :  * If reinitialize is false, assume the ExtensionVersionInfo list has not
    1202             :  * been used for this before, and the initialization done by get_ext_ver_info
    1203             :  * is still good.  Otherwise, reinitialize all transient fields used here.
    1204             :  *
    1205             :  * Result is a List of names of versions to transition through (the initial
    1206             :  * version is *not* included).  Returns NIL if no such path.
    1207             :  */
    1208             : static List *
    1209         422 : find_update_path(List *evi_list,
    1210             :                  ExtensionVersionInfo *evi_start,
    1211             :                  ExtensionVersionInfo *evi_target,
    1212             :                  bool reject_indirect,
    1213             :                  bool reinitialize)
    1214             : {
    1215             :     List       *result;
    1216             :     ExtensionVersionInfo *evi;
    1217             :     ListCell   *lc;
    1218             : 
    1219             :     /* Caller error if start == target */
    1220             :     Assert(evi_start != evi_target);
    1221             :     /* Caller error if reject_indirect and target is installable */
    1222             :     Assert(!(reject_indirect && evi_target->installable));
    1223             : 
    1224         422 :     if (reinitialize)
    1225             :     {
    1226        2732 :         foreach(lc, evi_list)
    1227             :         {
    1228        2312 :             evi = (ExtensionVersionInfo *) lfirst(lc);
    1229        2312 :             evi->distance_known = false;
    1230        2312 :             evi->distance = INT_MAX;
    1231        2312 :             evi->previous = NULL;
    1232             :         }
    1233             :     }
    1234             : 
    1235         422 :     evi_start->distance = 0;
    1236             : 
    1237        1354 :     while ((evi = get_nearest_unprocessed_vertex(evi_list)) != NULL)
    1238             :     {
    1239        1354 :         if (evi->distance == INT_MAX)
    1240         212 :             break;              /* all remaining vertices are unreachable */
    1241        1142 :         evi->distance_known = true;
    1242        1142 :         if (evi == evi_target)
    1243         210 :             break;              /* found shortest path to target */
    1244        1652 :         foreach(lc, evi->reachable)
    1245             :         {
    1246         720 :             ExtensionVersionInfo *evi2 = (ExtensionVersionInfo *) lfirst(lc);
    1247             :             int         newdist;
    1248             : 
    1249             :             /* if reject_indirect, treat installable versions as unreachable */
    1250         720 :             if (reject_indirect && evi2->installable)
    1251           0 :                 continue;
    1252         720 :             newdist = evi->distance + 1;
    1253         720 :             if (newdist < evi2->distance)
    1254             :             {
    1255         720 :                 evi2->distance = newdist;
    1256         720 :                 evi2->previous = evi;
    1257             :             }
    1258           0 :             else if (newdist == evi2->distance &&
    1259           0 :                      evi2->previous != NULL &&
    1260           0 :                      strcmp(evi->name, evi2->previous->name) < 0)
    1261             :             {
    1262             :                 /*
    1263             :                  * Break ties in favor of the version name that comes first
    1264             :                  * according to strcmp().  This behavior is undocumented and
    1265             :                  * users shouldn't rely on it.  We do it just to ensure that
    1266             :                  * if there is a tie, the update path that is chosen does not
    1267             :                  * depend on random factors like the order in which directory
    1268             :                  * entries get visited.
    1269             :                  */
    1270           0 :                 evi2->previous = evi;
    1271             :             }
    1272             :         }
    1273             :     }
    1274             : 
    1275             :     /* Return NIL if target is not reachable from start */
    1276         422 :     if (!evi_target->distance_known)
    1277         212 :         return NIL;
    1278             : 
    1279             :     /* Build and return list of version names representing the update path */
    1280         210 :     result = NIL;
    1281         602 :     for (evi = evi_target; evi != evi_start; evi = evi->previous)
    1282         392 :         result = lcons(evi->name, result);
    1283             : 
    1284         210 :     return result;
    1285             : }
    1286             : 
    1287             : /*
    1288             :  * Given a target version that is not directly installable, find the
    1289             :  * best installation sequence starting from a directly-installable version.
    1290             :  *
    1291             :  * evi_list: previously-collected version update graph
    1292             :  * evi_target: member of that list that we want to reach
    1293             :  *
    1294             :  * Returns the best starting-point version, or NULL if there is none.
    1295             :  * On success, *best_path is set to the path from the start point.
    1296             :  *
    1297             :  * If there's more than one possible start point, prefer shorter update paths,
    1298             :  * and break any ties arbitrarily on the basis of strcmp'ing the starting
    1299             :  * versions' names.
    1300             :  */
    1301             : static ExtensionVersionInfo *
    1302         420 : find_install_path(List *evi_list, ExtensionVersionInfo *evi_target,
    1303             :                   List **best_path)
    1304             : {
    1305         420 :     ExtensionVersionInfo *evi_start = NULL;
    1306             :     ListCell   *lc;
    1307             : 
    1308         420 :     *best_path = NIL;
    1309             : 
    1310             :     /*
    1311             :      * We don't expect to be called for an installable target, but if we are,
    1312             :      * the answer is easy: just start from there, with an empty update path.
    1313             :      */
    1314         420 :     if (evi_target->installable)
    1315           0 :         return evi_target;
    1316             : 
    1317             :     /* Consider all installable versions as start points */
    1318        2732 :     foreach(lc, evi_list)
    1319             :     {
    1320        2312 :         ExtensionVersionInfo *evi1 = (ExtensionVersionInfo *) lfirst(lc);
    1321             :         List       *path;
    1322             : 
    1323        2312 :         if (!evi1->installable)
    1324        1892 :             continue;
    1325             : 
    1326             :         /*
    1327             :          * Find shortest path from evi1 to evi_target; but no need to consider
    1328             :          * paths going through other installable versions.
    1329             :          */
    1330         420 :         path = find_update_path(evi_list, evi1, evi_target, true, true);
    1331         420 :         if (path == NIL)
    1332         212 :             continue;
    1333             : 
    1334             :         /* Remember best path */
    1335         208 :         if (evi_start == NULL ||
    1336           0 :             list_length(path) < list_length(*best_path) ||
    1337           0 :             (list_length(path) == list_length(*best_path) &&
    1338           0 :              strcmp(evi_start->name, evi1->name) < 0))
    1339             :         {
    1340         208 :             evi_start = evi1;
    1341         208 :             *best_path = path;
    1342             :         }
    1343             :     }
    1344             : 
    1345         420 :     return evi_start;
    1346             : }
    1347             : 
    1348             : /*
    1349             :  * CREATE EXTENSION worker
    1350             :  *
    1351             :  * When CASCADE is specified, CreateExtensionInternal() recurses if required
    1352             :  * extensions need to be installed.  To sanely handle cyclic dependencies,
    1353             :  * the "parents" list contains a list of names of extensions already being
    1354             :  * installed, allowing us to error out if we recurse to one of those.
    1355             :  */
    1356             : static ObjectAddress
    1357         586 : CreateExtensionInternal(char *extensionName,
    1358             :                         char *schemaName,
    1359             :                         const char *versionName,
    1360             :                         bool cascade,
    1361             :                         List *parents,
    1362             :                         bool is_create)
    1363             : {
    1364         586 :     char       *origSchemaName = schemaName;
    1365         586 :     Oid         schemaOid = InvalidOid;
    1366         586 :     Oid         extowner = GetUserId();
    1367             :     ExtensionControlFile *pcontrol;
    1368             :     ExtensionControlFile *control;
    1369             :     char       *filename;
    1370             :     struct stat fst;
    1371             :     List       *updateVersions;
    1372             :     List       *requiredExtensions;
    1373             :     List       *requiredSchemas;
    1374             :     Oid         extensionOid;
    1375             :     ObjectAddress address;
    1376             :     ListCell   *lc;
    1377             : 
    1378             :     /*
    1379             :      * Read the primary control file.  Note we assume that it does not contain
    1380             :      * any non-ASCII data, so there is no need to worry about encoding at this
    1381             :      * point.
    1382             :      */
    1383         586 :     pcontrol = read_extension_control_file(extensionName);
    1384             : 
    1385             :     /*
    1386             :      * Determine the version to install
    1387             :      */
    1388         586 :     if (versionName == NULL)
    1389             :     {
    1390         586 :         if (pcontrol->default_version)
    1391         586 :             versionName = pcontrol->default_version;
    1392             :         else
    1393           0 :             ereport(ERROR,
    1394             :                     (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
    1395             :                      errmsg("version to install must be specified")));
    1396             :     }
    1397         586 :     check_valid_version_name(versionName);
    1398             : 
    1399             :     /*
    1400             :      * Figure out which script(s) we need to run to install the desired
    1401             :      * version of the extension.  If we do not have a script that directly
    1402             :      * does what is needed, we try to find a sequence of update scripts that
    1403             :      * will get us there.
    1404             :      */
    1405         586 :     filename = get_extension_script_filename(pcontrol, NULL, versionName);
    1406         586 :     if (stat(filename, &fst) == 0)
    1407             :     {
    1408             :         /* Easy, no extra scripts */
    1409         530 :         updateVersions = NIL;
    1410             :     }
    1411             :     else
    1412             :     {
    1413             :         /* Look for best way to install this version */
    1414             :         List       *evi_list;
    1415             :         ExtensionVersionInfo *evi_start;
    1416             :         ExtensionVersionInfo *evi_target;
    1417             : 
    1418             :         /* Extract the version update graph from the script directory */
    1419          56 :         evi_list = get_ext_ver_list(pcontrol);
    1420             : 
    1421             :         /* Identify the target version */
    1422          56 :         evi_target = get_ext_ver_info(versionName, &evi_list);
    1423             : 
    1424             :         /* Identify best path to reach target */
    1425          56 :         evi_start = find_install_path(evi_list, evi_target,
    1426             :                                       &updateVersions);
    1427             : 
    1428             :         /* Fail if no path ... */
    1429          56 :         if (evi_start == NULL)
    1430           0 :             ereport(ERROR,
    1431             :                     (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
    1432             :                      errmsg("extension \"%s\" has no installation script nor update path for version \"%s\"",
    1433             :                             pcontrol->name, versionName)));
    1434             : 
    1435             :         /* Otherwise, install best starting point and then upgrade */
    1436          56 :         versionName = evi_start->name;
    1437             :     }
    1438             : 
    1439             :     /*
    1440             :      * Fetch control parameters for installation target version
    1441             :      */
    1442         586 :     control = read_extension_aux_control_file(pcontrol, versionName);
    1443             : 
    1444             :     /*
    1445             :      * Determine the target schema to install the extension into
    1446             :      */
    1447         586 :     if (schemaName)
    1448             :     {
    1449             :         /* If the user is giving us the schema name, it must exist already. */
    1450          34 :         schemaOid = get_namespace_oid(schemaName, false);
    1451             :     }
    1452             : 
    1453         582 :     if (control->schema != NULL)
    1454             :     {
    1455             :         /*
    1456             :          * The extension is not relocatable and the author gave us a schema
    1457             :          * for it.
    1458             :          *
    1459             :          * Unless CASCADE parameter was given, it's an error to give a schema
    1460             :          * different from control->schema if control->schema is specified.
    1461             :          */
    1462         420 :         if (schemaName && strcmp(control->schema, schemaName) != 0 &&
    1463           4 :             !cascade)
    1464           2 :             ereport(ERROR,
    1465             :                     (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
    1466             :                      errmsg("extension \"%s\" must be installed in schema \"%s\"",
    1467             :                             control->name,
    1468             :                             control->schema)));
    1469             : 
    1470             :         /* Always use the schema from control file for current extension. */
    1471         418 :         schemaName = control->schema;
    1472             : 
    1473             :         /* Find or create the schema in case it does not exist. */
    1474         418 :         schemaOid = get_namespace_oid(schemaName, true);
    1475             : 
    1476         418 :         if (!OidIsValid(schemaOid))
    1477             :         {
    1478           6 :             CreateSchemaStmt *csstmt = makeNode(CreateSchemaStmt);
    1479             : 
    1480           6 :             csstmt->schemaname = schemaName;
    1481           6 :             csstmt->authrole = NULL; /* will be created by current user */
    1482           6 :             csstmt->schemaElts = NIL;
    1483           6 :             csstmt->if_not_exists = false;
    1484           6 :             CreateSchemaCommand(csstmt, "(generated CREATE SCHEMA command)",
    1485             :                                 -1, -1);
    1486             : 
    1487             :             /*
    1488             :              * CreateSchemaCommand includes CommandCounterIncrement, so new
    1489             :              * schema is now visible.
    1490             :              */
    1491           6 :             schemaOid = get_namespace_oid(schemaName, false);
    1492             :         }
    1493             :     }
    1494         162 :     else if (!OidIsValid(schemaOid))
    1495             :     {
    1496             :         /*
    1497             :          * Neither user nor author of the extension specified schema; use the
    1498             :          * current default creation namespace, which is the first explicit
    1499             :          * entry in the search_path.
    1500             :          */
    1501         136 :         List       *search_path = fetch_search_path(false);
    1502             : 
    1503         136 :         if (search_path == NIL) /* nothing valid in search_path? */
    1504           0 :             ereport(ERROR,
    1505             :                     (errcode(ERRCODE_UNDEFINED_SCHEMA),
    1506             :                      errmsg("no schema has been selected to create in")));
    1507         136 :         schemaOid = linitial_oid(search_path);
    1508         136 :         schemaName = get_namespace_name(schemaOid);
    1509         136 :         if (schemaName == NULL) /* recently-deleted namespace? */
    1510           0 :             ereport(ERROR,
    1511             :                     (errcode(ERRCODE_UNDEFINED_SCHEMA),
    1512             :                      errmsg("no schema has been selected to create in")));
    1513             : 
    1514         136 :         list_free(search_path);
    1515             :     }
    1516             : 
    1517             :     /*
    1518             :      * Make note if a temporary namespace has been accessed in this
    1519             :      * transaction.
    1520             :      */
    1521         580 :     if (isTempNamespace(schemaOid))
    1522           4 :         MyXactFlags |= XACT_FLAGS_ACCESSEDTEMPNAMESPACE;
    1523             : 
    1524             :     /*
    1525             :      * We don't check creation rights on the target namespace here.  If the
    1526             :      * extension script actually creates any objects there, it will fail if
    1527             :      * the user doesn't have such permissions.  But there are cases such as
    1528             :      * procedural languages where it's convenient to set schema = pg_catalog
    1529             :      * yet we don't want to restrict the command to users with ACL_CREATE for
    1530             :      * pg_catalog.
    1531             :      */
    1532             : 
    1533             :     /*
    1534             :      * Look up the prerequisite extensions, install them if necessary, and
    1535             :      * build lists of their OIDs and the OIDs of their target schemas.
    1536             :      */
    1537         580 :     requiredExtensions = NIL;
    1538         580 :     requiredSchemas = NIL;
    1539         634 :     foreach(lc, control->requires)
    1540             :     {
    1541          62 :         char       *curreq = (char *) lfirst(lc);
    1542             :         Oid         reqext;
    1543             :         Oid         reqschema;
    1544             : 
    1545          62 :         reqext = get_required_extension(curreq,
    1546             :                                         extensionName,
    1547             :                                         origSchemaName,
    1548             :                                         cascade,
    1549             :                                         parents,
    1550             :                                         is_create);
    1551          54 :         reqschema = get_extension_schema(reqext);
    1552          54 :         requiredExtensions = lappend_oid(requiredExtensions, reqext);
    1553          54 :         requiredSchemas = lappend_oid(requiredSchemas, reqschema);
    1554             :     }
    1555             : 
    1556             :     /*
    1557             :      * Insert new tuple into pg_extension, and create dependency entries.
    1558             :      */
    1559         572 :     address = InsertExtensionTuple(control->name, extowner,
    1560         572 :                                    schemaOid, control->relocatable,
    1561             :                                    versionName,
    1562             :                                    PointerGetDatum(NULL),
    1563             :                                    PointerGetDatum(NULL),
    1564             :                                    requiredExtensions);
    1565         572 :     extensionOid = address.objectId;
    1566             : 
    1567             :     /*
    1568             :      * Apply any control-file comment on extension
    1569             :      */
    1570         572 :     if (control->comment != NULL)
    1571         572 :         CreateComments(extensionOid, ExtensionRelationId, 0, control->comment);
    1572             : 
    1573             :     /*
    1574             :      * Execute the installation script file
    1575             :      */
    1576         572 :     execute_extension_script(extensionOid, control,
    1577             :                              NULL, versionName,
    1578             :                              requiredSchemas,
    1579             :                              schemaName, schemaOid);
    1580             : 
    1581             :     /*
    1582             :      * If additional update scripts have to be executed, apply the updates as
    1583             :      * though a series of ALTER EXTENSION UPDATE commands were given
    1584             :      */
    1585         566 :     ApplyExtensionUpdates(extensionOid, pcontrol,
    1586             :                           versionName, updateVersions,
    1587             :                           origSchemaName, cascade, is_create);
    1588             : 
    1589         566 :     return address;
    1590             : }
    1591             : 
    1592             : /*
    1593             :  * Get the OID of an extension listed in "requires", possibly creating it.
    1594             :  */
    1595             : static Oid
    1596          62 : get_required_extension(char *reqExtensionName,
    1597             :                        char *extensionName,
    1598             :                        char *origSchemaName,
    1599             :                        bool cascade,
    1600             :                        List *parents,
    1601             :                        bool is_create)
    1602             : {
    1603             :     Oid         reqExtensionOid;
    1604             : 
    1605          62 :     reqExtensionOid = get_extension_oid(reqExtensionName, true);
    1606          62 :     if (!OidIsValid(reqExtensionOid))
    1607             :     {
    1608          40 :         if (cascade)
    1609             :         {
    1610             :             /* Must install it. */
    1611             :             ObjectAddress addr;
    1612             :             List       *cascade_parents;
    1613             :             ListCell   *lc;
    1614             : 
    1615             :             /* Check extension name validity before trying to cascade. */
    1616          36 :             check_valid_extension_name(reqExtensionName);
    1617             : 
    1618             :             /* Check for cyclic dependency between extensions. */
    1619          40 :             foreach(lc, parents)
    1620             :             {
    1621           6 :                 char       *pname = (char *) lfirst(lc);
    1622             : 
    1623           6 :                 if (strcmp(pname, reqExtensionName) == 0)
    1624           2 :                     ereport(ERROR,
    1625             :                             (errcode(ERRCODE_INVALID_RECURSION),
    1626             :                              errmsg("cyclic dependency detected between extensions \"%s\" and \"%s\"",
    1627             :                                     reqExtensionName, extensionName)));
    1628             :             }
    1629             : 
    1630          34 :             ereport(NOTICE,
    1631             :                     (errmsg("installing required extension \"%s\"",
    1632             :                             reqExtensionName)));
    1633             : 
    1634             :             /* Add current extension to list of parents to pass down. */
    1635          34 :             cascade_parents = lappend(list_copy(parents), extensionName);
    1636             : 
    1637             :             /*
    1638             :              * Create the required extension.  We propagate the SCHEMA option
    1639             :              * if any, and CASCADE, but no other options.
    1640             :              */
    1641          34 :             addr = CreateExtensionInternal(reqExtensionName,
    1642             :                                            origSchemaName,
    1643             :                                            NULL,
    1644             :                                            cascade,
    1645             :                                            cascade_parents,
    1646             :                                            is_create);
    1647             : 
    1648             :             /* Get its newly-assigned OID. */
    1649          32 :             reqExtensionOid = addr.objectId;
    1650             :         }
    1651             :         else
    1652           4 :             ereport(ERROR,
    1653             :                     (errcode(ERRCODE_UNDEFINED_OBJECT),
    1654             :                      errmsg("required extension \"%s\" is not installed",
    1655             :                             reqExtensionName),
    1656             :                      is_create ?
    1657             :                      errhint("Use CREATE EXTENSION ... CASCADE to install required extensions too.") : 0));
    1658             :     }
    1659             : 
    1660          54 :     return reqExtensionOid;
    1661             : }
    1662             : 
    1663             : /*
    1664             :  * CREATE EXTENSION
    1665             :  */
    1666             : ObjectAddress
    1667         554 : CreateExtension(ParseState *pstate, CreateExtensionStmt *stmt)
    1668             : {
    1669         554 :     DefElem    *d_schema = NULL;
    1670         554 :     DefElem    *d_new_version = NULL;
    1671         554 :     DefElem    *d_cascade = NULL;
    1672         554 :     char       *schemaName = NULL;
    1673         554 :     char       *versionName = NULL;
    1674         554 :     bool        cascade = false;
    1675             :     ListCell   *lc;
    1676             : 
    1677             :     /* Check extension name validity before any filesystem access */
    1678         554 :     check_valid_extension_name(stmt->extname);
    1679             : 
    1680             :     /*
    1681             :      * Check for duplicate extension name.  The unique index on
    1682             :      * pg_extension.extname would catch this anyway, and serves as a backstop
    1683             :      * in case of race conditions; but this is a friendlier error message, and
    1684             :      * besides we need a check to support IF NOT EXISTS.
    1685             :      */
    1686         554 :     if (get_extension_oid(stmt->extname, true) != InvalidOid)
    1687             :     {
    1688           2 :         if (stmt->if_not_exists)
    1689             :         {
    1690           2 :             ereport(NOTICE,
    1691             :                     (errcode(ERRCODE_DUPLICATE_OBJECT),
    1692             :                      errmsg("extension \"%s\" already exists, skipping",
    1693             :                             stmt->extname)));
    1694           2 :             return InvalidObjectAddress;
    1695             :         }
    1696             :         else
    1697           0 :             ereport(ERROR,
    1698             :                     (errcode(ERRCODE_DUPLICATE_OBJECT),
    1699             :                      errmsg("extension \"%s\" already exists",
    1700             :                             stmt->extname)));
    1701             :     }
    1702             : 
    1703             :     /*
    1704             :      * We use global variables to track the extension being created, so we can
    1705             :      * create only one extension at the same time.
    1706             :      */
    1707         552 :     if (creating_extension)
    1708           0 :         ereport(ERROR,
    1709             :                 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
    1710             :                  errmsg("nested CREATE EXTENSION is not supported")));
    1711             : 
    1712             :     /* Deconstruct the statement option list */
    1713         600 :     foreach(lc, stmt->options)
    1714             :     {
    1715          48 :         DefElem    *defel = (DefElem *) lfirst(lc);
    1716             : 
    1717          48 :         if (strcmp(defel->defname, "schema") == 0)
    1718             :         {
    1719          24 :             if (d_schema)
    1720           0 :                 ereport(ERROR,
    1721             :                         (errcode(ERRCODE_SYNTAX_ERROR),
    1722             :                          errmsg("conflicting or redundant options"),
    1723             :                          parser_errposition(pstate, defel->location)));
    1724          24 :             d_schema = defel;
    1725          24 :             schemaName = defGetString(d_schema);
    1726             :         }
    1727          24 :         else if (strcmp(defel->defname, "new_version") == 0)
    1728             :         {
    1729           0 :             if (d_new_version)
    1730           0 :                 ereport(ERROR,
    1731             :                         (errcode(ERRCODE_SYNTAX_ERROR),
    1732             :                          errmsg("conflicting or redundant options"),
    1733             :                          parser_errposition(pstate, defel->location)));
    1734           0 :             d_new_version = defel;
    1735           0 :             versionName = defGetString(d_new_version);
    1736             :         }
    1737          24 :         else if (strcmp(defel->defname, "cascade") == 0)
    1738             :         {
    1739          24 :             if (d_cascade)
    1740           0 :                 ereport(ERROR,
    1741             :                         (errcode(ERRCODE_SYNTAX_ERROR),
    1742             :                          errmsg("conflicting or redundant options"),
    1743             :                          parser_errposition(pstate, defel->location)));
    1744          24 :             d_cascade = defel;
    1745          24 :             cascade = defGetBoolean(d_cascade);
    1746             :         }
    1747             :         else
    1748           0 :             elog(ERROR, "unrecognized option: %s", defel->defname);
    1749             :     }
    1750             : 
    1751             :     /* Call CreateExtensionInternal to do the real work. */
    1752         552 :     return CreateExtensionInternal(stmt->extname,
    1753             :                                    schemaName,
    1754             :                                    versionName,
    1755             :                                    cascade,
    1756             :                                    NIL,
    1757             :                                    true);
    1758             : }
    1759             : 
    1760             : /*
    1761             :  * InsertExtensionTuple
    1762             :  *
    1763             :  * Insert the new pg_extension row, and create extension's dependency entries.
    1764             :  * Return the OID assigned to the new row.
    1765             :  *
    1766             :  * This is exported for the benefit of pg_upgrade, which has to create a
    1767             :  * pg_extension entry (and the extension-level dependencies) without
    1768             :  * actually running the extension's script.
    1769             :  *
    1770             :  * extConfig and extCondition should be arrays or PointerGetDatum(NULL).
    1771             :  * We declare them as plain Datum to avoid needing array.h in extension.h.
    1772             :  */
    1773             : ObjectAddress
    1774         572 : InsertExtensionTuple(const char *extName, Oid extOwner,
    1775             :                      Oid schemaOid, bool relocatable, const char *extVersion,
    1776             :                      Datum extConfig, Datum extCondition,
    1777             :                      List *requiredExtensions)
    1778             : {
    1779             :     Oid         extensionOid;
    1780             :     Relation    rel;
    1781             :     Datum       values[Natts_pg_extension];
    1782             :     bool        nulls[Natts_pg_extension];
    1783             :     HeapTuple   tuple;
    1784             :     ObjectAddress myself;
    1785             :     ObjectAddress nsp;
    1786             :     ListCell   *lc;
    1787             : 
    1788             :     /*
    1789             :      * Build and insert the pg_extension tuple
    1790             :      */
    1791         572 :     rel = table_open(ExtensionRelationId, RowExclusiveLock);
    1792             : 
    1793         572 :     memset(values, 0, sizeof(values));
    1794         572 :     memset(nulls, 0, sizeof(nulls));
    1795             : 
    1796         572 :     extensionOid = GetNewOidWithIndex(rel, ExtensionOidIndexId,
    1797             :                                       Anum_pg_extension_oid);
    1798         572 :     values[Anum_pg_extension_oid - 1] = ObjectIdGetDatum(extensionOid);
    1799         572 :     values[Anum_pg_extension_extname - 1] =
    1800         572 :         DirectFunctionCall1(namein, CStringGetDatum(extName));
    1801         572 :     values[Anum_pg_extension_extowner - 1] = ObjectIdGetDatum(extOwner);
    1802         572 :     values[Anum_pg_extension_extnamespace - 1] = ObjectIdGetDatum(schemaOid);
    1803         572 :     values[Anum_pg_extension_extrelocatable - 1] = BoolGetDatum(relocatable);
    1804         572 :     values[Anum_pg_extension_extversion - 1] = CStringGetTextDatum(extVersion);
    1805             : 
    1806         572 :     if (extConfig == PointerGetDatum(NULL))
    1807         572 :         nulls[Anum_pg_extension_extconfig - 1] = true;
    1808             :     else
    1809           0 :         values[Anum_pg_extension_extconfig - 1] = extConfig;
    1810             : 
    1811         572 :     if (extCondition == PointerGetDatum(NULL))
    1812         572 :         nulls[Anum_pg_extension_extcondition - 1] = true;
    1813             :     else
    1814           0 :         values[Anum_pg_extension_extcondition - 1] = extCondition;
    1815             : 
    1816         572 :     tuple = heap_form_tuple(rel->rd_att, values, nulls);
    1817             : 
    1818         572 :     CatalogTupleInsert(rel, tuple);
    1819             : 
    1820         572 :     heap_freetuple(tuple);
    1821         572 :     table_close(rel, RowExclusiveLock);
    1822             : 
    1823             :     /*
    1824             :      * Record dependencies on owner, schema, and prerequisite extensions
    1825             :      */
    1826         572 :     recordDependencyOnOwner(ExtensionRelationId, extensionOid, extOwner);
    1827             : 
    1828         572 :     myself.classId = ExtensionRelationId;
    1829         572 :     myself.objectId = extensionOid;
    1830         572 :     myself.objectSubId = 0;
    1831             : 
    1832         572 :     nsp.classId = NamespaceRelationId;
    1833         572 :     nsp.objectId = schemaOid;
    1834         572 :     nsp.objectSubId = 0;
    1835             : 
    1836         572 :     recordDependencyOn(&myself, &nsp, DEPENDENCY_NORMAL);
    1837             : 
    1838         626 :     foreach(lc, requiredExtensions)
    1839             :     {
    1840          54 :         Oid         reqext = lfirst_oid(lc);
    1841             :         ObjectAddress otherext;
    1842             : 
    1843          54 :         otherext.classId = ExtensionRelationId;
    1844          54 :         otherext.objectId = reqext;
    1845          54 :         otherext.objectSubId = 0;
    1846             : 
    1847          54 :         recordDependencyOn(&myself, &otherext, DEPENDENCY_NORMAL);
    1848             :     }
    1849             :     /* Post creation hook for new extension */
    1850         572 :     InvokeObjectPostCreateHook(ExtensionRelationId, extensionOid, 0);
    1851             : 
    1852         572 :     return myself;
    1853             : }
    1854             : 
    1855             : /*
    1856             :  * Guts of extension deletion.
    1857             :  *
    1858             :  * All we need do here is remove the pg_extension tuple itself.  Everything
    1859             :  * else is taken care of by the dependency infrastructure.
    1860             :  */
    1861             : void
    1862          76 : RemoveExtensionById(Oid extId)
    1863             : {
    1864             :     Relation    rel;
    1865             :     SysScanDesc scandesc;
    1866             :     HeapTuple   tuple;
    1867             :     ScanKeyData entry[1];
    1868             : 
    1869             :     /*
    1870             :      * Disallow deletion of any extension that's currently open for insertion;
    1871             :      * else subsequent executions of recordDependencyOnCurrentExtension()
    1872             :      * could create dangling pg_depend records that refer to a no-longer-valid
    1873             :      * pg_extension OID.  This is needed not so much because we think people
    1874             :      * might write "DROP EXTENSION foo" in foo's own script files, as because
    1875             :      * errors in dependency management in extension script files could give
    1876             :      * rise to cases where an extension is dropped as a result of recursing
    1877             :      * from some contained object.  Because of that, we must test for the case
    1878             :      * here, not at some higher level of the DROP EXTENSION command.
    1879             :      */
    1880          76 :     if (extId == CurrentExtensionObject)
    1881           0 :         ereport(ERROR,
    1882             :                 (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
    1883             :                  errmsg("cannot drop extension \"%s\" because it is being modified",
    1884             :                         get_extension_name(extId))));
    1885             : 
    1886          76 :     rel = table_open(ExtensionRelationId, RowExclusiveLock);
    1887             : 
    1888          76 :     ScanKeyInit(&entry[0],
    1889             :                 Anum_pg_extension_oid,
    1890             :                 BTEqualStrategyNumber, F_OIDEQ,
    1891             :                 ObjectIdGetDatum(extId));
    1892          76 :     scandesc = systable_beginscan(rel, ExtensionOidIndexId, true,
    1893             :                                   NULL, 1, entry);
    1894             : 
    1895          76 :     tuple = systable_getnext(scandesc);
    1896             : 
    1897             :     /* We assume that there can be at most one matching tuple */
    1898          76 :     if (HeapTupleIsValid(tuple))
    1899          76 :         CatalogTupleDelete(rel, &tuple->t_self);
    1900             : 
    1901          76 :     systable_endscan(scandesc);
    1902             : 
    1903          76 :     table_close(rel, RowExclusiveLock);
    1904          76 : }
    1905             : 
    1906             : /*
    1907             :  * This function lists the available extensions (one row per primary control
    1908             :  * file in the control directory).  We parse each control file and report the
    1909             :  * interesting fields.
    1910             :  *
    1911             :  * The system view pg_available_extensions provides a user interface to this
    1912             :  * SRF, adding information about whether the extensions are installed in the
    1913             :  * current DB.
    1914             :  */
    1915             : Datum
    1916           4 : pg_available_extensions(PG_FUNCTION_ARGS)
    1917             : {
    1918           4 :     ReturnSetInfo *rsinfo = (ReturnSetInfo *) fcinfo->resultinfo;
    1919             :     TupleDesc   tupdesc;
    1920             :     Tuplestorestate *tupstore;
    1921             :     MemoryContext per_query_ctx;
    1922             :     MemoryContext oldcontext;
    1923             :     char       *location;
    1924             :     DIR        *dir;
    1925             :     struct dirent *de;
    1926             : 
    1927             :     /* check to see if caller supports us returning a tuplestore */
    1928           4 :     if (rsinfo == NULL || !IsA(rsinfo, ReturnSetInfo))
    1929           0 :         ereport(ERROR,
    1930             :                 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
    1931             :                  errmsg("set-valued function called in context that cannot accept a set")));
    1932           4 :     if (!(rsinfo->allowedModes & SFRM_Materialize))
    1933           0 :         ereport(ERROR,
    1934             :                 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
    1935             :                  errmsg("materialize mode required, but it is not allowed in this context")));
    1936             : 
    1937             :     /* Build a tuple descriptor for our result type */
    1938           4 :     if (get_call_result_type(fcinfo, NULL, &tupdesc) != TYPEFUNC_COMPOSITE)
    1939           0 :         elog(ERROR, "return type must be a row type");
    1940             : 
    1941             :     /* Build tuplestore to hold the result rows */
    1942           4 :     per_query_ctx = rsinfo->econtext->ecxt_per_query_memory;
    1943           4 :     oldcontext = MemoryContextSwitchTo(per_query_ctx);
    1944             : 
    1945           4 :     tupstore = tuplestore_begin_heap(true, false, work_mem);
    1946           4 :     rsinfo->returnMode = SFRM_Materialize;
    1947           4 :     rsinfo->setResult = tupstore;
    1948           4 :     rsinfo->setDesc = tupdesc;
    1949             : 
    1950           4 :     MemoryContextSwitchTo(oldcontext);
    1951             : 
    1952           4 :     location = get_extension_control_directory();
    1953           4 :     dir = AllocateDir(location);
    1954             : 
    1955             :     /*
    1956             :      * If the control directory doesn't exist, we want to silently return an
    1957             :      * empty set.  Any other error will be reported by ReadDir.
    1958             :      */
    1959           4 :     if (dir == NULL && errno == ENOENT)
    1960             :     {
    1961             :         /* do nothing */
    1962             :     }
    1963             :     else
    1964             :     {
    1965        1068 :         while ((de = ReadDir(dir, location)) != NULL)
    1966             :         {
    1967             :             ExtensionControlFile *control;
    1968             :             char       *extname;
    1969             :             Datum       values[3];
    1970             :             bool        nulls[3];
    1971             : 
    1972        1064 :             if (!is_extension_control_filename(de->d_name))
    1973         716 :                 continue;
    1974             : 
    1975             :             /* extract extension name from 'name.control' filename */
    1976         348 :             extname = pstrdup(de->d_name);
    1977         348 :             *strrchr(extname, '.') = '\0';
    1978             : 
    1979             :             /* ignore it if it's an auxiliary control file */
    1980         348 :             if (strstr(extname, "--"))
    1981           0 :                 continue;
    1982             : 
    1983         348 :             control = read_extension_control_file(extname);
    1984             : 
    1985         348 :             memset(values, 0, sizeof(values));
    1986         348 :             memset(nulls, 0, sizeof(nulls));
    1987             : 
    1988             :             /* name */
    1989         348 :             values[0] = DirectFunctionCall1(namein,
    1990             :                                             CStringGetDatum(control->name));
    1991             :             /* default_version */
    1992         348 :             if (control->default_version == NULL)
    1993           0 :                 nulls[1] = true;
    1994             :             else
    1995         348 :                 values[1] = CStringGetTextDatum(control->default_version);
    1996             :             /* comment */
    1997         348 :             if (control->comment == NULL)
    1998           0 :                 nulls[2] = true;
    1999             :             else
    2000         348 :                 values[2] = CStringGetTextDatum(control->comment);
    2001             : 
    2002         348 :             tuplestore_putvalues(tupstore, tupdesc, values, nulls);
    2003             :         }
    2004             : 
    2005           4 :         FreeDir(dir);
    2006             :     }
    2007             : 
    2008             :     /* clean up and return the tuplestore */
    2009             :     tuplestore_donestoring(tupstore);
    2010             : 
    2011           4 :     return (Datum) 0;
    2012             : }
    2013             : 
    2014             : /*
    2015             :  * This function lists the available extension versions (one row per
    2016             :  * extension installation script).  For each version, we parse the related
    2017             :  * control file(s) and report the interesting fields.
    2018             :  *
    2019             :  * The system view pg_available_extension_versions provides a user interface
    2020             :  * to this SRF, adding information about which versions are installed in the
    2021             :  * current DB.
    2022             :  */
    2023             : Datum
    2024           4 : pg_available_extension_versions(PG_FUNCTION_ARGS)
    2025             : {
    2026           4 :     ReturnSetInfo *rsinfo = (ReturnSetInfo *) fcinfo->resultinfo;
    2027             :     TupleDesc   tupdesc;
    2028             :     Tuplestorestate *tupstore;
    2029             :     MemoryContext per_query_ctx;
    2030             :     MemoryContext oldcontext;
    2031             :     char       *location;
    2032             :     DIR        *dir;
    2033             :     struct dirent *de;
    2034             : 
    2035             :     /* check to see if caller supports us returning a tuplestore */
    2036           4 :     if (rsinfo == NULL || !IsA(rsinfo, ReturnSetInfo))
    2037           0 :         ereport(ERROR,
    2038             :                 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
    2039             :                  errmsg("set-valued function called in context that cannot accept a set")));
    2040           4 :     if (!(rsinfo->allowedModes & SFRM_Materialize))
    2041           0 :         ereport(ERROR,
    2042             :                 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
    2043             :                  errmsg("materialize mode required, but it is not allowed in this context")));
    2044             : 
    2045             :     /* Build a tuple descriptor for our result type */
    2046           4 :     if (get_call_result_type(fcinfo, NULL, &tupdesc) != TYPEFUNC_COMPOSITE)
    2047           0 :         elog(ERROR, "return type must be a row type");
    2048             : 
    2049             :     /* Build tuplestore to hold the result rows */
    2050           4 :     per_query_ctx = rsinfo->econtext->ecxt_per_query_memory;
    2051           4 :     oldcontext = MemoryContextSwitchTo(per_query_ctx);
    2052             : 
    2053           4 :     tupstore = tuplestore_begin_heap(true, false, work_mem);
    2054           4 :     rsinfo->returnMode = SFRM_Materialize;
    2055           4 :     rsinfo->setResult = tupstore;
    2056           4 :     rsinfo->setDesc = tupdesc;
    2057             : 
    2058           4 :     MemoryContextSwitchTo(oldcontext);
    2059             : 
    2060           4 :     location = get_extension_control_directory();
    2061           4 :     dir = AllocateDir(location);
    2062             : 
    2063             :     /*
    2064             :      * If the control directory doesn't exist, we want to silently return an
    2065             :      * empty set.  Any other error will be reported by ReadDir.
    2066             :      */
    2067           4 :     if (dir == NULL && errno == ENOENT)
    2068             :     {
    2069             :         /* do nothing */
    2070             :     }
    2071             :     else
    2072             :     {
    2073        1068 :         while ((de = ReadDir(dir, location)) != NULL)
    2074             :         {
    2075             :             ExtensionControlFile *control;
    2076             :             char       *extname;
    2077             : 
    2078        1064 :             if (!is_extension_control_filename(de->d_name))
    2079         716 :                 continue;
    2080             : 
    2081             :             /* extract extension name from 'name.control' filename */
    2082         348 :             extname = pstrdup(de->d_name);
    2083         348 :             *strrchr(extname, '.') = '\0';
    2084             : 
    2085             :             /* ignore it if it's an auxiliary control file */
    2086         348 :             if (strstr(extname, "--"))
    2087           0 :                 continue;
    2088             : 
    2089             :             /* read the control file */
    2090         348 :             control = read_extension_control_file(extname);
    2091             : 
    2092             :             /* scan extension's script directory for install scripts */
    2093         348 :             get_available_versions_for_extension(control, tupstore, tupdesc);
    2094             :         }
    2095             : 
    2096           4 :         FreeDir(dir);
    2097             :     }
    2098             : 
    2099             :     /* clean up and return the tuplestore */
    2100             :     tuplestore_donestoring(tupstore);
    2101             : 
    2102           4 :     return (Datum) 0;
    2103             : }
    2104             : 
    2105             : /*
    2106             :  * Inner loop for pg_available_extension_versions:
    2107             :  *      read versions of one extension, add rows to tupstore
    2108             :  */
    2109             : static void
    2110         348 : get_available_versions_for_extension(ExtensionControlFile *pcontrol,
    2111             :                                      Tuplestorestate *tupstore,
    2112             :                                      TupleDesc tupdesc)
    2113             : {
    2114             :     List       *evi_list;
    2115             :     ListCell   *lc;
    2116             : 
    2117             :     /* Extract the version update graph from the script directory */
    2118         348 :     evi_list = get_ext_ver_list(pcontrol);
    2119             : 
    2120             :     /* For each installable version ... */
    2121        1056 :     foreach(lc, evi_list)
    2122             :     {
    2123         708 :         ExtensionVersionInfo *evi = (ExtensionVersionInfo *) lfirst(lc);
    2124             :         ExtensionControlFile *control;
    2125             :         Datum       values[8];
    2126             :         bool        nulls[8];
    2127             :         ListCell   *lc2;
    2128             : 
    2129         708 :         if (!evi->installable)
    2130         364 :             continue;
    2131             : 
    2132             :         /*
    2133             :          * Fetch parameters for specific version (pcontrol is not changed)
    2134             :          */
    2135         344 :         control = read_extension_aux_control_file(pcontrol, evi->name);
    2136             : 
    2137         344 :         memset(values, 0, sizeof(values));
    2138         344 :         memset(nulls, 0, sizeof(nulls));
    2139             : 
    2140             :         /* name */
    2141         344 :         values[0] = DirectFunctionCall1(namein,
    2142             :                                         CStringGetDatum(control->name));
    2143             :         /* version */
    2144         344 :         values[1] = CStringGetTextDatum(evi->name);
    2145             :         /* superuser */
    2146         344 :         values[2] = BoolGetDatum(control->superuser);
    2147             :         /* trusted */
    2148         344 :         values[3] = BoolGetDatum(control->trusted);
    2149             :         /* relocatable */
    2150         344 :         values[4] = BoolGetDatum(control->relocatable);
    2151             :         /* schema */
    2152         344 :         if (control->schema == NULL)
    2153         296 :             nulls[5] = true;
    2154             :         else
    2155          48 :             values[5] = DirectFunctionCall1(namein,
    2156             :                                             CStringGetDatum(control->schema));
    2157             :         /* requires */
    2158         344 :         if (control->requires == NIL)
    2159         260 :             nulls[6] = true;
    2160             :         else
    2161          84 :             values[6] = convert_requires_to_datum(control->requires);
    2162             :         /* comment */
    2163         344 :         if (control->comment == NULL)
    2164           0 :             nulls[7] = true;
    2165             :         else
    2166         344 :             values[7] = CStringGetTextDatum(control->comment);
    2167             : 
    2168         344 :         tuplestore_putvalues(tupstore, tupdesc, values, nulls);
    2169             : 
    2170             :         /*
    2171             :          * Find all non-directly-installable versions that would be installed
    2172             :          * starting from this version, and report them, inheriting the
    2173             :          * parameters that aren't changed in updates from this version.
    2174             :          */
    2175        1052 :         foreach(lc2, evi_list)
    2176             :         {
    2177         708 :             ExtensionVersionInfo *evi2 = (ExtensionVersionInfo *) lfirst(lc2);
    2178             :             List       *best_path;
    2179             : 
    2180         708 :             if (evi2->installable)
    2181         344 :                 continue;
    2182         364 :             if (find_install_path(evi_list, evi2, &best_path) == evi)
    2183             :             {
    2184             :                 /*
    2185             :                  * Fetch parameters for this version (pcontrol is not changed)
    2186             :                  */
    2187         152 :                 control = read_extension_aux_control_file(pcontrol, evi2->name);
    2188             : 
    2189             :                 /* name stays the same */
    2190             :                 /* version */
    2191         152 :                 values[1] = CStringGetTextDatum(evi2->name);
    2192             :                 /* superuser */
    2193         152 :                 values[2] = BoolGetDatum(control->superuser);
    2194             :                 /* trusted */
    2195         152 :                 values[3] = BoolGetDatum(control->trusted);
    2196             :                 /* relocatable */
    2197         152 :                 values[4] = BoolGetDatum(control->relocatable);
    2198             :                 /* schema stays the same */
    2199             :                 /* requires */
    2200         152 :                 if (control->requires == NIL)
    2201         152 :                     nulls[6] = true;
    2202             :                 else
    2203             :                 {
    2204           0 :                     values[6] = convert_requires_to_datum(control->requires);
    2205           0 :                     nulls[6] = false;
    2206             :                 }
    2207             :                 /* comment stays the same */
    2208             : 
    2209         152 :                 tuplestore_putvalues(tupstore, tupdesc, values, nulls);
    2210             :             }
    2211             :         }
    2212             :     }
    2213         348 : }
    2214             : 
    2215             : /*
    2216             :  * Test whether the given extension exists (not whether it's installed)
    2217             :  *
    2218             :  * This checks for the existence of a matching control file in the extension
    2219             :  * directory.  That's not a bulletproof check, since the file might be
    2220             :  * invalid, but this is only used for hints so it doesn't have to be 100%
    2221             :  * right.
    2222             :  */
    2223             : bool
    2224           0 : extension_file_exists(const char *extensionName)
    2225             : {
    2226           0 :     bool        result = false;
    2227             :     char       *location;
    2228             :     DIR        *dir;
    2229             :     struct dirent *de;
    2230             : 
    2231           0 :     location = get_extension_control_directory();
    2232           0 :     dir = AllocateDir(location);
    2233             : 
    2234             :     /*
    2235             :      * If the control directory doesn't exist, we want to silently return
    2236             :      * false.  Any other error will be reported by ReadDir.
    2237             :      */
    2238           0 :     if (dir == NULL && errno == ENOENT)
    2239             :     {
    2240             :         /* do nothing */
    2241             :     }
    2242             :     else
    2243             :     {
    2244           0 :         while ((de = ReadDir(dir, location)) != NULL)
    2245             :         {
    2246             :             char       *extname;
    2247             : 
    2248           0 :             if (!is_extension_control_filename(de->d_name))
    2249           0 :                 continue;
    2250             : 
    2251             :             /* extract extension name from 'name.control' filename */
    2252           0 :             extname = pstrdup(de->d_name);
    2253           0 :             *strrchr(extname, '.') = '\0';
    2254             : 
    2255             :             /* ignore it if it's an auxiliary control file */
    2256           0 :             if (strstr(extname, "--"))
    2257           0 :                 continue;
    2258             : 
    2259             :             /* done if it matches request */
    2260           0 :             if (strcmp(extname, extensionName) == 0)
    2261             :             {
    2262           0 :                 result = true;
    2263           0 :                 break;
    2264             :             }
    2265             :         }
    2266             : 
    2267           0 :         FreeDir(dir);
    2268             :     }
    2269             : 
    2270           0 :     return result;
    2271             : }
    2272             : 
    2273             : /*
    2274             :  * Convert a list of extension names to a name[] Datum
    2275             :  */
    2276             : static Datum
    2277          84 : convert_requires_to_datum(List *requires)
    2278             : {
    2279             :     Datum      *datums;
    2280             :     int         ndatums;
    2281             :     ArrayType  *a;
    2282             :     ListCell   *lc;
    2283             : 
    2284          84 :     ndatums = list_length(requires);
    2285          84 :     datums = (Datum *) palloc(ndatums * sizeof(Datum));
    2286          84 :     ndatums = 0;
    2287         208 :     foreach(lc, requires)
    2288             :     {
    2289         124 :         char       *curreq = (char *) lfirst(lc);
    2290             : 
    2291         124 :         datums[ndatums++] =
    2292         124 :             DirectFunctionCall1(namein, CStringGetDatum(curreq));
    2293             :     }
    2294          84 :     a = construct_array(datums, ndatums,
    2295             :                         NAMEOID,
    2296             :                         NAMEDATALEN, false, TYPALIGN_CHAR);
    2297          84 :     return PointerGetDatum(a);
    2298             : }
    2299             : 
    2300             : /*
    2301             :  * This function reports the version update paths that exist for the
    2302             :  * specified extension.
    2303             :  */
    2304             : Datum
    2305           0 : pg_extension_update_paths(PG_FUNCTION_ARGS)
    2306             : {
    2307           0 :     Name        extname = PG_GETARG_NAME(0);
    2308           0 :     ReturnSetInfo *rsinfo = (ReturnSetInfo *) fcinfo->resultinfo;
    2309             :     TupleDesc   tupdesc;
    2310             :     Tuplestorestate *tupstore;
    2311             :     MemoryContext per_query_ctx;
    2312             :     MemoryContext oldcontext;
    2313             :     List       *evi_list;
    2314             :     ExtensionControlFile *control;
    2315             :     ListCell   *lc1;
    2316             : 
    2317             :     /* Check extension name validity before any filesystem access */
    2318           0 :     check_valid_extension_name(NameStr(*extname));
    2319             : 
    2320             :     /* check to see if caller supports us returning a tuplestore */
    2321           0 :     if (rsinfo == NULL || !IsA(rsinfo, ReturnSetInfo))
    2322           0 :         ereport(ERROR,
    2323             :                 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
    2324             :                  errmsg("set-valued function called in context that cannot accept a set")));
    2325           0 :     if (!(rsinfo->allowedModes & SFRM_Materialize))
    2326           0 :         ereport(ERROR,
    2327             :                 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
    2328             :                  errmsg("materialize mode required, but it is not allowed in this context")));
    2329             : 
    2330             :     /* Build a tuple descriptor for our result type */
    2331           0 :     if (get_call_result_type(fcinfo, NULL, &tupdesc) != TYPEFUNC_COMPOSITE)
    2332           0 :         elog(ERROR, "return type must be a row type");
    2333             : 
    2334             :     /* Build tuplestore to hold the result rows */
    2335           0 :     per_query_ctx = rsinfo->econtext->ecxt_per_query_memory;
    2336           0 :     oldcontext = MemoryContextSwitchTo(per_query_ctx);
    2337             : 
    2338           0 :     tupstore = tuplestore_begin_heap(true, false, work_mem);
    2339           0 :     rsinfo->returnMode = SFRM_Materialize;
    2340           0 :     rsinfo->setResult = tupstore;
    2341           0 :     rsinfo->setDesc = tupdesc;
    2342             : 
    2343           0 :     MemoryContextSwitchTo(oldcontext);
    2344             : 
    2345             :     /* Read the extension's control file */
    2346           0 :     control = read_extension_control_file(NameStr(*extname));
    2347             : 
    2348             :     /* Extract the version update graph from the script directory */
    2349           0 :     evi_list = get_ext_ver_list(control);
    2350             : 
    2351             :     /* Iterate over all pairs of versions */
    2352           0 :     foreach(lc1, evi_list)
    2353             :     {
    2354           0 :         ExtensionVersionInfo *evi1 = (ExtensionVersionInfo *) lfirst(lc1);
    2355             :         ListCell   *lc2;
    2356             : 
    2357           0 :         foreach(lc2, evi_list)
    2358             :         {
    2359           0 :             ExtensionVersionInfo *evi2 = (ExtensionVersionInfo *) lfirst(lc2);
    2360             :             List       *path;
    2361             :             Datum       values[3];
    2362             :             bool        nulls[3];
    2363             : 
    2364           0 :             if (evi1 == evi2)
    2365           0 :                 continue;
    2366             : 
    2367             :             /* Find shortest path from evi1 to evi2 */
    2368           0 :             path = find_update_path(evi_list, evi1, evi2, false, true);
    2369             : 
    2370             :             /* Emit result row */
    2371           0 :             memset(values, 0, sizeof(values));
    2372           0 :             memset(nulls, 0, sizeof(nulls));
    2373             : 
    2374             :             /* source */
    2375           0 :             values[0] = CStringGetTextDatum(evi1->name);
    2376             :             /* target */
    2377           0 :             values[1] = CStringGetTextDatum(evi2->name);
    2378             :             /* path */
    2379           0 :             if (path == NIL)
    2380           0 :                 nulls[2] = true;
    2381             :             else
    2382             :             {
    2383             :                 StringInfoData pathbuf;
    2384             :                 ListCell   *lcv;
    2385             : 
    2386           0 :                 initStringInfo(&pathbuf);
    2387             :                 /* The path doesn't include start vertex, but show it */
    2388           0 :                 appendStringInfoString(&pathbuf, evi1->name);
    2389           0 :                 foreach(lcv, path)
    2390             :                 {
    2391           0 :                     char       *versionName = (char *) lfirst(lcv);
    2392             : 
    2393           0 :                     appendStringInfoString(&pathbuf, "--");
    2394           0 :                     appendStringInfoString(&pathbuf, versionName);
    2395             :                 }
    2396           0 :                 values[2] = CStringGetTextDatum(pathbuf.data);
    2397           0 :                 pfree(pathbuf.data);
    2398             :             }
    2399             : 
    2400           0 :             tuplestore_putvalues(tupstore, tupdesc, values, nulls);
    2401             :         }
    2402             :     }
    2403             : 
    2404             :     /* clean up and return the tuplestore */
    2405             :     tuplestore_donestoring(tupstore);
    2406             : 
    2407           0 :     return (Datum) 0;
    2408             : }
    2409             : 
    2410             : /*
    2411             :  * pg_extension_config_dump
    2412             :  *
    2413             :  * Record information about a configuration table that belongs to an
    2414             :  * extension being created, but whose contents should be dumped in whole
    2415             :  * or in part during pg_dump.
    2416             :  */
    2417             : Datum
    2418           4 : pg_extension_config_dump(PG_FUNCTION_ARGS)
    2419             : {
    2420           4 :     Oid         tableoid = PG_GETARG_OID(0);
    2421           4 :     text       *wherecond = PG_GETARG_TEXT_PP(1);
    2422             :     char       *tablename;
    2423             :     Relation    extRel;
    2424             :     ScanKeyData key[1];
    2425             :     SysScanDesc extScan;
    2426             :     HeapTuple   extTup;
    2427             :     Datum       arrayDatum;
    2428             :     Datum       elementDatum;
    2429             :     int         arrayLength;
    2430             :     int         arrayIndex;
    2431             :     bool        isnull;
    2432             :     Datum       repl_val[Natts_pg_extension];
    2433             :     bool        repl_null[Natts_pg_extension];
    2434             :     bool        repl_repl[Natts_pg_extension];
    2435             :     ArrayType  *a;
    2436             : 
    2437             :     /*
    2438             :      * We only allow this to be called from an extension's SQL script. We
    2439             :      * shouldn't need any permissions check beyond that.
    2440             :      */
    2441           4 :     if (!creating_extension)
    2442           0 :         ereport(ERROR,
    2443             :                 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
    2444             :                  errmsg("%s can only be called from an SQL script executed by CREATE EXTENSION",
    2445             :                         "pg_extension_config_dump()")));
    2446             : 
    2447             :     /*
    2448             :      * Check that the table exists and is a member of the extension being
    2449             :      * created.  This ensures that we don't need to register an additional
    2450             :      * dependency to protect the extconfig entry.
    2451             :      */
    2452           4 :     tablename = get_rel_name(tableoid);
    2453           4 :     if (tablename == NULL)
    2454           0 :         ereport(ERROR,
    2455             :                 (errcode(ERRCODE_UNDEFINED_TABLE),
    2456             :                  errmsg("OID %u does not refer to a table", tableoid)));
    2457           4 :     if (getExtensionOfObject(RelationRelationId, tableoid) !=
    2458             :         CurrentExtensionObject)
    2459           0 :         ereport(ERROR,
    2460             :                 (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
    2461             :                  errmsg("table \"%s\" is not a member of the extension being created",
    2462             :                         tablename)));
    2463             : 
    2464             :     /*
    2465             :      * Add the table OID and WHERE condition to the extension's extconfig and
    2466             :      * extcondition arrays.
    2467             :      *
    2468             :      * If the table is already in extconfig, treat this as an update of the
    2469             :      * WHERE condition.
    2470             :      */
    2471             : 
    2472             :     /* Find the pg_extension tuple */
    2473           4 :     extRel = table_open(ExtensionRelationId, RowExclusiveLock);
    2474             : 
    2475           4 :     ScanKeyInit(&key[0],
    2476             :                 Anum_pg_extension_oid,
    2477             :                 BTEqualStrategyNumber, F_OIDEQ,
    2478             :                 ObjectIdGetDatum(CurrentExtensionObject));
    2479             : 
    2480           4 :     extScan = systable_beginscan(extRel, ExtensionOidIndexId, true,
    2481             :                                  NULL, 1, key);
    2482             : 
    2483           4 :     extTup = systable_getnext(extScan);
    2484             : 
    2485           4 :     if (!HeapTupleIsValid(extTup))  /* should not happen */
    2486           0 :         elog(ERROR, "could not find tuple for extension %u",
    2487             :              CurrentExtensionObject);
    2488             : 
    2489           4 :     memset(repl_val, 0, sizeof(repl_val));
    2490           4 :     memset(repl_null, false, sizeof(repl_null));
    2491           4 :     memset(repl_repl, false, sizeof(repl_repl));
    2492             : 
    2493             :     /* Build or modify the extconfig value */
    2494           4 :     elementDatum = ObjectIdGetDatum(tableoid);
    2495             : 
    2496           4 :     arrayDatum = heap_getattr(extTup, Anum_pg_extension_extconfig,
    2497             :                               RelationGetDescr(extRel), &isnull);
    2498           4 :     if (isnull)
    2499             :     {
    2500             :         /* Previously empty extconfig, so build 1-element array */
    2501           4 :         arrayLength = 0;
    2502           4 :         arrayIndex = 1;
    2503             : 
    2504           4 :         a = construct_array(&elementDatum, 1,
    2505             :                             OIDOID,
    2506             :                             sizeof(Oid), true, TYPALIGN_INT);
    2507             :     }
    2508             :     else
    2509             :     {
    2510             :         /* Modify or extend existing extconfig array */
    2511             :         Oid        *arrayData;
    2512             :         int         i;
    2513             : 
    2514           0 :         a = DatumGetArrayTypeP(arrayDatum);
    2515             : 
    2516           0 :         arrayLength = ARR_DIMS(a)[0];
    2517           0 :         if (ARR_NDIM(a) != 1 ||
    2518           0 :             ARR_LBOUND(a)[0] != 1 ||
    2519           0 :             arrayLength < 0 ||
    2520           0 :             ARR_HASNULL(a) ||
    2521           0 :             ARR_ELEMTYPE(a) != OIDOID)
    2522           0 :             elog(ERROR, "extconfig is not a 1-D Oid array");
    2523           0 :         arrayData = (Oid *) ARR_DATA_PTR(a);
    2524             : 
    2525           0 :         arrayIndex = arrayLength + 1;   /* set up to add after end */
    2526             : 
    2527           0 :         for (i = 0; i < arrayLength; i++)
    2528             :         {
    2529           0 :             if (arrayData[i] == tableoid)
    2530             :             {
    2531           0 :                 arrayIndex = i + 1; /* replace this element instead */
    2532           0 :                 break;
    2533             :             }
    2534             :         }
    2535             : 
    2536           0 :         a = array_set(a, 1, &arrayIndex,
    2537             :                       elementDatum,
    2538             :                       false,
    2539             :                       -1 /* varlena array */ ,
    2540             :                       sizeof(Oid) /* OID's typlen */ ,
    2541             :                       true /* OID's typbyval */ ,
    2542             :                       TYPALIGN_INT /* OID's typalign */ );
    2543             :     }
    2544           4 :     repl_val[Anum_pg_extension_extconfig - 1] = PointerGetDatum(a);
    2545           4 :     repl_repl[Anum_pg_extension_extconfig - 1] = true;
    2546             : 
    2547             :     /* Build or modify the extcondition value */
    2548           4 :     elementDatum = PointerGetDatum(wherecond);
    2549             : 
    2550           4 :     arrayDatum = heap_getattr(extTup, Anum_pg_extension_extcondition,
    2551             :                               RelationGetDescr(extRel), &isnull);
    2552           4 :     if (isnull)
    2553             :     {
    2554           4 :         if (arrayLength != 0)
    2555           0 :             elog(ERROR, "extconfig and extcondition arrays do not match");
    2556             : 
    2557           4 :         a = construct_array(&elementDatum, 1,
    2558             :                             TEXTOID,
    2559             :                             -1, false, TYPALIGN_INT);
    2560             :     }
    2561             :     else
    2562             :     {
    2563           0 :         a = DatumGetArrayTypeP(arrayDatum);
    2564             : 
    2565           0 :         if (ARR_NDIM(a) != 1 ||
    2566           0 :             ARR_LBOUND(a)[0] != 1 ||
    2567           0 :             ARR_HASNULL(a) ||
    2568           0 :             ARR_ELEMTYPE(a) != TEXTOID)
    2569           0 :             elog(ERROR, "extcondition is not a 1-D text array");
    2570           0 :         if (ARR_DIMS(a)[0] != arrayLength)
    2571           0 :             elog(ERROR, "extconfig and extcondition arrays do not match");
    2572             : 
    2573             :         /* Add or replace at same index as in extconfig */
    2574           0 :         a = array_set(a, 1, &arrayIndex,
    2575             :                       elementDatum,
    2576             :                       false,
    2577             :                       -1 /* varlena array */ ,
    2578             :                       -1 /* TEXT's typlen */ ,
    2579             :                       false /* TEXT's typbyval */ ,
    2580             :                       TYPALIGN_INT /* TEXT's typalign */ );
    2581             :     }
    2582           4 :     repl_val[Anum_pg_extension_extcondition - 1] = PointerGetDatum(a);
    2583           4 :     repl_repl[Anum_pg_extension_extcondition - 1] = true;
    2584             : 
    2585           4 :     extTup = heap_modify_tuple(extTup, RelationGetDescr(extRel),
    2586             :                                repl_val, repl_null, repl_repl);
    2587             : 
    2588           4 :     CatalogTupleUpdate(extRel, &extTup->t_self, extTup);
    2589             : 
    2590           4 :     systable_endscan(extScan);
    2591             : 
    2592           4 :     table_close(extRel, RowExclusiveLock);
    2593             : 
    2594           4 :     PG_RETURN_VOID();
    2595             : }
    2596             : 
    2597             : /*
    2598             :  * extension_config_remove
    2599             :  *
    2600             :  * Remove the specified table OID from extension's extconfig, if present.
    2601             :  * This is not currently exposed as a function, but it could be;
    2602             :  * for now, we just invoke it from ALTER EXTENSION DROP.
    2603             :  */
    2604             : static void
    2605          12 : extension_config_remove(Oid extensionoid, Oid tableoid)
    2606             : {
    2607             :     Relation    extRel;
    2608             :     ScanKeyData key[1];
    2609             :     SysScanDesc extScan;
    2610             :     HeapTuple   extTup;
    2611             :     Datum       arrayDatum;
    2612             :     int         arrayLength;
    2613             :     int         arrayIndex;
    2614             :     bool        isnull;
    2615             :     Datum       repl_val[Natts_pg_extension];
    2616             :     bool        repl_null[Natts_pg_extension];
    2617             :     bool        repl_repl[Natts_pg_extension];
    2618             :     ArrayType  *a;
    2619             : 
    2620             :     /* Find the pg_extension tuple */
    2621          12 :     extRel = table_open(ExtensionRelationId, RowExclusiveLock);
    2622             : 
    2623          12 :     ScanKeyInit(&key[0],
    2624             :                 Anum_pg_extension_oid,
    2625             :                 BTEqualStrategyNumber, F_OIDEQ,
    2626             :                 ObjectIdGetDatum(extensionoid));
    2627             : 
    2628          12 :     extScan = systable_beginscan(extRel, ExtensionOidIndexId, true,
    2629             :                                  NULL, 1, key);
    2630             : 
    2631          12 :     extTup = systable_getnext(extScan);
    2632             : 
    2633          12 :     if (!HeapTupleIsValid(extTup))  /* should not happen */
    2634           0 :         elog(ERROR, "could not find tuple for extension %u",
    2635             :              extensionoid);
    2636             : 
    2637             :     /* Search extconfig for the tableoid */
    2638          12 :     arrayDatum = heap_getattr(extTup, Anum_pg_extension_extconfig,
    2639             :                               RelationGetDescr(extRel), &isnull);
    2640          12 :     if (isnull)
    2641             :     {
    2642             :         /* nothing to do */
    2643           4 :         a = NULL;
    2644           4 :         arrayLength = 0;
    2645           4 :         arrayIndex = -1;
    2646             :     }
    2647             :     else
    2648             :     {
    2649             :         Oid        *arrayData;
    2650             :         int         i;
    2651             : 
    2652           8 :         a = DatumGetArrayTypeP(arrayDatum);
    2653             : 
    2654           8 :         arrayLength = ARR_DIMS(a)[0];
    2655           8 :         if (ARR_NDIM(a) != 1 ||
    2656           8 :             ARR_LBOUND(a)[0] != 1 ||
    2657           8 :             arrayLength < 0 ||
    2658           8 :             ARR_HASNULL(a) ||
    2659           8 :             ARR_ELEMTYPE(a) != OIDOID)
    2660           0 :             elog(ERROR, "extconfig is not a 1-D Oid array");
    2661           8 :         arrayData = (Oid *) ARR_DATA_PTR(a);
    2662             : 
    2663           8 :         arrayIndex = -1;        /* flag for no deletion needed */
    2664             : 
    2665          16 :         for (i = 0; i < arrayLength; i++)
    2666             :         {
    2667           8 :             if (arrayData[i] == tableoid)
    2668             :             {
    2669           0 :                 arrayIndex = i; /* index to remove */
    2670           0 :                 break;
    2671             :             }
    2672             :         }
    2673             :     }
    2674             : 
    2675             :     /* If tableoid is not in extconfig, nothing to do */
    2676          12 :     if (arrayIndex < 0)
    2677             :     {
    2678          12 :         systable_endscan(extScan);
    2679          12 :         table_close(extRel, RowExclusiveLock);
    2680          12 :         return;
    2681             :     }
    2682             : 
    2683             :     /* Modify or delete the extconfig value */
    2684           0 :     memset(repl_val, 0, sizeof(repl_val));
    2685           0 :     memset(repl_null, false, sizeof(repl_null));
    2686           0 :     memset(repl_repl, false, sizeof(repl_repl));
    2687             : 
    2688           0 :     if (arrayLength <= 1)
    2689             :     {
    2690             :         /* removing only element, just set array to null */
    2691           0 :         repl_null[Anum_pg_extension_extconfig - 1] = true;
    2692             :     }
    2693             :     else
    2694             :     {
    2695             :         /* squeeze out the target element */
    2696             :         Datum      *dvalues;
    2697             :         int         nelems;
    2698             :         int         i;
    2699             : 
    2700             :         /* We already checked there are no nulls */
    2701           0 :         deconstruct_array(a, OIDOID, sizeof(Oid), true, TYPALIGN_INT,
    2702             :                           &dvalues, NULL, &nelems);
    2703             : 
    2704           0 :         for (i = arrayIndex; i < arrayLength - 1; i++)
    2705           0 :             dvalues[i] = dvalues[i + 1];
    2706             : 
    2707           0 :         a = construct_array(dvalues, arrayLength - 1,
    2708             :                             OIDOID, sizeof(Oid), true, TYPALIGN_INT);
    2709             : 
    2710           0 :         repl_val[Anum_pg_extension_extconfig - 1] = PointerGetDatum(a);
    2711             :     }
    2712           0 :     repl_repl[Anum_pg_extension_extconfig - 1] = true;
    2713             : 
    2714             :     /* Modify or delete the extcondition value */
    2715           0 :     arrayDatum = heap_getattr(extTup, Anum_pg_extension_extcondition,
    2716             :                               RelationGetDescr(extRel), &isnull);
    2717           0 :     if (isnull)
    2718             :     {
    2719           0 :         elog(ERROR, "extconfig and extcondition arrays do not match");
    2720             :     }
    2721             :     else
    2722             :     {
    2723           0 :         a = DatumGetArrayTypeP(arrayDatum);
    2724             : 
    2725           0 :         if (ARR_NDIM(a) != 1 ||
    2726           0 :             ARR_LBOUND(a)[0] != 1 ||
    2727           0 :             ARR_HASNULL(a) ||
    2728           0 :             ARR_ELEMTYPE(a) != TEXTOID)
    2729           0 :             elog(ERROR, "extcondition is not a 1-D text array");
    2730           0 :         if (ARR_DIMS(a)[0] != arrayLength)
    2731           0 :             elog(ERROR, "extconfig and extcondition arrays do not match");
    2732             :     }
    2733             : 
    2734           0 :     if (arrayLength <= 1)
    2735             :     {
    2736             :         /* removing only element, just set array to null */
    2737           0 :         repl_null[Anum_pg_extension_extcondition - 1] = true;
    2738             :     }
    2739             :     else
    2740             :     {
    2741             :         /* squeeze out the target element */
    2742             :         Datum      *dvalues;
    2743             :         int         nelems;
    2744             :         int         i;
    2745             : 
    2746             :         /* We already checked there are no nulls */
    2747           0 :         deconstruct_array(a, TEXTOID, -1, false, TYPALIGN_INT,
    2748             :                           &dvalues, NULL, &nelems);
    2749             : 
    2750           0 :         for (i = arrayIndex; i < arrayLength - 1; i++)
    2751           0 :             dvalues[i] = dvalues[i + 1];
    2752             : 
    2753           0 :         a = construct_array(dvalues, arrayLength - 1,
    2754             :                             TEXTOID, -1, false, TYPALIGN_INT);
    2755             : 
    2756           0 :         repl_val[Anum_pg_extension_extcondition - 1] = PointerGetDatum(a);
    2757             :     }
    2758           0 :     repl_repl[Anum_pg_extension_extcondition - 1] = true;
    2759             : 
    2760           0 :     extTup = heap_modify_tuple(extTup, RelationGetDescr(extRel),
    2761             :                                repl_val, repl_null, repl_repl);
    2762             : 
    2763           0 :     CatalogTupleUpdate(extRel, &extTup->t_self, extTup);
    2764             : 
    2765           0 :     systable_endscan(extScan);
    2766             : 
    2767           0 :     table_close(extRel, RowExclusiveLock);
    2768             : }
    2769             : 
    2770             : /*
    2771             :  * Execute ALTER EXTENSION SET SCHEMA
    2772             :  */
    2773             : ObjectAddress
    2774           0 : AlterExtensionNamespace(const char *extensionName, const char *newschema, Oid *oldschema)
    2775             : {
    2776             :     Oid         extensionOid;
    2777             :     Oid         nspOid;
    2778           0 :     Oid         oldNspOid = InvalidOid;
    2779             :     AclResult   aclresult;
    2780             :     Relation    extRel;
    2781             :     ScanKeyData key[2];
    2782             :     SysScanDesc extScan;
    2783             :     HeapTuple   extTup;
    2784             :     Form_pg_extension extForm;
    2785             :     Relation    depRel;
    2786             :     SysScanDesc depScan;
    2787             :     HeapTuple   depTup;
    2788             :     ObjectAddresses *objsMoved;
    2789             :     ObjectAddress extAddr;
    2790             : 
    2791           0 :     extensionOid = get_extension_oid(extensionName, false);
    2792             : 
    2793           0 :     nspOid = LookupCreationNamespace(newschema);
    2794             : 
    2795             :     /*
    2796             :      * Permission check: must own extension.  Note that we don't bother to
    2797             :      * check ownership of the individual member objects ...
    2798             :      */
    2799           0 :     if (!pg_extension_ownercheck(extensionOid, GetUserId()))
    2800           0 :         aclcheck_error(ACLCHECK_NOT_OWNER, OBJECT_EXTENSION,
    2801             :                        extensionName);
    2802             : 
    2803             :     /* Permission check: must have creation rights in target namespace */
    2804           0 :     aclresult = pg_namespace_aclcheck(nspOid, GetUserId(), ACL_CREATE);
    2805           0 :     if (aclresult != ACLCHECK_OK)
    2806           0 :         aclcheck_error(aclresult, OBJECT_SCHEMA, newschema);
    2807             : 
    2808             :     /*
    2809             :      * If the schema is currently a member of the extension, disallow moving
    2810             :      * the extension into the schema.  That would create a dependency loop.
    2811             :      */
    2812           0 :     if (getExtensionOfObject(NamespaceRelationId, nspOid) == extensionOid)
    2813           0 :         ereport(ERROR,
    2814             :                 (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
    2815             :                  errmsg("cannot move extension \"%s\" into schema \"%s\" "
    2816             :                         "because the extension contains the schema",
    2817             :                         extensionName, newschema)));
    2818             : 
    2819             :     /* Locate the pg_extension tuple */
    2820           0 :     extRel = table_open(ExtensionRelationId, RowExclusiveLock);
    2821             : 
    2822           0 :     ScanKeyInit(&key[0],
    2823             :                 Anum_pg_extension_oid,
    2824             :                 BTEqualStrategyNumber, F_OIDEQ,
    2825             :                 ObjectIdGetDatum(extensionOid));
    2826             : 
    2827           0 :     extScan = systable_beginscan(extRel, ExtensionOidIndexId, true,
    2828             :                                  NULL, 1, key);
    2829             : 
    2830           0 :     extTup = systable_getnext(extScan);
    2831             : 
    2832           0 :     if (!HeapTupleIsValid(extTup))  /* should not happen */
    2833           0 :         elog(ERROR, "could not find tuple for extension %u",
    2834             :              extensionOid);
    2835             : 
    2836             :     /* Copy tuple so we can modify it below */
    2837           0 :     extTup = heap_copytuple(extTup);
    2838           0 :     extForm = (Form_pg_extension) GETSTRUCT(extTup);
    2839             : 
    2840           0 :     systable_endscan(extScan);
    2841             : 
    2842             :     /*
    2843             :      * If the extension is already in the target schema, just silently do
    2844             :      * nothing.
    2845             :      */
    2846           0 :     if (extForm->extnamespace == nspOid)
    2847             :     {
    2848           0 :         table_close(extRel, RowExclusiveLock);
    2849           0 :         return InvalidObjectAddress;
    2850             :     }
    2851             : 
    2852             :     /* Check extension is supposed to be relocatable */
    2853           0 :     if (!extForm->extrelocatable)
    2854           0 :         ereport(ERROR,
    2855             :                 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
    2856             :                  errmsg("extension \"%s\" does not support SET SCHEMA",
    2857             :                         NameStr(extForm->extname))));
    2858             : 
    2859           0 :     objsMoved = new_object_addresses();
    2860             : 
    2861             :     /*
    2862             :      * Scan pg_depend to find objects that depend directly on the extension,
    2863             :      * and alter each one's schema.
    2864             :      */
    2865           0 :     depRel = table_open(DependRelationId, AccessShareLock);
    2866             : 
    2867           0 :     ScanKeyInit(&key[0],
    2868             :                 Anum_pg_depend_refclassid,
    2869             :                 BTEqualStrategyNumber, F_OIDEQ,
    2870             :                 ObjectIdGetDatum(ExtensionRelationId));
    2871           0 :     ScanKeyInit(&key[1],
    2872             :                 Anum_pg_depend_refobjid,
    2873             :                 BTEqualStrategyNumber, F_OIDEQ,
    2874             :                 ObjectIdGetDatum(extensionOid));
    2875             : 
    2876           0 :     depScan = systable_beginscan(depRel, DependReferenceIndexId, true,
    2877             :                                  NULL, 2, key);
    2878             : 
    2879           0 :     while (HeapTupleIsValid(depTup = systable_getnext(depScan)))
    2880             :     {
    2881           0 :         Form_pg_depend pg_depend = (Form_pg_depend) GETSTRUCT(depTup);
    2882             :         ObjectAddress dep;
    2883             :         Oid         dep_oldNspOid;
    2884             : 
    2885             :         /*
    2886             :          * Ignore non-membership dependencies.  (Currently, the only other
    2887             :          * case we could see here is a normal dependency from another
    2888             :          * extension.)
    2889             :          */
    2890           0 :         if (pg_depend->deptype != DEPENDENCY_EXTENSION)
    2891           0 :             continue;
    2892             : 
    2893           0 :         dep.classId = pg_depend->classid;
    2894           0 :         dep.objectId = pg_depend->objid;
    2895           0 :         dep.objectSubId = pg_depend->objsubid;
    2896             : 
    2897           0 :         if (dep.objectSubId != 0)   /* should not happen */
    2898           0 :             elog(ERROR, "extension should not have a sub-object dependency");
    2899             : 
    2900             :         /* Relocate the object */
    2901           0 :         dep_oldNspOid = AlterObjectNamespace_oid(dep.classId,
    2902             :                                                  dep.objectId,
    2903             :                                                  nspOid,
    2904             :                                                  objsMoved);
    2905             : 
    2906             :         /*
    2907             :          * Remember previous namespace of first object that has one
    2908             :          */
    2909           0 :         if (oldNspOid == InvalidOid && dep_oldNspOid != InvalidOid)
    2910           0 :             oldNspOid = dep_oldNspOid;
    2911             : 
    2912             :         /*
    2913             :          * If not all the objects had the same old namespace (ignoring any
    2914             :          * that are not in namespaces), complain.
    2915             :          */
    2916           0 :         if (dep_oldNspOid != InvalidOid && dep_oldNspOid != oldNspOid)
    2917           0 :             ereport(ERROR,
    2918             :                     (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
    2919             :                      errmsg("extension \"%s\" does not support SET SCHEMA",
    2920             :                             NameStr(extForm->extname)),
    2921             :                      errdetail("%s is not in the extension's schema \"%s\"",
    2922             :                                getObjectDescription(&dep),
    2923             :                                get_namespace_name(oldNspOid))));
    2924             :     }
    2925             : 
    2926             :     /* report old schema, if caller wants it */
    2927           0 :     if (oldschema)
    2928           0 :         *oldschema = oldNspOid;
    2929             : 
    2930           0 :     systable_endscan(depScan);
    2931             : 
    2932           0 :     relation_close(depRel, AccessShareLock);
    2933             : 
    2934             :     /* Now adjust pg_extension.extnamespace */
    2935           0 :     extForm->extnamespace = nspOid;
    2936             : 
    2937           0 :     CatalogTupleUpdate(extRel, &extTup->t_self, extTup);
    2938             : 
    2939           0 :     table_close(extRel, RowExclusiveLock);
    2940             : 
    2941             :     /* update dependencies to point to the new schema */
    2942           0 :     changeDependencyFor(ExtensionRelationId, extensionOid,
    2943             :                         NamespaceRelationId, oldNspOid, nspOid);
    2944             : 
    2945           0 :     InvokeObjectPostAlterHook(ExtensionRelationId, extensionOid, 0);
    2946             : 
    2947           0 :     ObjectAddressSet(extAddr, ExtensionRelationId, extensionOid);
    2948             : 
    2949           0 :     return extAddr;
    2950             : }
    2951             : 
    2952             : /*
    2953             :  * Execute ALTER EXTENSION UPDATE
    2954             :  */
    2955             : ObjectAddress
    2956           2 : ExecAlterExtensionStmt(ParseState *pstate, AlterExtensionStmt *stmt)
    2957             : {
    2958           2 :     DefElem    *d_new_version = NULL;
    2959             :     char       *versionName;
    2960             :     char       *oldVersionName;
    2961             :     ExtensionControlFile *control;
    2962             :     Oid         extensionOid;
    2963             :     Relation    extRel;
    2964             :     ScanKeyData key[1];
    2965             :     SysScanDesc extScan;
    2966             :     HeapTuple   extTup;
    2967             :     List       *updateVersions;
    2968             :     Datum       datum;
    2969             :     bool        isnull;
    2970             :     ListCell   *lc;
    2971             :     ObjectAddress address;
    2972             : 
    2973             :     /*
    2974             :      * We use global variables to track the extension being created, so we can
    2975             :      * create/update only one extension at the same time.
    2976             :      */
    2977           2 :     if (creating_extension)
    2978           0 :         ereport(ERROR,
    2979             :                 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
    2980             :                  errmsg("nested ALTER EXTENSION is not supported")));
    2981             : 
    2982             :     /*
    2983             :      * Look up the extension --- it must already exist in pg_extension
    2984             :      */
    2985           2 :     extRel = table_open(ExtensionRelationId, AccessShareLock);
    2986             : 
    2987           2 :     ScanKeyInit(&key[0],
    2988             :                 Anum_pg_extension_extname,
    2989             :                 BTEqualStrategyNumber, F_NAMEEQ,
    2990           2 :                 CStringGetDatum(stmt->extname));
    2991             : 
    2992           2 :     extScan = systable_beginscan(extRel, ExtensionNameIndexId, true,
    2993             :                                  NULL, 1, key);
    2994             : 
    2995           2 :     extTup = systable_getnext(extScan);
    2996             : 
    2997           2 :     if (!HeapTupleIsValid(extTup))
    2998           0 :         ereport(ERROR,
    2999             :                 (errcode(ERRCODE_UNDEFINED_OBJECT),
    3000             :                  errmsg("extension \"%s\" does not exist",
    3001             :                         stmt->extname)));
    3002             : 
    3003           2 :     extensionOid = ((Form_pg_extension) GETSTRUCT(extTup))->oid;
    3004             : 
    3005             :     /*
    3006             :      * Determine the existing version we are updating from
    3007             :      */
    3008           2 :     datum = heap_getattr(extTup, Anum_pg_extension_extversion,
    3009             :                          RelationGetDescr(extRel), &isnull);
    3010           2 :     if (isnull)
    3011           0 :         elog(ERROR, "extversion is null");
    3012           2 :     oldVersionName = text_to_cstring(DatumGetTextPP(datum));
    3013             : 
    3014           2 :     systable_endscan(extScan);
    3015             : 
    3016           2 :     table_close(extRel, AccessShareLock);
    3017             : 
    3018             :     /* Permission check: must own extension */
    3019           2 :     if (!pg_extension_ownercheck(extensionOid, GetUserId()))
    3020           0 :         aclcheck_error(ACLCHECK_NOT_OWNER, OBJECT_EXTENSION,
    3021           0 :                        stmt->extname);
    3022             : 
    3023             :     /*
    3024             :      * Read the primary control file.  Note we assume that it does not contain
    3025             :      * any non-ASCII data, so there is no need to worry about encoding at this
    3026             :      * point.
    3027             :      */
    3028           2 :     control = read_extension_control_file(stmt->extname);
    3029             : 
    3030             :     /*
    3031             :      * Read the statement option list
    3032             :      */
    3033           4 :     foreach(lc, stmt->options)
    3034             :     {
    3035           2 :         DefElem    *defel = (DefElem *) lfirst(lc);
    3036             : 
    3037           2 :         if (strcmp(defel->defname, "new_version") == 0)
    3038             :         {
    3039           2 :             if (d_new_version)
    3040           0 :                 ereport(ERROR,
    3041             :                         (errcode(ERRCODE_SYNTAX_ERROR),
    3042             :                          errmsg("conflicting or redundant options"),
    3043             :                          parser_errposition(pstate, defel->location)));
    3044           2 :             d_new_version = defel;
    3045             :         }
    3046             :         else
    3047           0 :             elog(ERROR, "unrecognized option: %s", defel->defname);
    3048             :     }
    3049             : 
    3050             :     /*
    3051             :      * Determine the version to update to
    3052             :      */
    3053           2 :     if (d_new_version && d_new_version->arg)
    3054           2 :         versionName = strVal(d_new_version->arg);
    3055           0 :     else if (control->default_version)
    3056           0 :         versionName = control->default_version;
    3057             :     else
    3058             :     {
    3059           0 :         ereport(ERROR,
    3060             :                 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
    3061             :                  errmsg("version to install must be specified")));
    3062             :         versionName = NULL;     /* keep compiler quiet */
    3063             :     }
    3064           2 :     check_valid_version_name(versionName);
    3065             : 
    3066             :     /*
    3067             :      * If we're already at that version, just say so
    3068             :      */
    3069           2 :     if (strcmp(oldVersionName, versionName) == 0)
    3070             :     {
    3071           0 :         ereport(NOTICE,
    3072             :                 (errmsg("version \"%s\" of extension \"%s\" is already installed",
    3073             :                         versionName, stmt->extname)));
    3074           0 :         return InvalidObjectAddress;
    3075             :     }
    3076             : 
    3077             :     /*
    3078             :      * Identify the series of update script files we need to execute
    3079             :      */
    3080           2 :     updateVersions = identify_update_path(control,
    3081             :                                           oldVersionName,
    3082             :                                           versionName);
    3083             : 
    3084             :     /*
    3085             :      * Update the pg_extension row and execute the update scripts, one at a
    3086             :      * time
    3087             :      */
    3088           2 :     ApplyExtensionUpdates(extensionOid, control,
    3089             :                           oldVersionName, updateVersions,
    3090             :                           NULL, false, false);
    3091             : 
    3092           2 :     ObjectAddressSet(address, ExtensionRelationId, extensionOid);
    3093             : 
    3094           2 :     return address;
    3095             : }
    3096             : 
    3097             : /*
    3098             :  * Apply a series of update scripts as though individual ALTER EXTENSION
    3099             :  * UPDATE commands had been given, including altering the pg_extension row
    3100             :  * and dependencies each time.
    3101             :  *
    3102             :  * This might be more work than necessary, but it ensures that old update
    3103             :  * scripts don't break if newer versions have different control parameters.
    3104             :  */
    3105             : static void
    3106         568 : ApplyExtensionUpdates(Oid extensionOid,
    3107             :                       ExtensionControlFile *pcontrol,
    3108             :                       const char *initialVersion,
    3109             :                       List *updateVersions,
    3110             :                       char *origSchemaName,
    3111             :                       bool cascade,
    3112             :                       bool is_create)
    3113             : {
    3114         568 :     const char *oldVersionName = initialVersion;
    3115             :     ListCell   *lcv;
    3116             : 
    3117         704 :     foreach(lcv, updateVersions)
    3118             :     {
    3119         136 :         char       *versionName = (char *) lfirst(lcv);
    3120             :         ExtensionControlFile *control;
    3121             :         char       *schemaName;
    3122             :         Oid         schemaOid;
    3123             :         List       *requiredExtensions;
    3124             :         List       *requiredSchemas;
    3125             :         Relation    extRel;
    3126             :         ScanKeyData key[1];
    3127             :         SysScanDesc extScan;
    3128             :         HeapTuple   extTup;
    3129             :         Form_pg_extension extForm;
    3130             :         Datum       values[Natts_pg_extension];
    3131             :         bool        nulls[Natts_pg_extension];
    3132             :         bool        repl[Natts_pg_extension];
    3133             :         ObjectAddress myself;
    3134             :         ListCell   *lc;
    3135             : 
    3136             :         /*
    3137             :          * Fetch parameters for specific version (pcontrol is not changed)
    3138             :          */
    3139         136 :         control = read_extension_aux_control_file(pcontrol, versionName);
    3140             : 
    3141             :         /* Find the pg_extension tuple */
    3142         136 :         extRel = table_open(ExtensionRelationId, RowExclusiveLock);
    3143             : 
    3144         136 :         ScanKeyInit(&key[0],
    3145             :                     Anum_pg_extension_oid,
    3146             :                     BTEqualStrategyNumber, F_OIDEQ,
    3147             :                     ObjectIdGetDatum(extensionOid));
    3148             : 
    3149         136 :         extScan = systable_beginscan(extRel, ExtensionOidIndexId, true,
    3150             :                                      NULL, 1, key);
    3151             : 
    3152         136 :         extTup = systable_getnext(extScan);
    3153             : 
    3154         136 :         if (!HeapTupleIsValid(extTup))  /* should not happen */
    3155           0 :             elog(ERROR, "could not find tuple for extension %u",
    3156             :                  extensionOid);
    3157             : 
    3158         136 :         extForm = (Form_pg_extension) GETSTRUCT(extTup);
    3159             : 
    3160             :         /*
    3161             :          * Determine the target schema (set by original install)
    3162             :          */
    3163         136 :         schemaOid = extForm->extnamespace;
    3164         136 :         schemaName = get_namespace_name(schemaOid);
    3165             : 
    3166             :         /*
    3167             :          * Modify extrelocatable and extversion in the pg_extension tuple
    3168             :          */
    3169         136 :         memset(values, 0, sizeof(values));
    3170         136 :         memset(nulls, 0, sizeof(nulls));
    3171         136 :         memset(repl, 0, sizeof(repl));
    3172             : 
    3173         136 :         values[Anum_pg_extension_extrelocatable - 1] =
    3174         136 :             BoolGetDatum(control->relocatable);
    3175         136 :         repl[Anum_pg_extension_extrelocatable - 1] = true;
    3176         136 :         values[Anum_pg_extension_extversion - 1] =
    3177         136 :             CStringGetTextDatum(versionName);
    3178         136 :         repl[Anum_pg_extension_extversion - 1] = true;
    3179             : 
    3180         136 :         extTup = heap_modify_tuple(extTup, RelationGetDescr(extRel),
    3181             :                                    values, nulls, repl);
    3182             : 
    3183         136 :         CatalogTupleUpdate(extRel, &extTup->t_self, extTup);
    3184             : 
    3185         136 :         systable_endscan(extScan);
    3186             : 
    3187         136 :         table_close(extRel, RowExclusiveLock);
    3188             : 
    3189             :         /*
    3190             :          * Look up the prerequisite extensions for this version, install them
    3191             :          * if necessary, and build lists of their OIDs and the OIDs of their
    3192             :          * target schemas.
    3193             :          */
    3194         136 :         requiredExtensions = NIL;
    3195         136 :         requiredSchemas = NIL;
    3196         136 :         foreach(lc, control->requires)
    3197             :         {
    3198           0 :             char       *curreq = (char *) lfirst(lc);
    3199             :             Oid         reqext;
    3200             :             Oid         reqschema;
    3201             : 
    3202           0 :             reqext = get_required_extension(curreq,
    3203             :                                             control->name,
    3204             :                                             origSchemaName,
    3205             :                                             cascade,
    3206             :                                             NIL,
    3207             :                                             is_create);
    3208           0 :             reqschema = get_extension_schema(reqext);
    3209           0 :             requiredExtensions = lappend_oid(requiredExtensions, reqext);
    3210           0 :             requiredSchemas = lappend_oid(requiredSchemas, reqschema);
    3211             :         }
    3212             : 
    3213             :         /*
    3214             :          * Remove and recreate dependencies on prerequisite extensions
    3215             :          */
    3216         136 :         deleteDependencyRecordsForClass(ExtensionRelationId, extensionOid,
    3217             :                                         ExtensionRelationId,
    3218             :                                         DEPENDENCY_NORMAL);
    3219             : 
    3220         136 :         myself.classId = ExtensionRelationId;
    3221         136 :         myself.objectId = extensionOid;
    3222         136 :         myself.objectSubId = 0;
    3223             : 
    3224         136 :         foreach(lc, requiredExtensions)
    3225             :         {
    3226           0 :             Oid         reqext = lfirst_oid(lc);
    3227             :             ObjectAddress otherext;
    3228             : 
    3229           0 :             otherext.classId = ExtensionRelationId;
    3230           0 :             otherext.objectId = reqext;
    3231           0 :             otherext.objectSubId = 0;
    3232             : 
    3233           0 :             recordDependencyOn(&myself, &otherext, DEPENDENCY_NORMAL);
    3234             :         }
    3235             : 
    3236         136 :         InvokeObjectPostAlterHook(ExtensionRelationId, extensionOid, 0);
    3237             : 
    3238             :         /*
    3239             :          * Finally, execute the update script file
    3240             :          */
    3241         136 :         execute_extension_script(extensionOid, control,
    3242             :                                  oldVersionName, versionName,
    3243             :                                  requiredSchemas,
    3244             :                                  schemaName, schemaOid);
    3245             : 
    3246             :         /*
    3247             :          * Update prior-version name and loop around.  Since
    3248             :          * execute_sql_string did a final CommandCounterIncrement, we can
    3249             :          * update the pg_extension row again.
    3250             :          */
    3251         136 :         oldVersionName = versionName;
    3252             :     }
    3253         568 : }
    3254             : 
    3255             : /*
    3256             :  * Execute ALTER EXTENSION ADD/DROP
    3257             :  *
    3258             :  * Return value is the address of the altered extension.
    3259             :  *
    3260             :  * objAddr is an output argument which, if not NULL, is set to the address of
    3261             :  * the added/dropped object.
    3262             :  */
    3263             : ObjectAddress
    3264         126 : ExecAlterExtensionContentsStmt(AlterExtensionContentsStmt *stmt,
    3265             :                                ObjectAddress *objAddr)
    3266             : {
    3267             :     ObjectAddress extension;
    3268             :     ObjectAddress object;
    3269             :     Relation    relation;
    3270             :     Oid         oldExtension;
    3271             : 
    3272         126 :     extension.classId = ExtensionRelationId;
    3273         126 :     extension.objectId = get_extension_oid(stmt->extname, false);
    3274         126 :     extension.objectSubId = 0;
    3275             : 
    3276             :     /* Permission check: must own extension */
    3277         126 :     if (!pg_extension_ownercheck(extension.objectId, GetUserId()))
    3278           0 :         aclcheck_error(ACLCHECK_NOT_OWNER, OBJECT_EXTENSION,
    3279           0 :                        stmt->extname);
    3280             : 
    3281             :     /*
    3282             :      * Translate the parser representation that identifies the object into an
    3283             :      * ObjectAddress.  get_object_address() will throw an error if the object
    3284             :      * does not exist, and will also acquire a lock on the object to guard
    3285             :      * against concurrent DROP and ALTER EXTENSION ADD/DROP operations.
    3286             :      */
    3287         126 :     object = get_object_address(stmt->objtype, stmt->object,
    3288             :                                 &relation, ShareUpdateExclusiveLock, false);
    3289             : 
    3290             :     Assert(object.objectSubId == 0);
    3291         126 :     if (objAddr)
    3292         126 :         *objAddr = object;
    3293             : 
    3294             :     /* Permission check: must own target object, too */
    3295         126 :     check_object_ownership(GetUserId(), stmt->objtype, object,
    3296             :                            stmt->object, relation);
    3297             : 
    3298             :     /*
    3299             :      * Check existing extension membership.
    3300             :      */
    3301         126 :     oldExtension = getExtensionOfObject(object.classId, object.objectId);
    3302             : 
    3303         126 :     if (stmt->action > 0)
    3304             :     {
    3305             :         /*
    3306             :          * ADD, so complain if object is already attached to some extension.
    3307             :          */
    3308          54 :         if (OidIsValid(oldExtension))
    3309           0 :             ereport(ERROR,
    3310             :                     (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
    3311             :                      errmsg("%s is already a member of extension \"%s\"",
    3312             :                             getObjectDescription(&object),
    3313             :                             get_extension_name(oldExtension))));
    3314             : 
    3315             :         /*
    3316             :          * Prevent a schema from being added to an extension if the schema
    3317             :          * contains the extension.  That would create a dependency loop.
    3318             :          */
    3319          56 :         if (object.classId == NamespaceRelationId &&
    3320           2 :             object.objectId == get_extension_schema(extension.objectId))
    3321           0 :             ereport(ERROR,
    3322             :                     (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
    3323             :                      errmsg("cannot add schema \"%s\" to extension \"%s\" "
    3324             :                             "because the schema contains the extension",
    3325             :                             get_namespace_name(object.objectId),
    3326             :                             stmt->extname)));
    3327             : 
    3328             :         /*
    3329             :          * OK, add the dependency.
    3330             :          */
    3331          54 :         recordDependencyOn(&object, &extension, DEPENDENCY_EXTENSION);
    3332             : 
    3333             :         /*
    3334             :          * Also record the initial ACL on the object, if any.
    3335             :          *
    3336             :          * Note that this will handle the object's ACLs, as well as any ACLs
    3337             :          * on object subIds.  (In other words, when the object is a table,
    3338             :          * this will record the table's ACL and the ACLs for the columns on
    3339             :          * the table, if any).
    3340             :          */
    3341          54 :         recordExtObjInitPriv(object.objectId, object.classId);
    3342             :     }
    3343             :     else
    3344             :     {
    3345             :         /*
    3346             :          * DROP, so complain if it's not a member.
    3347             :          */
    3348          72 :         if (oldExtension != extension.objectId)
    3349           0 :             ereport(ERROR,
    3350             :                     (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
    3351             :                      errmsg("%s is not a member of extension \"%s\"",
    3352             :                             getObjectDescription(&object),
    3353             :                             stmt->extname)));
    3354             : 
    3355             :         /*
    3356             :          * OK, drop the dependency.
    3357             :          */
    3358          72 :         if (deleteDependencyRecordsForClass(object.classId, object.objectId,
    3359             :                                             ExtensionRelationId,
    3360             :                                             DEPENDENCY_EXTENSION) != 1)
    3361           0 :             elog(ERROR, "unexpected number of extension dependency records");
    3362             : 
    3363             :         /*
    3364             :          * If it's a relation, it might have an entry in the extension's
    3365             :          * extconfig array, which we must remove.
    3366             :          */
    3367          72 :         if (object.classId == RelationRelationId)
    3368          12 :             extension_config_remove(extension.objectId, object.objectId);
    3369             : 
    3370             :         /*
    3371             :          * Remove all the initial ACLs, if any.
    3372             :          *
    3373             :          * Note that this will remove the object's ACLs, as well as any ACLs
    3374             :          * on object subIds.  (In other words, when the object is a table,
    3375             :          * this will remove the table's ACL and the ACLs for the columns on
    3376             :          * the table, if any).
    3377             :          */
    3378          72 :         removeExtObjInitPriv(object.objectId, object.classId);
    3379             :     }
    3380             : 
    3381         126 :     InvokeObjectPostAlterHook(ExtensionRelationId, extension.objectId, 0);
    3382             : 
    3383             :     /*
    3384             :      * If get_object_address() opened the relation for us, we close it to keep
    3385             :      * the reference count correct - but we retain any locks acquired by
    3386             :      * get_object_address() until commit time, to guard against concurrent
    3387             :      * activity.
    3388             :      */
    3389         126 :     if (relation != NULL)
    3390          26 :         relation_close(relation, NoLock);
    3391             : 
    3392         126 :     return extension;
    3393             : }
    3394             : 
    3395             : /*
    3396             :  * Read the whole of file into memory.
    3397             :  *
    3398             :  * The file contents are returned as a single palloc'd chunk. For convenience
    3399             :  * of the callers, an extra \0 byte is added to the end.
    3400             :  */
    3401             : static char *
    3402         702 : read_whole_file(const char *filename, int *length)
    3403             : {
    3404             :     char       *buf;
    3405             :     FILE       *file;
    3406             :     size_t      bytes_to_read;
    3407             :     struct stat fst;
    3408             : 
    3409         702 :     if (stat(filename, &fst) < 0)
    3410           0 :         ereport(ERROR,
    3411             :                 (errcode_for_file_access(),
    3412             :                  errmsg("could not stat file \"%s\": %m", filename)));
    3413             : 
    3414         702 :     if (fst.st_size > (MaxAllocSize - 1))
    3415           0 :         ereport(ERROR,
    3416             :                 (errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED),
    3417             :                  errmsg("file \"%s\" is too large", filename)));
    3418         702 :     bytes_to_read = (size_t) fst.st_size;
    3419             : 
    3420         702 :     if ((file = AllocateFile(filename, PG_BINARY_R)) == NULL)
    3421           0 :         ereport(ERROR,
    3422             :                 (errcode_for_file_access(),
    3423             :                  errmsg("could not open file \"%s\" for reading: %m",
    3424             :                         filename)));
    3425             : 
    3426         702 :     buf = (char *) palloc(bytes_to_read + 1);
    3427             : 
    3428         702 :     *length = fread(buf, 1, bytes_to_read, file);
    3429             : 
    3430         702 :     if (ferror(file))
    3431           0 :         ereport(ERROR,
    3432             :                 (errcode_for_file_access(),
    3433             :                  errmsg("could not read file \"%s\": %m", filename)));
    3434             : 
    3435         702 :     FreeFile(file);
    3436             : 
    3437         702 :     buf[*length] = '\0';
    3438         702 :     return buf;
    3439             : }

Generated by: LCOV version 1.13