PostgreSQL Source Code  git master
extension.c File Reference
#include "postgres.h"
#include <dirent.h>
#include <limits.h>
#include <sys/file.h>
#include <sys/stat.h>
#include <unistd.h>
#include "access/genam.h"
#include "access/htup_details.h"
#include "access/relation.h"
#include "access/table.h"
#include "access/xact.h"
#include "catalog/catalog.h"
#include "catalog/dependency.h"
#include "catalog/indexing.h"
#include "catalog/namespace.h"
#include "catalog/objectaccess.h"
#include "catalog/pg_authid.h"
#include "catalog/pg_collation.h"
#include "catalog/pg_database.h"
#include "catalog/pg_depend.h"
#include "catalog/pg_extension.h"
#include "catalog/pg_namespace.h"
#include "catalog/pg_type.h"
#include "commands/alter.h"
#include "commands/comment.h"
#include "commands/defrem.h"
#include "commands/extension.h"
#include "commands/schemacmds.h"
#include "funcapi.h"
#include "mb/pg_wchar.h"
#include "miscadmin.h"
#include "nodes/queryjumble.h"
#include "storage/fd.h"
#include "tcop/utility.h"
#include "utils/acl.h"
#include "utils/builtins.h"
#include "utils/conffiles.h"
#include "utils/fmgroids.h"
#include "utils/lsyscache.h"
#include "utils/memutils.h"
#include "utils/rel.h"
#include "utils/snapmgr.h"
#include "utils/syscache.h"
#include "utils/varlena.h"
Include dependency graph for extension.c:

Go to the source code of this file.

Data Structures

struct  ExtensionControlFile
 
struct  ExtensionVersionInfo
 
struct  script_error_callback_arg
 

Typedefs

typedef struct ExtensionControlFile ExtensionControlFile
 
typedef struct ExtensionVersionInfo ExtensionVersionInfo
 

Functions

static Listfind_update_path (List *evi_list, ExtensionVersionInfo *evi_start, ExtensionVersionInfo *evi_target, bool reject_indirect, bool reinitialize)
 
static Oid get_required_extension (char *reqExtensionName, char *extensionName, char *origSchemaName, bool cascade, List *parents, bool is_create)
 
static void get_available_versions_for_extension (ExtensionControlFile *pcontrol, Tuplestorestate *tupstore, TupleDesc tupdesc)
 
static Datum convert_requires_to_datum (List *requires)
 
static void ApplyExtensionUpdates (Oid extensionOid, ExtensionControlFile *pcontrol, const char *initialVersion, List *updateVersions, char *origSchemaName, bool cascade, bool is_create)
 
static void ExecAlterExtensionContentsRecurse (AlterExtensionContentsStmt *stmt, ObjectAddress extension, ObjectAddress object)
 
static char * read_whole_file (const char *filename, int *length)
 
Oid get_extension_oid (const char *extname, bool missing_ok)
 
char * get_extension_name (Oid ext_oid)
 
Oid get_extension_schema (Oid ext_oid)
 
static void check_valid_extension_name (const char *extensionname)
 
static void check_valid_version_name (const char *versionname)
 
static bool is_extension_control_filename (const char *filename)
 
static bool is_extension_script_filename (const char *filename)
 
static char * get_extension_control_directory (void)
 
static char * get_extension_control_filename (const char *extname)
 
static char * get_extension_script_directory (ExtensionControlFile *control)
 
static char * get_extension_aux_control_filename (ExtensionControlFile *control, const char *version)
 
static char * get_extension_script_filename (ExtensionControlFile *control, const char *from_version, const char *version)
 
static void parse_extension_control_file (ExtensionControlFile *control, const char *version)
 
static ExtensionControlFileread_extension_control_file (const char *extname)
 
static ExtensionControlFileread_extension_aux_control_file (const ExtensionControlFile *pcontrol, const char *version)
 
static char * read_extension_script_file (const ExtensionControlFile *control, const char *filename)
 
static void script_error_callback (void *arg)
 
static void execute_sql_string (const char *sql, const char *filename)
 
static bool extension_is_trusted (ExtensionControlFile *control)
 
static void execute_extension_script (Oid extensionOid, ExtensionControlFile *control, const char *from_version, const char *version, List *requiredSchemas, const char *schemaName, Oid schemaOid)
 
static ExtensionVersionInfoget_ext_ver_info (const char *versionname, List **evi_list)
 
static ExtensionVersionInfoget_nearest_unprocessed_vertex (List *evi_list)
 
static Listget_ext_ver_list (ExtensionControlFile *control)
 
static Listidentify_update_path (ExtensionControlFile *control, const char *oldVersion, const char *newVersion)
 
static ExtensionVersionInfofind_install_path (List *evi_list, ExtensionVersionInfo *evi_target, List **best_path)
 
static ObjectAddress CreateExtensionInternal (char *extensionName, char *schemaName, const char *versionName, bool cascade, List *parents, bool is_create)
 
ObjectAddress CreateExtension (ParseState *pstate, CreateExtensionStmt *stmt)
 
ObjectAddress InsertExtensionTuple (const char *extName, Oid extOwner, Oid schemaOid, bool relocatable, const char *extVersion, Datum extConfig, Datum extCondition, List *requiredExtensions)
 
void RemoveExtensionById (Oid extId)
 
Datum pg_available_extensions (PG_FUNCTION_ARGS)
 
Datum pg_available_extension_versions (PG_FUNCTION_ARGS)
 
bool extension_file_exists (const char *extensionName)
 
Datum pg_extension_update_paths (PG_FUNCTION_ARGS)
 
Datum pg_extension_config_dump (PG_FUNCTION_ARGS)
 
static void extension_config_remove (Oid extensionoid, Oid tableoid)
 
ObjectAddress AlterExtensionNamespace (const char *extensionName, const char *newschema, Oid *oldschema)
 
ObjectAddress ExecAlterExtensionStmt (ParseState *pstate, AlterExtensionStmt *stmt)
 
ObjectAddress ExecAlterExtensionContentsStmt (AlterExtensionContentsStmt *stmt, ObjectAddress *objAddr)
 

Variables

bool creating_extension = false
 
Oid CurrentExtensionObject = InvalidOid
 

Typedef Documentation

◆ ExtensionControlFile

◆ ExtensionVersionInfo

Function Documentation

◆ AlterExtensionNamespace()

ObjectAddress AlterExtensionNamespace ( const char *  extensionName,
const char *  newschema,
Oid oldschema 
)

Definition at line 2879 of file extension.c.

2880 {
2881  Oid extensionOid;
2882  Oid nspOid;
2883  Oid oldNspOid;
2884  AclResult aclresult;
2885  Relation extRel;
2886  ScanKeyData key[2];
2887  SysScanDesc extScan;
2888  HeapTuple extTup;
2889  Form_pg_extension extForm;
2890  Relation depRel;
2891  SysScanDesc depScan;
2892  HeapTuple depTup;
2893  ObjectAddresses *objsMoved;
2894  ObjectAddress extAddr;
2895 
2896  extensionOid = get_extension_oid(extensionName, false);
2897 
2898  nspOid = LookupCreationNamespace(newschema);
2899 
2900  /*
2901  * Permission check: must own extension. Note that we don't bother to
2902  * check ownership of the individual member objects ...
2903  */
2904  if (!object_ownercheck(ExtensionRelationId, extensionOid, GetUserId()))
2906  extensionName);
2907 
2908  /* Permission check: must have creation rights in target namespace */
2909  aclresult = object_aclcheck(NamespaceRelationId, nspOid, GetUserId(), ACL_CREATE);
2910  if (aclresult != ACLCHECK_OK)
2911  aclcheck_error(aclresult, OBJECT_SCHEMA, newschema);
2912 
2913  /*
2914  * If the schema is currently a member of the extension, disallow moving
2915  * the extension into the schema. That would create a dependency loop.
2916  */
2917  if (getExtensionOfObject(NamespaceRelationId, nspOid) == extensionOid)
2918  ereport(ERROR,
2919  (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
2920  errmsg("cannot move extension \"%s\" into schema \"%s\" "
2921  "because the extension contains the schema",
2922  extensionName, newschema)));
2923 
2924  /* Locate the pg_extension tuple */
2925  extRel = table_open(ExtensionRelationId, RowExclusiveLock);
2926 
2927  ScanKeyInit(&key[0],
2928  Anum_pg_extension_oid,
2929  BTEqualStrategyNumber, F_OIDEQ,
2930  ObjectIdGetDatum(extensionOid));
2931 
2932  extScan = systable_beginscan(extRel, ExtensionOidIndexId, true,
2933  NULL, 1, key);
2934 
2935  extTup = systable_getnext(extScan);
2936 
2937  if (!HeapTupleIsValid(extTup)) /* should not happen */
2938  elog(ERROR, "could not find tuple for extension %u",
2939  extensionOid);
2940 
2941  /* Copy tuple so we can modify it below */
2942  extTup = heap_copytuple(extTup);
2943  extForm = (Form_pg_extension) GETSTRUCT(extTup);
2944 
2945  systable_endscan(extScan);
2946 
2947  /*
2948  * If the extension is already in the target schema, just silently do
2949  * nothing.
2950  */
2951  if (extForm->extnamespace == nspOid)
2952  {
2953  table_close(extRel, RowExclusiveLock);
2954  return InvalidObjectAddress;
2955  }
2956 
2957  /* Check extension is supposed to be relocatable */
2958  if (!extForm->extrelocatable)
2959  ereport(ERROR,
2960  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2961  errmsg("extension \"%s\" does not support SET SCHEMA",
2962  NameStr(extForm->extname))));
2963 
2964  objsMoved = new_object_addresses();
2965 
2966  /* store the OID of the namespace to-be-changed */
2967  oldNspOid = extForm->extnamespace;
2968 
2969  /*
2970  * Scan pg_depend to find objects that depend directly on the extension,
2971  * and alter each one's schema.
2972  */
2973  depRel = table_open(DependRelationId, AccessShareLock);
2974 
2975  ScanKeyInit(&key[0],
2976  Anum_pg_depend_refclassid,
2977  BTEqualStrategyNumber, F_OIDEQ,
2978  ObjectIdGetDatum(ExtensionRelationId));
2979  ScanKeyInit(&key[1],
2980  Anum_pg_depend_refobjid,
2981  BTEqualStrategyNumber, F_OIDEQ,
2982  ObjectIdGetDatum(extensionOid));
2983 
2984  depScan = systable_beginscan(depRel, DependReferenceIndexId, true,
2985  NULL, 2, key);
2986 
2987  while (HeapTupleIsValid(depTup = systable_getnext(depScan)))
2988  {
2989  Form_pg_depend pg_depend = (Form_pg_depend) GETSTRUCT(depTup);
2990  ObjectAddress dep;
2991  Oid dep_oldNspOid;
2992 
2993  /*
2994  * If a dependent extension has a no_relocate request for this
2995  * extension, disallow SET SCHEMA. (XXX it's a bit ugly to do this in
2996  * the same loop that's actually executing the renames: we may detect
2997  * the error condition only after having expended a fair amount of
2998  * work. However, the alternative is to do two scans of pg_depend,
2999  * which seems like optimizing for failure cases. The rename work
3000  * will all roll back cleanly enough if we do fail here.)
3001  */
3002  if (pg_depend->deptype == DEPENDENCY_NORMAL &&
3003  pg_depend->classid == ExtensionRelationId)
3004  {
3005  char *depextname = get_extension_name(pg_depend->objid);
3006  ExtensionControlFile *dcontrol;
3007  ListCell *lc;
3008 
3009  dcontrol = read_extension_control_file(depextname);
3010  foreach(lc, dcontrol->no_relocate)
3011  {
3012  char *nrextname = (char *) lfirst(lc);
3013 
3014  if (strcmp(nrextname, NameStr(extForm->extname)) == 0)
3015  {
3016  ereport(ERROR,
3017  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
3018  errmsg("cannot SET SCHEMA of extension \"%s\" because other extensions prevent it",
3019  NameStr(extForm->extname)),
3020  errdetail("Extension \"%s\" requests no relocation of extension \"%s\".",
3021  depextname,
3022  NameStr(extForm->extname))));
3023  }
3024  }
3025  }
3026 
3027  /*
3028  * Otherwise, ignore non-membership dependencies. (Currently, the
3029  * only other case we could see here is a normal dependency from
3030  * another extension.)
3031  */
3032  if (pg_depend->deptype != DEPENDENCY_EXTENSION)
3033  continue;
3034 
3035  dep.classId = pg_depend->classid;
3036  dep.objectId = pg_depend->objid;
3037  dep.objectSubId = pg_depend->objsubid;
3038 
3039  if (dep.objectSubId != 0) /* should not happen */
3040  elog(ERROR, "extension should not have a sub-object dependency");
3041 
3042  /* Relocate the object */
3043  dep_oldNspOid = AlterObjectNamespace_oid(dep.classId,
3044  dep.objectId,
3045  nspOid,
3046  objsMoved);
3047 
3048  /*
3049  * If not all the objects had the same old namespace (ignoring any
3050  * that are not in namespaces or are dependent types), complain.
3051  */
3052  if (dep_oldNspOid != InvalidOid && dep_oldNspOid != oldNspOid)
3053  ereport(ERROR,
3054  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
3055  errmsg("extension \"%s\" does not support SET SCHEMA",
3056  NameStr(extForm->extname)),
3057  errdetail("%s is not in the extension's schema \"%s\"",
3058  getObjectDescription(&dep, false),
3059  get_namespace_name(oldNspOid))));
3060  }
3061 
3062  /* report old schema, if caller wants it */
3063  if (oldschema)
3064  *oldschema = oldNspOid;
3065 
3066  systable_endscan(depScan);
3067 
3069 
3070  /* Now adjust pg_extension.extnamespace */
3071  extForm->extnamespace = nspOid;
3072 
3073  CatalogTupleUpdate(extRel, &extTup->t_self, extTup);
3074 
3075  table_close(extRel, RowExclusiveLock);
3076 
3077  /* update dependency to point to the new schema */
3078  if (changeDependencyFor(ExtensionRelationId, extensionOid,
3079  NamespaceRelationId, oldNspOid, nspOid) != 1)
3080  elog(ERROR, "could not change schema dependency for extension %s",
3081  NameStr(extForm->extname));
3082 
3083  InvokeObjectPostAlterHook(ExtensionRelationId, extensionOid, 0);
3084 
3085  ObjectAddressSet(extAddr, ExtensionRelationId, extensionOid);
3086 
3087  return extAddr;
3088 }
AclResult
Definition: acl.h:182
@ ACLCHECK_OK
Definition: acl.h:183
@ ACLCHECK_NOT_OWNER
Definition: acl.h:185
void aclcheck_error(AclResult aclerr, ObjectType objtype, const char *objectname)
Definition: aclchk.c:2703
AclResult object_aclcheck(Oid classid, Oid objectid, Oid roleid, AclMode mode)
Definition: aclchk.c:3891
bool object_ownercheck(Oid classid, Oid objectid, Oid roleid)
Definition: aclchk.c:4145
Oid AlterObjectNamespace_oid(Oid classId, Oid objid, Oid nspOid, ObjectAddresses *objsMoved)
Definition: alter.c:613
#define NameStr(name)
Definition: c.h:737
ObjectAddresses * new_object_addresses(void)
Definition: dependency.c:2487
@ DEPENDENCY_EXTENSION
Definition: dependency.h:38
@ DEPENDENCY_NORMAL
Definition: dependency.h:33
int errdetail(const char *fmt,...)
Definition: elog.c:1203
int errcode(int sqlerrcode)
Definition: elog.c:853
int errmsg(const char *fmt,...)
Definition: elog.c:1070
#define ERROR
Definition: elog.h:39
#define elog(elevel,...)
Definition: elog.h:225
#define ereport(elevel,...)
Definition: elog.h:149
static ExtensionControlFile * read_extension_control_file(const char *extname)
Definition: extension.c:604
Oid get_extension_oid(const char *extname, bool missing_ok)
Definition: extension.c:158
char * get_extension_name(Oid ext_oid)
Definition: extension.c:180
void systable_endscan(SysScanDesc sysscan)
Definition: genam.c:604
HeapTuple systable_getnext(SysScanDesc sysscan)
Definition: genam.c:511
SysScanDesc systable_beginscan(Relation heapRelation, Oid indexId, bool indexOK, Snapshot snapshot, int nkeys, ScanKey key)
Definition: genam.c:387
HeapTuple heap_copytuple(HeapTuple tuple)
Definition: heaptuple.c:776
#define HeapTupleIsValid(tuple)
Definition: htup.h:78
#define GETSTRUCT(TUP)
Definition: htup_details.h:653
void CatalogTupleUpdate(Relation heapRel, ItemPointer otid, HeapTuple tup)
Definition: indexing.c:313
#define AccessShareLock
Definition: lockdefs.h:36
#define RowExclusiveLock
Definition: lockdefs.h:38
char * get_namespace_name(Oid nspid)
Definition: lsyscache.c:3366
Oid GetUserId(void)
Definition: miscinit.c:514
Oid LookupCreationNamespace(const char *nspname)
Definition: namespace.c:3428
#define InvokeObjectPostAlterHook(classId, objectId, subId)
Definition: objectaccess.h:197
char * getObjectDescription(const ObjectAddress *object, bool missing_ok)
const ObjectAddress InvalidObjectAddress
#define ObjectAddressSet(addr, class_id, object_id)
Definition: objectaddress.h:40
@ OBJECT_SCHEMA
Definition: parsenodes.h:2294
@ OBJECT_EXTENSION
Definition: parsenodes.h:2273
#define ACL_CREATE
Definition: parsenodes.h:85
long changeDependencyFor(Oid classId, Oid objectId, Oid refClassId, Oid oldRefObjectId, Oid newRefObjectId)
Definition: pg_depend.c:458
Oid getExtensionOfObject(Oid classId, Oid objectId)
Definition: pg_depend.c:733
FormData_pg_depend * Form_pg_depend
Definition: pg_depend.h:72
FormData_pg_extension * Form_pg_extension
Definition: pg_extension.h:52
#define lfirst(lc)
Definition: pg_list.h:172
static Datum ObjectIdGetDatum(Oid X)
Definition: postgres.h:252
#define InvalidOid
Definition: postgres_ext.h:36
unsigned int Oid
Definition: postgres_ext.h:31
void ScanKeyInit(ScanKey entry, AttrNumber attributeNumber, StrategyNumber strategy, RegProcedure procedure, Datum argument)
Definition: scankey.c:76
void relation_close(Relation relation, LOCKMODE lockmode)
Definition: relation.c:205
#define BTEqualStrategyNumber
Definition: stratnum.h:31
ItemPointerData t_self
Definition: htup.h:65
void table_close(Relation relation, LOCKMODE lockmode)
Definition: table.c:126
Relation table_open(Oid relationId, LOCKMODE lockmode)
Definition: table.c:40

References AccessShareLock, ACL_CREATE, aclcheck_error(), ACLCHECK_NOT_OWNER, ACLCHECK_OK, AlterObjectNamespace_oid(), BTEqualStrategyNumber, CatalogTupleUpdate(), changeDependencyFor(), ObjectAddress::classId, DEPENDENCY_EXTENSION, DEPENDENCY_NORMAL, elog, ereport, errcode(), errdetail(), errmsg(), ERROR, get_extension_name(), get_extension_oid(), get_namespace_name(), getExtensionOfObject(), getObjectDescription(), GETSTRUCT, GetUserId(), heap_copytuple(), HeapTupleIsValid, InvalidObjectAddress, InvalidOid, InvokeObjectPostAlterHook, sort-test::key, lfirst, LookupCreationNamespace(), NameStr, new_object_addresses(), ExtensionControlFile::no_relocate, object_aclcheck(), OBJECT_EXTENSION, object_ownercheck(), OBJECT_SCHEMA, ObjectAddressSet, ObjectAddress::objectId, ObjectIdGetDatum(), ObjectAddress::objectSubId, read_extension_control_file(), relation_close(), RowExclusiveLock, ScanKeyInit(), systable_beginscan(), systable_endscan(), systable_getnext(), HeapTupleData::t_self, table_close(), and table_open().

Referenced by ExecAlterObjectSchemaStmt().

◆ ApplyExtensionUpdates()

static void ApplyExtensionUpdates ( Oid  extensionOid,
ExtensionControlFile pcontrol,
const char *  initialVersion,
List updateVersions,
char *  origSchemaName,
bool  cascade,
bool  is_create 
)
static

Definition at line 3241 of file extension.c.

3248 {
3249  const char *oldVersionName = initialVersion;
3250  ListCell *lcv;
3251 
3252  foreach(lcv, updateVersions)
3253  {
3254  char *versionName = (char *) lfirst(lcv);
3255  ExtensionControlFile *control;
3256  char *schemaName;
3257  Oid schemaOid;
3258  List *requiredExtensions;
3259  List *requiredSchemas;
3260  Relation extRel;
3261  ScanKeyData key[1];
3262  SysScanDesc extScan;
3263  HeapTuple extTup;
3264  Form_pg_extension extForm;
3265  Datum values[Natts_pg_extension];
3266  bool nulls[Natts_pg_extension];
3267  bool repl[Natts_pg_extension];
3268  ObjectAddress myself;
3269  ListCell *lc;
3270 
3271  /*
3272  * Fetch parameters for specific version (pcontrol is not changed)
3273  */
3274  control = read_extension_aux_control_file(pcontrol, versionName);
3275 
3276  /* Find the pg_extension tuple */
3277  extRel = table_open(ExtensionRelationId, RowExclusiveLock);
3278 
3279  ScanKeyInit(&key[0],
3280  Anum_pg_extension_oid,
3281  BTEqualStrategyNumber, F_OIDEQ,
3282  ObjectIdGetDatum(extensionOid));
3283 
3284  extScan = systable_beginscan(extRel, ExtensionOidIndexId, true,
3285  NULL, 1, key);
3286 
3287  extTup = systable_getnext(extScan);
3288 
3289  if (!HeapTupleIsValid(extTup)) /* should not happen */
3290  elog(ERROR, "could not find tuple for extension %u",
3291  extensionOid);
3292 
3293  extForm = (Form_pg_extension) GETSTRUCT(extTup);
3294 
3295  /*
3296  * Determine the target schema (set by original install)
3297  */
3298  schemaOid = extForm->extnamespace;
3299  schemaName = get_namespace_name(schemaOid);
3300 
3301  /*
3302  * Modify extrelocatable and extversion in the pg_extension tuple
3303  */
3304  memset(values, 0, sizeof(values));
3305  memset(nulls, 0, sizeof(nulls));
3306  memset(repl, 0, sizeof(repl));
3307 
3308  values[Anum_pg_extension_extrelocatable - 1] =
3309  BoolGetDatum(control->relocatable);
3310  repl[Anum_pg_extension_extrelocatable - 1] = true;
3311  values[Anum_pg_extension_extversion - 1] =
3312  CStringGetTextDatum(versionName);
3313  repl[Anum_pg_extension_extversion - 1] = true;
3314 
3315  extTup = heap_modify_tuple(extTup, RelationGetDescr(extRel),
3316  values, nulls, repl);
3317 
3318  CatalogTupleUpdate(extRel, &extTup->t_self, extTup);
3319 
3320  systable_endscan(extScan);
3321 
3322  table_close(extRel, RowExclusiveLock);
3323 
3324  /*
3325  * Look up the prerequisite extensions for this version, install them
3326  * if necessary, and build lists of their OIDs and the OIDs of their
3327  * target schemas.
3328  */
3329  requiredExtensions = NIL;
3330  requiredSchemas = NIL;
3331  foreach(lc, control->requires)
3332  {
3333  char *curreq = (char *) lfirst(lc);
3334  Oid reqext;
3335  Oid reqschema;
3336 
3337  reqext = get_required_extension(curreq,
3338  control->name,
3339  origSchemaName,
3340  cascade,
3341  NIL,
3342  is_create);
3343  reqschema = get_extension_schema(reqext);
3344  requiredExtensions = lappend_oid(requiredExtensions, reqext);
3345  requiredSchemas = lappend_oid(requiredSchemas, reqschema);
3346  }
3347 
3348  /*
3349  * Remove and recreate dependencies on prerequisite extensions
3350  */
3351  deleteDependencyRecordsForClass(ExtensionRelationId, extensionOid,
3352  ExtensionRelationId,
3354 
3355  myself.classId = ExtensionRelationId;
3356  myself.objectId = extensionOid;
3357  myself.objectSubId = 0;
3358 
3359  foreach(lc, requiredExtensions)
3360  {
3361  Oid reqext = lfirst_oid(lc);
3362  ObjectAddress otherext;
3363 
3364  otherext.classId = ExtensionRelationId;
3365  otherext.objectId = reqext;
3366  otherext.objectSubId = 0;
3367 
3368  recordDependencyOn(&myself, &otherext, DEPENDENCY_NORMAL);
3369  }
3370 
3371  InvokeObjectPostAlterHook(ExtensionRelationId, extensionOid, 0);
3372 
3373  /*
3374  * Finally, execute the update script file
3375  */
3376  execute_extension_script(extensionOid, control,
3377  oldVersionName, versionName,
3378  requiredSchemas,
3379  schemaName, schemaOid);
3380 
3381  /*
3382  * Update prior-version name and loop around. Since
3383  * execute_sql_string did a final CommandCounterIncrement, we can
3384  * update the pg_extension row again.
3385  */
3386  oldVersionName = versionName;
3387  }
3388 }
static Datum values[MAXATTR]
Definition: bootstrap.c:150
#define CStringGetTextDatum(s)
Definition: builtins.h:97
Oid get_extension_schema(Oid ext_oid)
Definition: extension.c:202
static Oid get_required_extension(char *reqExtensionName, char *extensionName, char *origSchemaName, bool cascade, List *parents, bool is_create)
Definition: extension.c:1804
static void execute_extension_script(Oid extensionOid, ExtensionControlFile *control, const char *from_version, const char *version, List *requiredSchemas, const char *schemaName, Oid schemaOid)
Definition: extension.c:977
static ExtensionControlFile * read_extension_aux_control_file(const ExtensionControlFile *pcontrol, const char *version)
Definition: extension.c:633
HeapTuple heap_modify_tuple(HeapTuple tuple, TupleDesc tupleDesc, const Datum *replValues, const bool *replIsnull, const bool *doReplace)
Definition: heaptuple.c:1209
List * lappend_oid(List *list, Oid datum)
Definition: list.c:375
void recordDependencyOn(const ObjectAddress *depender, const ObjectAddress *referenced, DependencyType behavior)
Definition: pg_depend.c:46
long deleteDependencyRecordsForClass(Oid classId, Oid objectId, Oid refclassId, char deptype)
Definition: pg_depend.c:352
#define NIL
Definition: pg_list.h:68
#define lfirst_oid(lc)
Definition: pg_list.h:174
uintptr_t Datum
Definition: postgres.h:64
static Datum BoolGetDatum(bool X)
Definition: postgres.h:102
#define RelationGetDescr(relation)
Definition: rel.h:531
Definition: pg_list.h:54

References BoolGetDatum(), BTEqualStrategyNumber, CatalogTupleUpdate(), ObjectAddress::classId, CStringGetTextDatum, deleteDependencyRecordsForClass(), DEPENDENCY_NORMAL, elog, ERROR, execute_extension_script(), get_extension_schema(), get_namespace_name(), get_required_extension(), GETSTRUCT, heap_modify_tuple(), HeapTupleIsValid, InvokeObjectPostAlterHook, sort-test::key, lappend_oid(), lfirst, lfirst_oid, ExtensionControlFile::name, NIL, ObjectAddress::objectId, ObjectIdGetDatum(), ObjectAddress::objectSubId, read_extension_aux_control_file(), recordDependencyOn(), RelationGetDescr, ExtensionControlFile::relocatable, ExtensionControlFile::requires, RowExclusiveLock, ScanKeyInit(), systable_beginscan(), systable_endscan(), systable_getnext(), HeapTupleData::t_self, table_close(), table_open(), and values.

Referenced by CreateExtensionInternal(), and ExecAlterExtensionStmt().

◆ check_valid_extension_name()

static void check_valid_extension_name ( const char *  extensionname)
static

Definition at line 222 of file extension.c.

223 {
224  int namelen = strlen(extensionname);
225 
226  /*
227  * Disallow empty names (the parser rejects empty identifiers anyway, but
228  * let's check).
229  */
230  if (namelen == 0)
231  ereport(ERROR,
232  (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
233  errmsg("invalid extension name: \"%s\"", extensionname),
234  errdetail("Extension names must not be empty.")));
235 
236  /*
237  * No double dashes, since that would make script filenames ambiguous.
238  */
239  if (strstr(extensionname, "--"))
240  ereport(ERROR,
241  (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
242  errmsg("invalid extension name: \"%s\"", extensionname),
243  errdetail("Extension names must not contain \"--\".")));
244 
245  /*
246  * No leading or trailing dash either. (We could probably allow this, but
247  * it would require much care in filename parsing and would make filenames
248  * visually if not formally ambiguous. Since there's no real-world use
249  * case, let's just forbid it.)
250  */
251  if (extensionname[0] == '-' || extensionname[namelen - 1] == '-')
252  ereport(ERROR,
253  (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
254  errmsg("invalid extension name: \"%s\"", extensionname),
255  errdetail("Extension names must not begin or end with \"-\".")));
256 
257  /*
258  * No directory separators either (this is sufficient to prevent ".."
259  * style attacks).
260  */
261  if (first_dir_separator(extensionname) != NULL)
262  ereport(ERROR,
263  (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
264  errmsg("invalid extension name: \"%s\"", extensionname),
265  errdetail("Extension names must not contain directory separator characters.")));
266 }
char * first_dir_separator(const char *filename)
Definition: path.c:105

References ereport, errcode(), errdetail(), errmsg(), ERROR, and first_dir_separator().

Referenced by CreateExtension(), get_required_extension(), and pg_extension_update_paths().

◆ check_valid_version_name()

static void check_valid_version_name ( const char *  versionname)
static

Definition at line 269 of file extension.c.

270 {
271  int namelen = strlen(versionname);
272 
273  /*
274  * Disallow empty names (we could possibly allow this, but there seems
275  * little point).
276  */
277  if (namelen == 0)
278  ereport(ERROR,
279  (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
280  errmsg("invalid extension version name: \"%s\"", versionname),
281  errdetail("Version names must not be empty.")));
282 
283  /*
284  * No double dashes, since that would make script filenames ambiguous.
285  */
286  if (strstr(versionname, "--"))
287  ereport(ERROR,
288  (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
289  errmsg("invalid extension version name: \"%s\"", versionname),
290  errdetail("Version names must not contain \"--\".")));
291 
292  /*
293  * No leading or trailing dash either.
294  */
295  if (versionname[0] == '-' || versionname[namelen - 1] == '-')
296  ereport(ERROR,
297  (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
298  errmsg("invalid extension version name: \"%s\"", versionname),
299  errdetail("Version names must not begin or end with \"-\".")));
300 
301  /*
302  * No directory separators either (this is sufficient to prevent ".."
303  * style attacks).
304  */
305  if (first_dir_separator(versionname) != NULL)
306  ereport(ERROR,
307  (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
308  errmsg("invalid extension version name: \"%s\"", versionname),
309  errdetail("Version names must not contain directory separator characters.")));
310 }

References ereport, errcode(), errdetail(), errmsg(), ERROR, and first_dir_separator().

Referenced by CreateExtensionInternal(), and ExecAlterExtensionStmt().

◆ convert_requires_to_datum()

static Datum convert_requires_to_datum ( List requires)
static

Definition at line 2420 of file extension.c.

2421 {
2422  Datum *datums;
2423  int ndatums;
2424  ArrayType *a;
2425  ListCell *lc;
2426 
2427  ndatums = list_length(requires);
2428  datums = (Datum *) palloc(ndatums * sizeof(Datum));
2429  ndatums = 0;
2430  foreach(lc, requires)
2431  {
2432  char *curreq = (char *) lfirst(lc);
2433 
2434  datums[ndatums++] =
2436  }
2437  a = construct_array_builtin(datums, ndatums, NAMEOID);
2438  return PointerGetDatum(a);
2439 }
ArrayType * construct_array_builtin(Datum *elems, int nelems, Oid elmtype)
Definition: arrayfuncs.c:3381
#define DirectFunctionCall1(func, arg1)
Definition: fmgr.h:641
int a
Definition: isn.c:69
void * palloc(Size size)
Definition: mcxt.c:1317
Datum namein(PG_FUNCTION_ARGS)
Definition: name.c:48
static int list_length(const List *l)
Definition: pg_list.h:152
static Datum PointerGetDatum(const void *X)
Definition: postgres.h:322
static Datum CStringGetDatum(const char *X)
Definition: postgres.h:350

References a, construct_array_builtin(), CStringGetDatum(), DirectFunctionCall1, lfirst, list_length(), namein(), palloc(), and PointerGetDatum().

Referenced by get_available_versions_for_extension().

◆ CreateExtension()

ObjectAddress CreateExtension ( ParseState pstate,
CreateExtensionStmt stmt 
)

Definition at line 1875 of file extension.c.

1876 {
1877  DefElem *d_schema = NULL;
1878  DefElem *d_new_version = NULL;
1879  DefElem *d_cascade = NULL;
1880  char *schemaName = NULL;
1881  char *versionName = NULL;
1882  bool cascade = false;
1883  ListCell *lc;
1884 
1885  /* Check extension name validity before any filesystem access */
1886  check_valid_extension_name(stmt->extname);
1887 
1888  /*
1889  * Check for duplicate extension name. The unique index on
1890  * pg_extension.extname would catch this anyway, and serves as a backstop
1891  * in case of race conditions; but this is a friendlier error message, and
1892  * besides we need a check to support IF NOT EXISTS.
1893  */
1894  if (get_extension_oid(stmt->extname, true) != InvalidOid)
1895  {
1896  if (stmt->if_not_exists)
1897  {
1898  ereport(NOTICE,
1900  errmsg("extension \"%s\" already exists, skipping",
1901  stmt->extname)));
1902  return InvalidObjectAddress;
1903  }
1904  else
1905  ereport(ERROR,
1907  errmsg("extension \"%s\" already exists",
1908  stmt->extname)));
1909  }
1910 
1911  /*
1912  * We use global variables to track the extension being created, so we can
1913  * create only one extension at the same time.
1914  */
1915  if (creating_extension)
1916  ereport(ERROR,
1917  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1918  errmsg("nested CREATE EXTENSION is not supported")));
1919 
1920  /* Deconstruct the statement option list */
1921  foreach(lc, stmt->options)
1922  {
1923  DefElem *defel = (DefElem *) lfirst(lc);
1924 
1925  if (strcmp(defel->defname, "schema") == 0)
1926  {
1927  if (d_schema)
1928  errorConflictingDefElem(defel, pstate);
1929  d_schema = defel;
1930  schemaName = defGetString(d_schema);
1931  }
1932  else if (strcmp(defel->defname, "new_version") == 0)
1933  {
1934  if (d_new_version)
1935  errorConflictingDefElem(defel, pstate);
1936  d_new_version = defel;
1937  versionName = defGetString(d_new_version);
1938  }
1939  else if (strcmp(defel->defname, "cascade") == 0)
1940  {
1941  if (d_cascade)
1942  errorConflictingDefElem(defel, pstate);
1943  d_cascade = defel;
1944  cascade = defGetBoolean(d_cascade);
1945  }
1946  else
1947  elog(ERROR, "unrecognized option: %s", defel->defname);
1948  }
1949 
1950  /* Call CreateExtensionInternal to do the real work. */
1951  return CreateExtensionInternal(stmt->extname,
1952  schemaName,
1953  versionName,
1954  cascade,
1955  NIL,
1956  true);
1957 }
bool defGetBoolean(DefElem *def)
Definition: define.c:107
char * defGetString(DefElem *def)
Definition: define.c:48
void errorConflictingDefElem(DefElem *defel, ParseState *pstate)
Definition: define.c:384
#define NOTICE
Definition: elog.h:35
static void check_valid_extension_name(const char *extensionname)
Definition: extension.c:222
bool creating_extension
Definition: extension.c:73
static ObjectAddress CreateExtensionInternal(char *extensionName, char *schemaName, const char *versionName, bool cascade, List *parents, bool is_create)
Definition: extension.c:1565
#define stmt
Definition: indent_codes.h:59
#define ERRCODE_DUPLICATE_OBJECT
Definition: streamutil.c:32
char * defname
Definition: parsenodes.h:817

References check_valid_extension_name(), CreateExtensionInternal(), creating_extension, defGetBoolean(), defGetString(), DefElem::defname, elog, ereport, errcode(), ERRCODE_DUPLICATE_OBJECT, errmsg(), ERROR, errorConflictingDefElem(), get_extension_oid(), InvalidObjectAddress, InvalidOid, lfirst, NIL, NOTICE, and stmt.

Referenced by ProcessUtilitySlow().

◆ CreateExtensionInternal()

static ObjectAddress CreateExtensionInternal ( char *  extensionName,
char *  schemaName,
const char *  versionName,
bool  cascade,
List parents,
bool  is_create 
)
static

Definition at line 1565 of file extension.c.

1571 {
1572  char *origSchemaName = schemaName;
1573  Oid schemaOid = InvalidOid;
1574  Oid extowner = GetUserId();
1575  ExtensionControlFile *pcontrol;
1576  ExtensionControlFile *control;
1577  char *filename;
1578  struct stat fst;
1579  List *updateVersions;
1580  List *requiredExtensions;
1581  List *requiredSchemas;
1582  Oid extensionOid;
1583  ObjectAddress address;
1584  ListCell *lc;
1585 
1586  /*
1587  * Read the primary control file. Note we assume that it does not contain
1588  * any non-ASCII data, so there is no need to worry about encoding at this
1589  * point.
1590  */
1591  pcontrol = read_extension_control_file(extensionName);
1592 
1593  /*
1594  * Determine the version to install
1595  */
1596  if (versionName == NULL)
1597  {
1598  if (pcontrol->default_version)
1599  versionName = pcontrol->default_version;
1600  else
1601  ereport(ERROR,
1602  (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
1603  errmsg("version to install must be specified")));
1604  }
1605  check_valid_version_name(versionName);
1606 
1607  /*
1608  * Figure out which script(s) we need to run to install the desired
1609  * version of the extension. If we do not have a script that directly
1610  * does what is needed, we try to find a sequence of update scripts that
1611  * will get us there.
1612  */
1613  filename = get_extension_script_filename(pcontrol, NULL, versionName);
1614  if (stat(filename, &fst) == 0)
1615  {
1616  /* Easy, no extra scripts */
1617  updateVersions = NIL;
1618  }
1619  else
1620  {
1621  /* Look for best way to install this version */
1622  List *evi_list;
1623  ExtensionVersionInfo *evi_start;
1624  ExtensionVersionInfo *evi_target;
1625 
1626  /* Extract the version update graph from the script directory */
1627  evi_list = get_ext_ver_list(pcontrol);
1628 
1629  /* Identify the target version */
1630  evi_target = get_ext_ver_info(versionName, &evi_list);
1631 
1632  /* Identify best path to reach target */
1633  evi_start = find_install_path(evi_list, evi_target,
1634  &updateVersions);
1635 
1636  /* Fail if no path ... */
1637  if (evi_start == NULL)
1638  ereport(ERROR,
1639  (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
1640  errmsg("extension \"%s\" has no installation script nor update path for version \"%s\"",
1641  pcontrol->name, versionName)));
1642 
1643  /* Otherwise, install best starting point and then upgrade */
1644  versionName = evi_start->name;
1645  }
1646 
1647  /*
1648  * Fetch control parameters for installation target version
1649  */
1650  control = read_extension_aux_control_file(pcontrol, versionName);
1651 
1652  /*
1653  * Determine the target schema to install the extension into
1654  */
1655  if (schemaName)
1656  {
1657  /* If the user is giving us the schema name, it must exist already. */
1658  schemaOid = get_namespace_oid(schemaName, false);
1659  }
1660 
1661  if (control->schema != NULL)
1662  {
1663  /*
1664  * The extension is not relocatable and the author gave us a schema
1665  * for it.
1666  *
1667  * Unless CASCADE parameter was given, it's an error to give a schema
1668  * different from control->schema if control->schema is specified.
1669  */
1670  if (schemaName && strcmp(control->schema, schemaName) != 0 &&
1671  !cascade)
1672  ereport(ERROR,
1673  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1674  errmsg("extension \"%s\" must be installed in schema \"%s\"",
1675  control->name,
1676  control->schema)));
1677 
1678  /* Always use the schema from control file for current extension. */
1679  schemaName = control->schema;
1680 
1681  /* Find or create the schema in case it does not exist. */
1682  schemaOid = get_namespace_oid(schemaName, true);
1683 
1684  if (!OidIsValid(schemaOid))
1685  {
1687 
1688  csstmt->schemaname = schemaName;
1689  csstmt->authrole = NULL; /* will be created by current user */
1690  csstmt->schemaElts = NIL;
1691  csstmt->if_not_exists = false;
1692  CreateSchemaCommand(csstmt, "(generated CREATE SCHEMA command)",
1693  -1, -1);
1694 
1695  /*
1696  * CreateSchemaCommand includes CommandCounterIncrement, so new
1697  * schema is now visible.
1698  */
1699  schemaOid = get_namespace_oid(schemaName, false);
1700  }
1701  }
1702  else if (!OidIsValid(schemaOid))
1703  {
1704  /*
1705  * Neither user nor author of the extension specified schema; use the
1706  * current default creation namespace, which is the first explicit
1707  * entry in the search_path.
1708  */
1709  List *search_path = fetch_search_path(false);
1710 
1711  if (search_path == NIL) /* nothing valid in search_path? */
1712  ereport(ERROR,
1713  (errcode(ERRCODE_UNDEFINED_SCHEMA),
1714  errmsg("no schema has been selected to create in")));
1715  schemaOid = linitial_oid(search_path);
1716  schemaName = get_namespace_name(schemaOid);
1717  if (schemaName == NULL) /* recently-deleted namespace? */
1718  ereport(ERROR,
1719  (errcode(ERRCODE_UNDEFINED_SCHEMA),
1720  errmsg("no schema has been selected to create in")));
1721 
1722  list_free(search_path);
1723  }
1724 
1725  /*
1726  * Make note if a temporary namespace has been accessed in this
1727  * transaction.
1728  */
1729  if (isTempNamespace(schemaOid))
1731 
1732  /*
1733  * We don't check creation rights on the target namespace here. If the
1734  * extension script actually creates any objects there, it will fail if
1735  * the user doesn't have such permissions. But there are cases such as
1736  * procedural languages where it's convenient to set schema = pg_catalog
1737  * yet we don't want to restrict the command to users with ACL_CREATE for
1738  * pg_catalog.
1739  */
1740 
1741  /*
1742  * Look up the prerequisite extensions, install them if necessary, and
1743  * build lists of their OIDs and the OIDs of their target schemas.
1744  */
1745  requiredExtensions = NIL;
1746  requiredSchemas = NIL;
1747  foreach(lc, control->requires)
1748  {
1749  char *curreq = (char *) lfirst(lc);
1750  Oid reqext;
1751  Oid reqschema;
1752 
1753  reqext = get_required_extension(curreq,
1754  extensionName,
1755  origSchemaName,
1756  cascade,
1757  parents,
1758  is_create);
1759  reqschema = get_extension_schema(reqext);
1760  requiredExtensions = lappend_oid(requiredExtensions, reqext);
1761  requiredSchemas = lappend_oid(requiredSchemas, reqschema);
1762  }
1763 
1764  /*
1765  * Insert new tuple into pg_extension, and create dependency entries.
1766  */
1767  address = InsertExtensionTuple(control->name, extowner,
1768  schemaOid, control->relocatable,
1769  versionName,
1770  PointerGetDatum(NULL),
1771  PointerGetDatum(NULL),
1772  requiredExtensions);
1773  extensionOid = address.objectId;
1774 
1775  /*
1776  * Apply any control-file comment on extension
1777  */
1778  if (control->comment != NULL)
1779  CreateComments(extensionOid, ExtensionRelationId, 0, control->comment);
1780 
1781  /*
1782  * Execute the installation script file
1783  */
1784  execute_extension_script(extensionOid, control,
1785  NULL, versionName,
1786  requiredSchemas,
1787  schemaName, schemaOid);
1788 
1789  /*
1790  * If additional update scripts have to be executed, apply the updates as
1791  * though a series of ALTER EXTENSION UPDATE commands were given
1792  */
1793  ApplyExtensionUpdates(extensionOid, pcontrol,
1794  versionName, updateVersions,
1795  origSchemaName, cascade, is_create);
1796 
1797  return address;
1798 }
#define OidIsValid(objectId)
Definition: c.h:766
void CreateComments(Oid oid, Oid classoid, int32 subid, const char *comment)
Definition: comment.c:143
static ExtensionVersionInfo * get_ext_ver_info(const char *versionname, List **evi_list)
Definition: extension.c:1250
ObjectAddress InsertExtensionTuple(const char *extName, Oid extOwner, Oid schemaOid, bool relocatable, const char *extVersion, Datum extConfig, Datum extCondition, List *requiredExtensions)
Definition: extension.c:1973
static void check_valid_version_name(const char *versionname)
Definition: extension.c:269
static char * get_extension_script_filename(ExtensionControlFile *control, const char *from_version, const char *version)
Definition: extension.c:400
static List * get_ext_ver_list(ExtensionControlFile *control)
Definition: extension.c:1311
static ExtensionVersionInfo * find_install_path(List *evi_list, ExtensionVersionInfo *evi_target, List **best_path)
Definition: extension.c:1510
static void ApplyExtensionUpdates(Oid extensionOid, ExtensionControlFile *pcontrol, const char *initialVersion, List *updateVersions, char *origSchemaName, bool cascade, bool is_create)
Definition: extension.c:3241
void list_free(List *list)
Definition: list.c:1546
bool isTempNamespace(Oid namespaceId)
Definition: namespace.c:3649
List * fetch_search_path(bool includeImplicit)
Definition: namespace.c:4819
Oid get_namespace_oid(const char *nspname, bool missing_ok)
Definition: namespace.c:3535
#define makeNode(_type_)
Definition: nodes.h:155
static char * filename
Definition: pg_dumpall.c:119
#define linitial_oid(l)
Definition: pg_list.h:180
Oid CreateSchemaCommand(CreateSchemaStmt *stmt, const char *queryString, int stmt_location, int stmt_len)
Definition: schemacmds.c:52
RoleSpec * authrole
Definition: parsenodes.h:2324
char * default_version
Definition: extension.c:83
#define stat
Definition: win32_port.h:284
int MyXactFlags
Definition: xact.c:135
#define XACT_FLAGS_ACCESSEDTEMPNAMESPACE
Definition: xact.h:102

References ApplyExtensionUpdates(), CreateSchemaStmt::authrole, check_valid_version_name(), ExtensionControlFile::comment, CreateComments(), CreateSchemaCommand(), ExtensionControlFile::default_version, ereport, errcode(), errmsg(), ERROR, execute_extension_script(), fetch_search_path(), filename, find_install_path(), get_ext_ver_info(), get_ext_ver_list(), get_extension_schema(), get_extension_script_filename(), get_namespace_name(), get_namespace_oid(), get_required_extension(), GetUserId(), CreateSchemaStmt::if_not_exists, InsertExtensionTuple(), InvalidOid, isTempNamespace(), lappend_oid(), lfirst, linitial_oid, list_free(), makeNode, MyXactFlags, ExtensionControlFile::name, ExtensionVersionInfo::name, NIL, ObjectAddress::objectId, OidIsValid, PointerGetDatum(), read_extension_aux_control_file(), read_extension_control_file(), ExtensionControlFile::relocatable, ExtensionControlFile::requires, ExtensionControlFile::schema, CreateSchemaStmt::schemaElts, CreateSchemaStmt::schemaname, stat, and XACT_FLAGS_ACCESSEDTEMPNAMESPACE.

Referenced by CreateExtension(), and get_required_extension().

◆ ExecAlterExtensionContentsRecurse()

static void ExecAlterExtensionContentsRecurse ( AlterExtensionContentsStmt stmt,
ObjectAddress  extension,
ObjectAddress  object 
)
static

Definition at line 3485 of file extension.c.

3488 {
3489  Oid oldExtension;
3490 
3491  /*
3492  * Check existing extension membership.
3493  */
3494  oldExtension = getExtensionOfObject(object.classId, object.objectId);
3495 
3496  if (stmt->action > 0)
3497  {
3498  /*
3499  * ADD, so complain if object is already attached to some extension.
3500  */
3501  if (OidIsValid(oldExtension))
3502  ereport(ERROR,
3503  (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
3504  errmsg("%s is already a member of extension \"%s\"",
3505  getObjectDescription(&object, false),
3506  get_extension_name(oldExtension))));
3507 
3508  /*
3509  * Prevent a schema from being added to an extension if the schema
3510  * contains the extension. That would create a dependency loop.
3511  */
3512  if (object.classId == NamespaceRelationId &&
3513  object.objectId == get_extension_schema(extension.objectId))
3514  ereport(ERROR,
3515  (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
3516  errmsg("cannot add schema \"%s\" to extension \"%s\" "
3517  "because the schema contains the extension",
3518  get_namespace_name(object.objectId),
3519  stmt->extname)));
3520 
3521  /*
3522  * OK, add the dependency.
3523  */
3524  recordDependencyOn(&object, &extension, DEPENDENCY_EXTENSION);
3525 
3526  /*
3527  * Also record the initial ACL on the object, if any.
3528  *
3529  * Note that this will handle the object's ACLs, as well as any ACLs
3530  * on object subIds. (In other words, when the object is a table,
3531  * this will record the table's ACL and the ACLs for the columns on
3532  * the table, if any).
3533  */
3534  recordExtObjInitPriv(object.objectId, object.classId);
3535  }
3536  else
3537  {
3538  /*
3539  * DROP, so complain if it's not a member.
3540  */
3541  if (oldExtension != extension.objectId)
3542  ereport(ERROR,
3543  (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
3544  errmsg("%s is not a member of extension \"%s\"",
3545  getObjectDescription(&object, false),
3546  stmt->extname)));
3547 
3548  /*
3549  * OK, drop the dependency.
3550  */
3551  if (deleteDependencyRecordsForClass(object.classId, object.objectId,
3552  ExtensionRelationId,
3553  DEPENDENCY_EXTENSION) != 1)
3554  elog(ERROR, "unexpected number of extension dependency records");
3555 
3556  /*
3557  * If it's a relation, it might have an entry in the extension's
3558  * extconfig array, which we must remove.
3559  */
3560  if (object.classId == RelationRelationId)
3561  extension_config_remove(extension.objectId, object.objectId);
3562 
3563  /*
3564  * Remove all the initial ACLs, if any.
3565  *
3566  * Note that this will remove the object's ACLs, as well as any ACLs
3567  * on object subIds. (In other words, when the object is a table,
3568  * this will remove the table's ACL and the ACLs for the columns on
3569  * the table, if any).
3570  */
3571  removeExtObjInitPriv(object.objectId, object.classId);
3572  }
3573 
3574  /*
3575  * Recurse to any dependent objects; currently, this includes the array
3576  * type of a base type, the multirange type associated with a range type,
3577  * and the rowtype of a table.
3578  */
3579  if (object.classId == TypeRelationId)
3580  {
3581  ObjectAddress depobject;
3582 
3583  depobject.classId = TypeRelationId;
3584  depobject.objectSubId = 0;
3585 
3586  /* If it has an array type, update that too */
3587  depobject.objectId = get_array_type(object.objectId);
3588  if (OidIsValid(depobject.objectId))
3589  ExecAlterExtensionContentsRecurse(stmt, extension, depobject);
3590 
3591  /* If it is a range type, update the associated multirange too */
3592  if (type_is_range(object.objectId))
3593  {
3594  depobject.objectId = get_range_multirange(object.objectId);
3595  if (!OidIsValid(depobject.objectId))
3596  ereport(ERROR,
3597  (errcode(ERRCODE_UNDEFINED_OBJECT),
3598  errmsg("could not find multirange type for data type %s",
3599  format_type_be(object.objectId))));
3600  ExecAlterExtensionContentsRecurse(stmt, extension, depobject);
3601  }
3602  }
3603  if (object.classId == RelationRelationId)
3604  {
3605  ObjectAddress depobject;
3606 
3607  depobject.classId = TypeRelationId;
3608  depobject.objectSubId = 0;
3609 
3610  /* It might not have a rowtype, but if it does, update that */
3611  depobject.objectId = get_rel_type_id(object.objectId);
3612  if (OidIsValid(depobject.objectId))
3613  ExecAlterExtensionContentsRecurse(stmt, extension, depobject);
3614  }
3615 }
void recordExtObjInitPriv(Oid objoid, Oid classoid)
Definition: aclchk.c:4407
void removeExtObjInitPriv(Oid objoid, Oid classoid)
Definition: aclchk.c:4571
static void extension_config_remove(Oid extensionoid, Oid tableoid)
Definition: extension.c:2714
static void ExecAlterExtensionContentsRecurse(AlterExtensionContentsStmt *stmt, ObjectAddress extension, ObjectAddress object)
Definition: extension.c:3485
char * format_type_be(Oid type_oid)
Definition: format_type.c:343
bool type_is_range(Oid typid)
Definition: lsyscache.c:2688
Oid get_rel_type_id(Oid relid)
Definition: lsyscache.c:1979
Oid get_range_multirange(Oid rangeOid)
Definition: lsyscache.c:3458
Oid get_array_type(Oid typid)
Definition: lsyscache.c:2787

References ObjectAddress::classId, deleteDependencyRecordsForClass(), DEPENDENCY_EXTENSION, elog, ereport, errcode(), errmsg(), ERROR, extension_config_remove(), format_type_be(), get_array_type(), get_extension_name(), get_extension_schema(), get_namespace_name(), get_range_multirange(), get_rel_type_id(), getExtensionOfObject(), getObjectDescription(), ObjectAddress::objectId, ObjectAddress::objectSubId, OidIsValid, recordDependencyOn(), recordExtObjInitPriv(), removeExtObjInitPriv(), stmt, and type_is_range().

Referenced by ExecAlterExtensionContentsStmt().

◆ ExecAlterExtensionContentsStmt()

ObjectAddress ExecAlterExtensionContentsStmt ( AlterExtensionContentsStmt stmt,
ObjectAddress objAddr 
)

Definition at line 3399 of file extension.c.

3401 {
3402  ObjectAddress extension;
3403  ObjectAddress object;
3404  Relation relation;
3405 
3406  switch (stmt->objtype)
3407  {
3408  case OBJECT_DATABASE:
3409  case OBJECT_EXTENSION:
3410  case OBJECT_INDEX:
3411  case OBJECT_PUBLICATION:
3412  case OBJECT_ROLE:
3413  case OBJECT_STATISTIC_EXT:
3414  case OBJECT_SUBSCRIPTION:
3415  case OBJECT_TABLESPACE:
3416  ereport(ERROR,
3417  (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
3418  errmsg("cannot add an object of this type to an extension")));
3419  break;
3420  default:
3421  /* OK */
3422  break;
3423  }
3424 
3425  /*
3426  * Find the extension and acquire a lock on it, to ensure it doesn't get
3427  * dropped concurrently. A sharable lock seems sufficient: there's no
3428  * reason not to allow other sorts of manipulations, such as add/drop of
3429  * other objects, to occur concurrently. Concurrently adding/dropping the
3430  * *same* object would be bad, but we prevent that by using a non-sharable
3431  * lock on the individual object, below.
3432  */
3434  (Node *) makeString(stmt->extname),
3435  &relation, AccessShareLock, false);
3436 
3437  /* Permission check: must own extension */
3438  if (!object_ownercheck(ExtensionRelationId, extension.objectId, GetUserId()))
3440  stmt->extname);
3441 
3442  /*
3443  * Translate the parser representation that identifies the object into an
3444  * ObjectAddress. get_object_address() will throw an error if the object
3445  * does not exist, and will also acquire a lock on the object to guard
3446  * against concurrent DROP and ALTER EXTENSION ADD/DROP operations.
3447  */
3448  object = get_object_address(stmt->objtype, stmt->object,
3449  &relation, ShareUpdateExclusiveLock, false);
3450 
3451  Assert(object.objectSubId == 0);
3452  if (objAddr)
3453  *objAddr = object;
3454 
3455  /* Permission check: must own target object, too */
3456  check_object_ownership(GetUserId(), stmt->objtype, object,
3457  stmt->object, relation);
3458 
3459  /* Do the update, recursing to any dependent objects */
3460  ExecAlterExtensionContentsRecurse(stmt, extension, object);
3461 
3462  /* Finish up */
3463  InvokeObjectPostAlterHook(ExtensionRelationId, extension.objectId, 0);
3464 
3465  /*
3466  * If get_object_address() opened the relation for us, we close it to keep
3467  * the reference count correct - but we retain any locks acquired by
3468  * get_object_address() until commit time, to guard against concurrent
3469  * activity.
3470  */
3471  if (relation != NULL)
3472  relation_close(relation, NoLock);
3473 
3474  return extension;
3475 }
#define Assert(condition)
Definition: c.h:849
#define NoLock
Definition: lockdefs.h:34
#define ShareUpdateExclusiveLock
Definition: lockdefs.h:39
void check_object_ownership(Oid roleid, ObjectType objtype, ObjectAddress address, Node *object, Relation relation)
ObjectAddress get_object_address(ObjectType objtype, Node *object, Relation *relp, LOCKMODE lockmode, bool missing_ok)
@ OBJECT_TABLESPACE
Definition: parsenodes.h:2300
@ OBJECT_ROLE
Definition: parsenodes.h:2291
@ OBJECT_INDEX
Definition: parsenodes.h:2278
@ OBJECT_DATABASE
Definition: parsenodes.h:2267
@ OBJECT_PUBLICATION
Definition: parsenodes.h:2288
@ OBJECT_SUBSCRIPTION
Definition: parsenodes.h:2296
@ OBJECT_STATISTIC_EXT
Definition: parsenodes.h:2297
Definition: nodes.h:129
String * makeString(char *str)
Definition: value.c:63

References AccessShareLock, aclcheck_error(), ACLCHECK_NOT_OWNER, Assert, check_object_ownership(), ereport, errcode(), errmsg(), ERROR, ExecAlterExtensionContentsRecurse(), get_object_address(), GetUserId(), InvokeObjectPostAlterHook, makeString(), NoLock, OBJECT_DATABASE, OBJECT_EXTENSION, OBJECT_INDEX, object_ownercheck(), OBJECT_PUBLICATION, OBJECT_ROLE, OBJECT_STATISTIC_EXT, OBJECT_SUBSCRIPTION, OBJECT_TABLESPACE, ObjectAddress::objectId, relation_close(), ShareUpdateExclusiveLock, and stmt.

Referenced by ProcessUtilitySlow().

◆ ExecAlterExtensionStmt()

ObjectAddress ExecAlterExtensionStmt ( ParseState pstate,
AlterExtensionStmt stmt 
)

Definition at line 3094 of file extension.c.

3095 {
3096  DefElem *d_new_version = NULL;
3097  char *versionName;
3098  char *oldVersionName;
3099  ExtensionControlFile *control;
3100  Oid extensionOid;
3101  Relation extRel;
3102  ScanKeyData key[1];
3103  SysScanDesc extScan;
3104  HeapTuple extTup;
3105  List *updateVersions;
3106  Datum datum;
3107  bool isnull;
3108  ListCell *lc;
3109  ObjectAddress address;
3110 
3111  /*
3112  * We use global variables to track the extension being created, so we can
3113  * create/update only one extension at the same time.
3114  */
3115  if (creating_extension)
3116  ereport(ERROR,
3117  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
3118  errmsg("nested ALTER EXTENSION is not supported")));
3119 
3120  /*
3121  * Look up the extension --- it must already exist in pg_extension
3122  */
3123  extRel = table_open(ExtensionRelationId, AccessShareLock);
3124 
3125  ScanKeyInit(&key[0],
3126  Anum_pg_extension_extname,
3127  BTEqualStrategyNumber, F_NAMEEQ,
3128  CStringGetDatum(stmt->extname));
3129 
3130  extScan = systable_beginscan(extRel, ExtensionNameIndexId, true,
3131  NULL, 1, key);
3132 
3133  extTup = systable_getnext(extScan);
3134 
3135  if (!HeapTupleIsValid(extTup))
3136  ereport(ERROR,
3137  (errcode(ERRCODE_UNDEFINED_OBJECT),
3138  errmsg("extension \"%s\" does not exist",
3139  stmt->extname)));
3140 
3141  extensionOid = ((Form_pg_extension) GETSTRUCT(extTup))->oid;
3142 
3143  /*
3144  * Determine the existing version we are updating from
3145  */
3146  datum = heap_getattr(extTup, Anum_pg_extension_extversion,
3147  RelationGetDescr(extRel), &isnull);
3148  if (isnull)
3149  elog(ERROR, "extversion is null");
3150  oldVersionName = text_to_cstring(DatumGetTextPP(datum));
3151 
3152  systable_endscan(extScan);
3153 
3154  table_close(extRel, AccessShareLock);
3155 
3156  /* Permission check: must own extension */
3157  if (!object_ownercheck(ExtensionRelationId, extensionOid, GetUserId()))
3159  stmt->extname);
3160 
3161  /*
3162  * Read the primary control file. Note we assume that it does not contain
3163  * any non-ASCII data, so there is no need to worry about encoding at this
3164  * point.
3165  */
3166  control = read_extension_control_file(stmt->extname);
3167 
3168  /*
3169  * Read the statement option list
3170  */
3171  foreach(lc, stmt->options)
3172  {
3173  DefElem *defel = (DefElem *) lfirst(lc);
3174 
3175  if (strcmp(defel->defname, "new_version") == 0)
3176  {
3177  if (d_new_version)
3178  errorConflictingDefElem(defel, pstate);
3179  d_new_version = defel;
3180  }
3181  else
3182  elog(ERROR, "unrecognized option: %s", defel->defname);
3183  }
3184 
3185  /*
3186  * Determine the version to update to
3187  */
3188  if (d_new_version && d_new_version->arg)
3189  versionName = strVal(d_new_version->arg);
3190  else if (control->default_version)
3191  versionName = control->default_version;
3192  else
3193  {
3194  ereport(ERROR,
3195  (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
3196  errmsg("version to install must be specified")));
3197  versionName = NULL; /* keep compiler quiet */
3198  }
3199  check_valid_version_name(versionName);
3200 
3201  /*
3202  * If we're already at that version, just say so
3203  */
3204  if (strcmp(oldVersionName, versionName) == 0)
3205  {
3206  ereport(NOTICE,
3207  (errmsg("version \"%s\" of extension \"%s\" is already installed",
3208  versionName, stmt->extname)));
3209  return InvalidObjectAddress;
3210  }
3211 
3212  /*
3213  * Identify the series of update script files we need to execute
3214  */
3215  updateVersions = identify_update_path(control,
3216  oldVersionName,
3217  versionName);
3218 
3219  /*
3220  * Update the pg_extension row and execute the update scripts, one at a
3221  * time
3222  */
3223  ApplyExtensionUpdates(extensionOid, control,
3224  oldVersionName, updateVersions,
3225  NULL, false, false);
3226 
3227  ObjectAddressSet(address, ExtensionRelationId, extensionOid);
3228 
3229  return address;
3230 }
static List * identify_update_path(ExtensionControlFile *control, const char *oldVersion, const char *newVersion)
Definition: extension.c:1374
#define DatumGetTextPP(X)
Definition: fmgr.h:292
static Datum heap_getattr(HeapTuple tup, int attnum, TupleDesc tupleDesc, bool *isnull)
Definition: htup_details.h:792
Node * arg
Definition: parsenodes.h:818
#define strVal(v)
Definition: value.h:82
char * text_to_cstring(const text *t)
Definition: varlena.c:217

References AccessShareLock, aclcheck_error(), ACLCHECK_NOT_OWNER, ApplyExtensionUpdates(), DefElem::arg, BTEqualStrategyNumber, check_valid_version_name(), creating_extension, CStringGetDatum(), DatumGetTextPP, ExtensionControlFile::default_version, DefElem::defname, elog, ereport, errcode(), errmsg(), ERROR, errorConflictingDefElem(), GETSTRUCT, GetUserId(), heap_getattr(), HeapTupleIsValid, identify_update_path(), InvalidObjectAddress, sort-test::key, lfirst, NOTICE, OBJECT_EXTENSION, object_ownercheck(), ObjectAddressSet, read_extension_control_file(), RelationGetDescr, ScanKeyInit(), stmt, strVal, systable_beginscan(), systable_endscan(), systable_getnext(), table_close(), table_open(), and text_to_cstring().

Referenced by ProcessUtilitySlow().

◆ execute_extension_script()

static void execute_extension_script ( Oid  extensionOid,
ExtensionControlFile control,
const char *  from_version,
const char *  version,
List requiredSchemas,
const char *  schemaName,
Oid  schemaOid 
)
static

Definition at line 977 of file extension.c.

982 {
983  bool switch_to_superuser = false;
984  char *filename;
985  Oid save_userid = 0;
986  int save_sec_context = 0;
987  int save_nestlevel;
988  StringInfoData pathbuf;
989  ListCell *lc;
990  ListCell *lc2;
991 
992  /*
993  * Enforce superuser-ness if appropriate. We postpone these checks until
994  * here so that the control flags are correctly associated with the right
995  * script(s) if they happen to be set in secondary control files.
996  */
997  if (control->superuser && !superuser())
998  {
999  if (extension_is_trusted(control))
1000  switch_to_superuser = true;
1001  else if (from_version == NULL)
1002  ereport(ERROR,
1003  (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
1004  errmsg("permission denied to create extension \"%s\"",
1005  control->name),
1006  control->trusted
1007  ? errhint("Must have CREATE privilege on current database to create this extension.")
1008  : errhint("Must be superuser to create this extension.")));
1009  else
1010  ereport(ERROR,
1011  (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
1012  errmsg("permission denied to update extension \"%s\"",
1013  control->name),
1014  control->trusted
1015  ? errhint("Must have CREATE privilege on current database to update this extension.")
1016  : errhint("Must be superuser to update this extension.")));
1017  }
1018 
1019  filename = get_extension_script_filename(control, from_version, version);
1020 
1021  if (from_version == NULL)
1022  elog(DEBUG1, "executing extension script for \"%s\" version '%s'", control->name, version);
1023  else
1024  elog(DEBUG1, "executing extension script for \"%s\" update from version '%s' to '%s'", control->name, from_version, version);
1025 
1026  /*
1027  * If installing a trusted extension on behalf of a non-superuser, become
1028  * the bootstrap superuser. (This switch will be cleaned up automatically
1029  * if the transaction aborts, as will the GUC changes below.)
1030  */
1031  if (switch_to_superuser)
1032  {
1033  GetUserIdAndSecContext(&save_userid, &save_sec_context);
1034  SetUserIdAndSecContext(BOOTSTRAP_SUPERUSERID,
1035  save_sec_context | SECURITY_LOCAL_USERID_CHANGE);
1036  }
1037 
1038  /*
1039  * Force client_min_messages and log_min_messages to be at least WARNING,
1040  * so that we won't spam the user with useless NOTICE messages from common
1041  * script actions like creating shell types.
1042  *
1043  * We use the equivalent of a function SET option to allow the setting to
1044  * persist for exactly the duration of the script execution. guc.c also
1045  * takes care of undoing the setting on error.
1046  *
1047  * log_min_messages can't be set by ordinary users, so for that one we
1048  * pretend to be superuser.
1049  */
1050  save_nestlevel = NewGUCNestLevel();
1051 
1053  (void) set_config_option("client_min_messages", "warning",
1055  GUC_ACTION_SAVE, true, 0, false);
1056  if (log_min_messages < WARNING)
1057  (void) set_config_option_ext("log_min_messages", "warning",
1059  BOOTSTRAP_SUPERUSERID,
1060  GUC_ACTION_SAVE, true, 0, false);
1061 
1062  /*
1063  * Similarly disable check_function_bodies, to ensure that SQL functions
1064  * won't be parsed during creation.
1065  */
1067  (void) set_config_option("check_function_bodies", "off",
1069  GUC_ACTION_SAVE, true, 0, false);
1070 
1071  /*
1072  * Set up the search path to have the target schema first, making it be
1073  * the default creation target namespace. Then add the schemas of any
1074  * prerequisite extensions, unless they are in pg_catalog which would be
1075  * searched anyway. (Listing pg_catalog explicitly in a non-first
1076  * position would be bad for security.) Finally add pg_temp to ensure
1077  * that temp objects can't take precedence over others.
1078  */
1079  initStringInfo(&pathbuf);
1080  appendStringInfoString(&pathbuf, quote_identifier(schemaName));
1081  foreach(lc, requiredSchemas)
1082  {
1083  Oid reqschema = lfirst_oid(lc);
1084  char *reqname = get_namespace_name(reqschema);
1085 
1086  if (reqname && strcmp(reqname, "pg_catalog") != 0)
1087  appendStringInfo(&pathbuf, ", %s", quote_identifier(reqname));
1088  }
1089  appendStringInfoString(&pathbuf, ", pg_temp");
1090 
1091  (void) set_config_option("search_path", pathbuf.data,
1093  GUC_ACTION_SAVE, true, 0, false);
1094 
1095  /*
1096  * Set creating_extension and related variables so that
1097  * recordDependencyOnCurrentExtension and other functions do the right
1098  * things. On failure, ensure we reset these variables.
1099  */
1100  creating_extension = true;
1101  CurrentExtensionObject = extensionOid;
1102  PG_TRY();
1103  {
1104  char *c_sql = read_extension_script_file(control, filename);
1105  Datum t_sql;
1106 
1107  /*
1108  * We filter each substitution through quote_identifier(). When the
1109  * arg contains one of the following characters, no one collection of
1110  * quoting can work inside $$dollar-quoted string literals$$,
1111  * 'single-quoted string literals', and outside of any literal. To
1112  * avoid a security snare for extension authors, error on substitution
1113  * for arguments containing these.
1114  */
1115  const char *quoting_relevant_chars = "\"$'\\";
1116 
1117  /* We use various functions that want to operate on text datums */
1118  t_sql = CStringGetTextDatum(c_sql);
1119 
1120  /*
1121  * Reduce any lines beginning with "\echo" to empty. This allows
1122  * scripts to contain messages telling people not to run them via
1123  * psql, which has been found to be necessary due to old habits.
1124  */
1126  C_COLLATION_OID,
1127  t_sql,
1128  CStringGetTextDatum("^\\\\echo.*$"),
1129  CStringGetTextDatum(""),
1130  CStringGetTextDatum("ng"));
1131 
1132  /*
1133  * If the script uses @extowner@, substitute the calling username.
1134  */
1135  if (strstr(c_sql, "@extowner@"))
1136  {
1137  Oid uid = switch_to_superuser ? save_userid : GetUserId();
1138  const char *userName = GetUserNameFromId(uid, false);
1139  const char *qUserName = quote_identifier(userName);
1140 
1142  C_COLLATION_OID,
1143  t_sql,
1144  CStringGetTextDatum("@extowner@"),
1145  CStringGetTextDatum(qUserName));
1146  if (strpbrk(userName, quoting_relevant_chars))
1147  ereport(ERROR,
1148  (errcode(ERRCODE_INVALID_TEXT_REPRESENTATION),
1149  errmsg("invalid character in extension owner: must not contain any of \"%s\"",
1150  quoting_relevant_chars)));
1151  }
1152 
1153  /*
1154  * If it's not relocatable, substitute the target schema name for
1155  * occurrences of @extschema@.
1156  *
1157  * For a relocatable extension, we needn't do this. There cannot be
1158  * any need for @extschema@, else it wouldn't be relocatable.
1159  */
1160  if (!control->relocatable)
1161  {
1162  Datum old = t_sql;
1163  const char *qSchemaName = quote_identifier(schemaName);
1164 
1166  C_COLLATION_OID,
1167  t_sql,
1168  CStringGetTextDatum("@extschema@"),
1169  CStringGetTextDatum(qSchemaName));
1170  if (t_sql != old && strpbrk(schemaName, quoting_relevant_chars))
1171  ereport(ERROR,
1172  (errcode(ERRCODE_INVALID_TEXT_REPRESENTATION),
1173  errmsg("invalid character in extension \"%s\" schema: must not contain any of \"%s\"",
1174  control->name, quoting_relevant_chars)));
1175  }
1176 
1177  /*
1178  * Likewise, substitute required extensions' schema names for
1179  * occurrences of @extschema:extension_name@.
1180  */
1181  Assert(list_length(control->requires) == list_length(requiredSchemas));
1182  forboth(lc, control->requires, lc2, requiredSchemas)
1183  {
1184  Datum old = t_sql;
1185  char *reqextname = (char *) lfirst(lc);
1186  Oid reqschema = lfirst_oid(lc2);
1187  char *schemaName = get_namespace_name(reqschema);
1188  const char *qSchemaName = quote_identifier(schemaName);
1189  char *repltoken;
1190 
1191  repltoken = psprintf("@extschema:%s@", reqextname);
1193  C_COLLATION_OID,
1194  t_sql,
1195  CStringGetTextDatum(repltoken),
1196  CStringGetTextDatum(qSchemaName));
1197  if (t_sql != old && strpbrk(schemaName, quoting_relevant_chars))
1198  ereport(ERROR,
1199  (errcode(ERRCODE_INVALID_TEXT_REPRESENTATION),
1200  errmsg("invalid character in extension \"%s\" schema: must not contain any of \"%s\"",
1201  reqextname, quoting_relevant_chars)));
1202  }
1203 
1204  /*
1205  * If module_pathname was set in the control file, substitute its
1206  * value for occurrences of MODULE_PATHNAME.
1207  */
1208  if (control->module_pathname)
1209  {
1211  C_COLLATION_OID,
1212  t_sql,
1213  CStringGetTextDatum("MODULE_PATHNAME"),
1215  }
1216 
1217  /* And now back to C string */
1218  c_sql = text_to_cstring(DatumGetTextPP(t_sql));
1219 
1220  execute_sql_string(c_sql, filename);
1221  }
1222  PG_FINALLY();
1223  {
1224  creating_extension = false;
1226  }
1227  PG_END_TRY();
1228 
1229  /*
1230  * Restore the GUC variables we set above.
1231  */
1232  AtEOXact_GUC(true, save_nestlevel);
1233 
1234  /*
1235  * Restore authentication state if needed.
1236  */
1237  if (switch_to_superuser)
1238  SetUserIdAndSecContext(save_userid, save_sec_context);
1239 }
int errhint(const char *fmt,...)
Definition: elog.c:1317
#define PG_TRY(...)
Definition: elog.h:371
#define WARNING
Definition: elog.h:36
#define PG_END_TRY(...)
Definition: elog.h:396
#define DEBUG1
Definition: elog.h:30
#define PG_FINALLY(...)
Definition: elog.h:388
static char * read_extension_script_file(const ExtensionControlFile *control, const char *filename)
Definition: extension.c:656
static void execute_sql_string(const char *sql, const char *filename)
Definition: extension.c:827
Oid CurrentExtensionObject
Definition: extension.c:74
static bool extension_is_trusted(ExtensionControlFile *control)
Definition: extension.c:955
Datum DirectFunctionCall4Coll(PGFunction func, Oid collation, Datum arg1, Datum arg2, Datum arg3, Datum arg4)
Definition: fmgr.c:859
Datum DirectFunctionCall3Coll(PGFunction func, Oid collation, Datum arg1, Datum arg2, Datum arg3)
Definition: fmgr.c:834
int set_config_option_ext(const char *name, const char *value, GucContext context, GucSource source, Oid srole, GucAction action, bool changeVal, int elevel, bool is_reload)
Definition: guc.c:3381
int NewGUCNestLevel(void)
Definition: guc.c:2234
void AtEOXact_GUC(bool isCommit, int nestLevel)
Definition: guc.c:2261
int set_config_option(const char *name, const char *value, GucContext context, GucSource source, GucAction action, bool changeVal, int elevel, bool is_reload)
Definition: guc.c:3341
@ GUC_ACTION_SAVE
Definition: guc.h:201
@ PGC_S_SESSION
Definition: guc.h:122
@ PGC_SUSET
Definition: guc.h:74
@ PGC_USERSET
Definition: guc.h:75
bool check_function_bodies
Definition: guc_tables.c:511
int client_min_messages
Definition: guc_tables.c:523
int log_min_messages
Definition: guc_tables.c:522
#define SECURITY_LOCAL_USERID_CHANGE
Definition: miscadmin.h:311
char * GetUserNameFromId(Oid roleid, bool noerr)
Definition: miscinit.c:980
void GetUserIdAndSecContext(Oid *userid, int *sec_context)
Definition: miscinit.c:635
void SetUserIdAndSecContext(Oid userid, int sec_context)
Definition: miscinit.c:642
#define forboth(cell1, list1, cell2, list2)
Definition: pg_list.h:518
char * psprintf(const char *fmt,...)
Definition: psprintf.c:46
Datum textregexreplace(PG_FUNCTION_ARGS)
Definition: regexp.c:658
const char * quote_identifier(const char *ident)
Definition: ruleutils.c:12840
void appendStringInfo(StringInfo str, const char *fmt,...)
Definition: stringinfo.c:97
void appendStringInfoString(StringInfo str, const char *s)
Definition: stringinfo.c:182
void initStringInfo(StringInfo str)
Definition: stringinfo.c:59
char * module_pathname
Definition: extension.c:84
bool superuser(void)
Definition: superuser.c:46
Datum replace_text(PG_FUNCTION_ARGS)
Definition: varlena.c:4009

References appendStringInfo(), appendStringInfoString(), Assert, AtEOXact_GUC(), check_function_bodies, client_min_messages, creating_extension, CStringGetTextDatum, CurrentExtensionObject, StringInfoData::data, DatumGetTextPP, DEBUG1, DirectFunctionCall3Coll(), DirectFunctionCall4Coll(), elog, ereport, errcode(), errhint(), errmsg(), ERROR, execute_sql_string(), extension_is_trusted(), filename, forboth, get_extension_script_filename(), get_namespace_name(), GetUserId(), GetUserIdAndSecContext(), GetUserNameFromId(), GUC_ACTION_SAVE, initStringInfo(), InvalidOid, lfirst, lfirst_oid, list_length(), log_min_messages, ExtensionControlFile::module_pathname, ExtensionControlFile::name, NewGUCNestLevel(), PG_END_TRY, PG_FINALLY, PG_TRY, PGC_S_SESSION, PGC_SUSET, PGC_USERSET, psprintf(), quote_identifier(), read_extension_script_file(), ExtensionControlFile::relocatable, replace_text(), ExtensionControlFile::requires, SECURITY_LOCAL_USERID_CHANGE, set_config_option(), set_config_option_ext(), SetUserIdAndSecContext(), ExtensionControlFile::superuser, superuser(), text_to_cstring(), textregexreplace(), ExtensionControlFile::trusted, and WARNING.

Referenced by ApplyExtensionUpdates(), and CreateExtensionInternal().

◆ execute_sql_string()

static void execute_sql_string ( const char *  sql,
const char *  filename 
)
static

Definition at line 827 of file extension.c.

828 {
829  script_error_callback_arg callback_arg;
830  ErrorContextCallback scripterrcontext;
831  List *raw_parsetree_list;
833  ListCell *lc1;
834 
835  /*
836  * Setup error traceback support for ereport().
837  */
838  callback_arg.sql = sql;
839  callback_arg.filename = filename;
840  callback_arg.stmt_location = -1;
841  callback_arg.stmt_len = -1;
842 
843  scripterrcontext.callback = script_error_callback;
844  scripterrcontext.arg = (void *) &callback_arg;
845  scripterrcontext.previous = error_context_stack;
846  error_context_stack = &scripterrcontext;
847 
848  /*
849  * Parse the SQL string into a list of raw parse trees.
850  */
851  raw_parsetree_list = pg_parse_query(sql);
852 
853  /* All output from SELECTs goes to the bit bucket */
855 
856  /*
857  * Do parse analysis, rule rewrite, planning, and execution for each raw
858  * parsetree. We must fully execute each query before beginning parse
859  * analysis on the next one, since there may be interdependencies.
860  */
861  foreach(lc1, raw_parsetree_list)
862  {
863  RawStmt *parsetree = lfirst_node(RawStmt, lc1);
864  MemoryContext per_parsetree_context,
865  oldcontext;
866  List *stmt_list;
867  ListCell *lc2;
868 
869  /* Report location of this query for error context callback */
870  callback_arg.stmt_location = parsetree->stmt_location;
871  callback_arg.stmt_len = parsetree->stmt_len;
872 
873  /*
874  * We do the work for each parsetree in a short-lived context, to
875  * limit the memory used when there are many commands in the string.
876  */
877  per_parsetree_context =
879  "execute_sql_string per-statement context",
881  oldcontext = MemoryContextSwitchTo(per_parsetree_context);
882 
883  /* Be sure parser can see any DDL done so far */
885 
886  stmt_list = pg_analyze_and_rewrite_fixedparams(parsetree,
887  sql,
888  NULL,
889  0,
890  NULL);
891  stmt_list = pg_plan_queries(stmt_list, sql, CURSOR_OPT_PARALLEL_OK, NULL);
892 
893  foreach(lc2, stmt_list)
894  {
896 
898 
900 
901  if (stmt->utilityStmt == NULL)
902  {
903  QueryDesc *qdesc;
904 
905  qdesc = CreateQueryDesc(stmt,
906  sql,
907  GetActiveSnapshot(), NULL,
908  dest, NULL, NULL, 0);
909 
910  ExecutorStart(qdesc, 0);
911  ExecutorRun(qdesc, ForwardScanDirection, 0, true);
912  ExecutorFinish(qdesc);
913  ExecutorEnd(qdesc);
914 
915  FreeQueryDesc(qdesc);
916  }
917  else
918  {
919  if (IsA(stmt->utilityStmt, TransactionStmt))
920  ereport(ERROR,
921  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
922  errmsg("transaction control statements are not allowed within an extension script")));
923 
925  sql,
926  false,
928  NULL,
929  NULL,
930  dest,
931  NULL);
932  }
933 
935  }
936 
937  /* Clean up per-parsetree context. */
938  MemoryContextSwitchTo(oldcontext);
939  MemoryContextDelete(per_parsetree_context);
940  }
941 
942  error_context_stack = scripterrcontext.previous;
943 
944  /* Be sure to advance the command counter after the last script command */
946 }
DestReceiver * CreateDestReceiver(CommandDest dest)
Definition: dest.c:113
@ DestNone
Definition: dest.h:87
ErrorContextCallback * error_context_stack
Definition: elog.c:94
void ExecutorEnd(QueryDesc *queryDesc)
Definition: execMain.c:465
void ExecutorFinish(QueryDesc *queryDesc)
Definition: execMain.c:405
void ExecutorStart(QueryDesc *queryDesc, int eflags)
Definition: execMain.c:120
void ExecutorRun(QueryDesc *queryDesc, ScanDirection direction, uint64 count, bool execute_once)
Definition: execMain.c:295
static void script_error_callback(void *arg)
Definition: extension.c:689
MemoryContext CurrentMemoryContext
Definition: mcxt.c:143
void MemoryContextDelete(MemoryContext context)
Definition: mcxt.c:454
#define AllocSetContextCreate
Definition: memutils.h:129
#define ALLOCSET_DEFAULT_SIZES
Definition: memutils.h:160
#define IsA(nodeptr, _type_)
Definition: nodes.h:158
#define CURSOR_OPT_PARALLEL_OK
Definition: parsenodes.h:3307
#define lfirst_node(type, lc)
Definition: pg_list.h:176
List * pg_parse_query(const char *query_string)
Definition: postgres.c:615
List * pg_analyze_and_rewrite_fixedparams(RawStmt *parsetree, const char *query_string, const Oid *paramTypes, int numParams, QueryEnvironment *queryEnv)
Definition: postgres.c:677
List * pg_plan_queries(List *querytrees, const char *query_string, int cursorOptions, ParamListInfo boundParams)
Definition: postgres.c:982
void FreeQueryDesc(QueryDesc *qdesc)
Definition: pquery.c:105
QueryDesc * CreateQueryDesc(PlannedStmt *plannedstmt, const char *sourceText, Snapshot snapshot, Snapshot crosscheck_snapshot, DestReceiver *dest, ParamListInfo params, QueryEnvironment *queryEnv, int instrument_options)
Definition: pquery.c:67
MemoryContextSwitchTo(old_ctx)
@ ForwardScanDirection
Definition: sdir.h:28
Snapshot GetTransactionSnapshot(void)
Definition: snapmgr.c:216
void PushActiveSnapshot(Snapshot snapshot)
Definition: snapmgr.c:648
void PopActiveSnapshot(void)
Definition: snapmgr.c:743
Snapshot GetActiveSnapshot(void)
Definition: snapmgr.c:770
struct ErrorContextCallback * previous
Definition: elog.h:296
void(* callback)(void *arg)
Definition: elog.h:297
ParseLoc stmt_location
Definition: parsenodes.h:2023
ParseLoc stmt_len
Definition: parsenodes.h:2024
void ProcessUtility(PlannedStmt *pstmt, const char *queryString, bool readOnlyTree, ProcessUtilityContext context, ParamListInfo params, QueryEnvironment *queryEnv, DestReceiver *dest, QueryCompletion *qc)
Definition: utility.c:499
@ PROCESS_UTILITY_QUERY
Definition: utility.h:23
void CommandCounterIncrement(void)
Definition: xact.c:1099

References ALLOCSET_DEFAULT_SIZES, AllocSetContextCreate, ErrorContextCallback::arg, ErrorContextCallback::callback, CommandCounterIncrement(), CreateDestReceiver(), CreateQueryDesc(), CurrentMemoryContext, CURSOR_OPT_PARALLEL_OK, generate_unaccent_rules::dest, DestNone, ereport, errcode(), errmsg(), ERROR, error_context_stack, ExecutorEnd(), ExecutorFinish(), ExecutorRun(), ExecutorStart(), script_error_callback_arg::filename, filename, ForwardScanDirection, FreeQueryDesc(), GetActiveSnapshot(), GetTransactionSnapshot(), IsA, lfirst_node, MemoryContextDelete(), MemoryContextSwitchTo(), pg_analyze_and_rewrite_fixedparams(), pg_parse_query(), pg_plan_queries(), PopActiveSnapshot(), ErrorContextCallback::previous, PROCESS_UTILITY_QUERY, ProcessUtility(), PushActiveSnapshot(), script_error_callback(), script_error_callback_arg::sql, stmt, script_error_callback_arg::stmt_len, RawStmt::stmt_len, script_error_callback_arg::stmt_location, and RawStmt::stmt_location.

Referenced by execute_extension_script().

◆ extension_config_remove()

static void extension_config_remove ( Oid  extensionoid,
Oid  tableoid 
)
static

Definition at line 2714 of file extension.c.

2715 {
2716  Relation extRel;
2717  ScanKeyData key[1];
2718  SysScanDesc extScan;
2719  HeapTuple extTup;
2720  Datum arrayDatum;
2721  int arrayLength;
2722  int arrayIndex;
2723  bool isnull;
2724  Datum repl_val[Natts_pg_extension];
2725  bool repl_null[Natts_pg_extension];
2726  bool repl_repl[Natts_pg_extension];
2727  ArrayType *a;
2728 
2729  /* Find the pg_extension tuple */
2730  extRel = table_open(ExtensionRelationId, RowExclusiveLock);
2731 
2732  ScanKeyInit(&key[0],
2733  Anum_pg_extension_oid,
2734  BTEqualStrategyNumber, F_OIDEQ,
2735  ObjectIdGetDatum(extensionoid));
2736 
2737  extScan = systable_beginscan(extRel, ExtensionOidIndexId, true,
2738  NULL, 1, key);
2739 
2740  extTup = systable_getnext(extScan);
2741 
2742  if (!HeapTupleIsValid(extTup)) /* should not happen */
2743  elog(ERROR, "could not find tuple for extension %u",
2744  extensionoid);
2745 
2746  /* Search extconfig for the tableoid */
2747  arrayDatum = heap_getattr(extTup, Anum_pg_extension_extconfig,
2748  RelationGetDescr(extRel), &isnull);
2749  if (isnull)
2750  {
2751  /* nothing to do */
2752  a = NULL;
2753  arrayLength = 0;
2754  arrayIndex = -1;
2755  }
2756  else
2757  {
2758  Oid *arrayData;
2759  int i;
2760 
2761  a = DatumGetArrayTypeP(arrayDatum);
2762 
2763  arrayLength = ARR_DIMS(a)[0];
2764  if (ARR_NDIM(a) != 1 ||
2765  ARR_LBOUND(a)[0] != 1 ||
2766  arrayLength < 0 ||
2767  ARR_HASNULL(a) ||
2768  ARR_ELEMTYPE(a) != OIDOID)
2769  elog(ERROR, "extconfig is not a 1-D Oid array");
2770  arrayData = (Oid *) ARR_DATA_PTR(a);
2771 
2772  arrayIndex = -1; /* flag for no deletion needed */
2773 
2774  for (i = 0; i < arrayLength; i++)
2775  {
2776  if (arrayData[i] == tableoid)
2777  {
2778  arrayIndex = i; /* index to remove */
2779  break;
2780  }
2781  }
2782  }
2783 
2784  /* If tableoid is not in extconfig, nothing to do */
2785  if (arrayIndex < 0)
2786  {
2787  systable_endscan(extScan);
2788  table_close(extRel, RowExclusiveLock);
2789  return;
2790  }
2791 
2792  /* Modify or delete the extconfig value */
2793  memset(repl_val, 0, sizeof(repl_val));
2794  memset(repl_null, false, sizeof(repl_null));
2795  memset(repl_repl, false, sizeof(repl_repl));
2796 
2797  if (arrayLength <= 1)
2798  {
2799  /* removing only element, just set array to null */
2800  repl_null[Anum_pg_extension_extconfig - 1] = true;
2801  }
2802  else
2803  {
2804  /* squeeze out the target element */
2805  Datum *dvalues;
2806  int nelems;
2807  int i;
2808 
2809  /* We already checked there are no nulls */
2810  deconstruct_array_builtin(a, OIDOID, &dvalues, NULL, &nelems);
2811 
2812  for (i = arrayIndex; i < arrayLength - 1; i++)
2813  dvalues[i] = dvalues[i + 1];
2814 
2815  a = construct_array_builtin(dvalues, arrayLength - 1, OIDOID);
2816 
2817  repl_val[Anum_pg_extension_extconfig - 1] = PointerGetDatum(a);
2818  }
2819  repl_repl[Anum_pg_extension_extconfig - 1] = true;
2820 
2821  /* Modify or delete the extcondition value */
2822  arrayDatum = heap_getattr(extTup, Anum_pg_extension_extcondition,
2823  RelationGetDescr(extRel), &isnull);
2824  if (isnull)
2825  {
2826  elog(ERROR, "extconfig and extcondition arrays do not match");
2827  }
2828  else
2829  {
2830  a = DatumGetArrayTypeP(arrayDatum);
2831 
2832  if (ARR_NDIM(a) != 1 ||
2833  ARR_LBOUND(a)[0] != 1 ||
2834  ARR_HASNULL(a) ||
2835  ARR_ELEMTYPE(a) != TEXTOID)
2836  elog(ERROR, "extcondition is not a 1-D text array");
2837  if (ARR_DIMS(a)[0] != arrayLength)
2838  elog(ERROR, "extconfig and extcondition arrays do not match");
2839  }
2840 
2841  if (arrayLength <= 1)
2842  {
2843  /* removing only element, just set array to null */
2844  repl_null[Anum_pg_extension_extcondition - 1] = true;
2845  }
2846  else
2847  {
2848  /* squeeze out the target element */
2849  Datum *dvalues;
2850  int nelems;
2851  int i;
2852 
2853  /* We already checked there are no nulls */
2854  deconstruct_array_builtin(a, TEXTOID, &dvalues, NULL, &nelems);
2855 
2856  for (i = arrayIndex; i < arrayLength - 1; i++)
2857  dvalues[i] = dvalues[i + 1];
2858 
2859  a = construct_array_builtin(dvalues, arrayLength - 1, TEXTOID);
2860 
2861  repl_val[Anum_pg_extension_extcondition - 1] = PointerGetDatum(a);
2862  }
2863  repl_repl[Anum_pg_extension_extcondition - 1] = true;
2864 
2865  extTup = heap_modify_tuple(extTup, RelationGetDescr(extRel),
2866  repl_val, repl_null, repl_repl);
2867 
2868  CatalogTupleUpdate(extRel, &extTup->t_self, extTup);
2869 
2870  systable_endscan(extScan);
2871 
2872  table_close(extRel, RowExclusiveLock);
2873 }
#define ARR_NDIM(a)
Definition: array.h:290
#define ARR_DATA_PTR(a)
Definition: array.h:322
#define DatumGetArrayTypeP(X)
Definition: array.h:261
#define ARR_ELEMTYPE(a)
Definition: array.h:292
#define ARR_DIMS(a)
Definition: array.h:294
#define ARR_HASNULL(a)
Definition: array.h:291
#define ARR_LBOUND(a)
Definition: array.h:296
void deconstruct_array_builtin(ArrayType *array, Oid elmtype, Datum **elemsp, bool **nullsp, int *nelemsp)
Definition: arrayfuncs.c:3697
int i
Definition: isn.c:73

References a, ARR_DATA_PTR, ARR_DIMS, ARR_ELEMTYPE, ARR_HASNULL, ARR_LBOUND, ARR_NDIM, BTEqualStrategyNumber, CatalogTupleUpdate(), construct_array_builtin(), DatumGetArrayTypeP, deconstruct_array_builtin(), elog, ERROR, heap_getattr(), heap_modify_tuple(), HeapTupleIsValid, i, sort-test::key, ObjectIdGetDatum(), PointerGetDatum(), RelationGetDescr, RowExclusiveLock, ScanKeyInit(), systable_beginscan(), systable_endscan(), systable_getnext(), HeapTupleData::t_self, table_close(), and table_open().

Referenced by ExecAlterExtensionContentsRecurse().

◆ extension_file_exists()

bool extension_file_exists ( const char *  extensionName)

Definition at line 2367 of file extension.c.

2368 {
2369  bool result = false;
2370  char *location;
2371  DIR *dir;
2372  struct dirent *de;
2373 
2374  location = get_extension_control_directory();
2375  dir = AllocateDir(location);
2376 
2377  /*
2378  * If the control directory doesn't exist, we want to silently return
2379  * false. Any other error will be reported by ReadDir.
2380  */
2381  if (dir == NULL && errno == ENOENT)
2382  {
2383  /* do nothing */
2384  }
2385  else
2386  {
2387  while ((de = ReadDir(dir, location)) != NULL)
2388  {
2389  char *extname;
2390 
2392  continue;
2393 
2394  /* extract extension name from 'name.control' filename */
2395  extname = pstrdup(de->d_name);
2396  *strrchr(extname, '.') = '\0';
2397 
2398  /* ignore it if it's an auxiliary control file */
2399  if (strstr(extname, "--"))
2400  continue;
2401 
2402  /* done if it matches request */
2403  if (strcmp(extname, extensionName) == 0)
2404  {
2405  result = true;
2406  break;
2407  }
2408  }
2409 
2410  FreeDir(dir);
2411  }
2412 
2413  return result;
2414 }
static bool is_extension_control_filename(const char *filename)
Definition: extension.c:316
static char * get_extension_control_directory(void)
Definition: extension.c:332
struct dirent * ReadDir(DIR *dir, const char *dirname)
Definition: fd.c:2932
int FreeDir(DIR *dir)
Definition: fd.c:2984
DIR * AllocateDir(const char *dirname)
Definition: fd.c:2866
char * pstrdup(const char *in)
Definition: mcxt.c:1696
Definition: dirent.c:26
Definition: dirent.h:10
char d_name[MAX_PATH]
Definition: dirent.h:15

References AllocateDir(), dirent::d_name, FreeDir(), get_extension_control_directory(), is_extension_control_filename(), pstrdup(), and ReadDir().

Referenced by CreateFunction(), and ExecuteDoStmt().

◆ extension_is_trusted()

static bool extension_is_trusted ( ExtensionControlFile control)
static

Definition at line 955 of file extension.c.

956 {
957  AclResult aclresult;
958 
959  /* Never trust unless extension's control file says it's okay */
960  if (!control->trusted)
961  return false;
962  /* Allow if user has CREATE privilege on current database */
963  aclresult = object_aclcheck(DatabaseRelationId, MyDatabaseId, GetUserId(), ACL_CREATE);
964  if (aclresult == ACLCHECK_OK)
965  return true;
966  return false;
967 }
Oid MyDatabaseId
Definition: globals.c:93

References ACL_CREATE, ACLCHECK_OK, GetUserId(), MyDatabaseId, object_aclcheck(), and ExtensionControlFile::trusted.

Referenced by execute_extension_script().

◆ find_install_path()

static ExtensionVersionInfo* find_install_path ( List evi_list,
ExtensionVersionInfo evi_target,
List **  best_path 
)
static

Definition at line 1510 of file extension.c.

1512 {
1513  ExtensionVersionInfo *evi_start = NULL;
1514  ListCell *lc;
1515 
1516  *best_path = NIL;
1517 
1518  /*
1519  * We don't expect to be called for an installable target, but if we are,
1520  * the answer is easy: just start from there, with an empty update path.
1521  */
1522  if (evi_target->installable)
1523  return evi_target;
1524 
1525  /* Consider all installable versions as start points */
1526  foreach(lc, evi_list)
1527  {
1529  List *path;
1530 
1531  if (!evi1->installable)
1532  continue;
1533 
1534  /*
1535  * Find shortest path from evi1 to evi_target; but no need to consider
1536  * paths going through other installable versions.
1537  */
1538  path = find_update_path(evi_list, evi1, evi_target, true, true);
1539  if (path == NIL)
1540  continue;
1541 
1542  /* Remember best path */
1543  if (evi_start == NULL ||
1544  list_length(path) < list_length(*best_path) ||
1545  (list_length(path) == list_length(*best_path) &&
1546  strcmp(evi_start->name, evi1->name) < 0))
1547  {
1548  evi_start = evi1;
1549  *best_path = path;
1550  }
1551  }
1552 
1553  return evi_start;
1554 }
static List * find_update_path(List *evi_list, ExtensionVersionInfo *evi_start, ExtensionVersionInfo *evi_target, bool reject_indirect, bool reinitialize)
Definition: extension.c:1417

References find_update_path(), ExtensionVersionInfo::installable, lfirst, list_length(), ExtensionVersionInfo::name, and NIL.

Referenced by CreateExtensionInternal(), and get_available_versions_for_extension().

◆ find_update_path()

static List * find_update_path ( List evi_list,
ExtensionVersionInfo evi_start,
ExtensionVersionInfo evi_target,
bool  reject_indirect,
bool  reinitialize 
)
static

Definition at line 1417 of file extension.c.

1422 {
1423  List *result;
1424  ExtensionVersionInfo *evi;
1425  ListCell *lc;
1426 
1427  /* Caller error if start == target */
1428  Assert(evi_start != evi_target);
1429  /* Caller error if reject_indirect and target is installable */
1430  Assert(!(reject_indirect && evi_target->installable));
1431 
1432  if (reinitialize)
1433  {
1434  foreach(lc, evi_list)
1435  {
1436  evi = (ExtensionVersionInfo *) lfirst(lc);
1437  evi->distance_known = false;
1438  evi->distance = INT_MAX;
1439  evi->previous = NULL;
1440  }
1441  }
1442 
1443  evi_start->distance = 0;
1444 
1445  while ((evi = get_nearest_unprocessed_vertex(evi_list)) != NULL)
1446  {
1447  if (evi->distance == INT_MAX)
1448  break; /* all remaining vertices are unreachable */
1449  evi->distance_known = true;
1450  if (evi == evi_target)
1451  break; /* found shortest path to target */
1452  foreach(lc, evi->reachable)
1453  {
1455  int newdist;
1456 
1457  /* if reject_indirect, treat installable versions as unreachable */
1458  if (reject_indirect && evi2->installable)
1459  continue;
1460  newdist = evi->distance + 1;
1461  if (newdist < evi2->distance)
1462  {
1463  evi2->distance = newdist;
1464  evi2->previous = evi;
1465  }
1466  else if (newdist == evi2->distance &&
1467  evi2->previous != NULL &&
1468  strcmp(evi->name, evi2->previous->name) < 0)
1469  {
1470  /*
1471  * Break ties in favor of the version name that comes first
1472  * according to strcmp(). This behavior is undocumented and
1473  * users shouldn't rely on it. We do it just to ensure that
1474  * if there is a tie, the update path that is chosen does not
1475  * depend on random factors like the order in which directory
1476  * entries get visited.
1477  */
1478  evi2->previous = evi;
1479  }
1480  }
1481  }
1482 
1483  /* Return NIL if target is not reachable from start */
1484  if (!evi_target->distance_known)
1485  return NIL;
1486 
1487  /* Build and return list of version names representing the update path */
1488  result = NIL;
1489  for (evi = evi_target; evi != evi_start; evi = evi->previous)
1490  result = lcons(evi->name, result);
1491 
1492  return result;
1493 }
static ExtensionVersionInfo * get_nearest_unprocessed_vertex(List *evi_list)
Definition: extension.c:1283
List * lcons(void *datum, List *list)
Definition: list.c:495
struct ExtensionVersionInfo * previous
Definition: extension.c:108

References Assert, ExtensionVersionInfo::distance, ExtensionVersionInfo::distance_known, get_nearest_unprocessed_vertex(), ExtensionVersionInfo::installable, lcons(), lfirst, ExtensionVersionInfo::name, NIL, ExtensionVersionInfo::previous, and ExtensionVersionInfo::reachable.

Referenced by find_install_path(), identify_update_path(), and pg_extension_update_paths().

◆ get_available_versions_for_extension()

static void get_available_versions_for_extension ( ExtensionControlFile pcontrol,
Tuplestorestate tupstore,
TupleDesc  tupdesc 
)
static

Definition at line 2253 of file extension.c.

2256 {
2257  List *evi_list;
2258  ListCell *lc;
2259 
2260  /* Extract the version update graph from the script directory */
2261  evi_list = get_ext_ver_list(pcontrol);
2262 
2263  /* For each installable version ... */
2264  foreach(lc, evi_list)
2265  {
2267  ExtensionControlFile *control;
2268  Datum values[8];
2269  bool nulls[8];
2270  ListCell *lc2;
2271 
2272  if (!evi->installable)
2273  continue;
2274 
2275  /*
2276  * Fetch parameters for specific version (pcontrol is not changed)
2277  */
2278  control = read_extension_aux_control_file(pcontrol, evi->name);
2279 
2280  memset(values, 0, sizeof(values));
2281  memset(nulls, 0, sizeof(nulls));
2282 
2283  /* name */
2285  CStringGetDatum(control->name));
2286  /* version */
2287  values[1] = CStringGetTextDatum(evi->name);
2288  /* superuser */
2289  values[2] = BoolGetDatum(control->superuser);
2290  /* trusted */
2291  values[3] = BoolGetDatum(control->trusted);
2292  /* relocatable */
2293  values[4] = BoolGetDatum(control->relocatable);
2294  /* schema */
2295  if (control->schema == NULL)
2296  nulls[5] = true;
2297  else
2299  CStringGetDatum(control->schema));
2300  /* requires */
2301  if (control->requires == NIL)
2302  nulls[6] = true;
2303  else
2304  values[6] = convert_requires_to_datum(control->requires);
2305  /* comment */
2306  if (control->comment == NULL)
2307  nulls[7] = true;
2308  else
2309  values[7] = CStringGetTextDatum(control->comment);
2310 
2311  tuplestore_putvalues(tupstore, tupdesc, values, nulls);
2312 
2313  /*
2314  * Find all non-directly-installable versions that would be installed
2315  * starting from this version, and report them, inheriting the
2316  * parameters that aren't changed in updates from this version.
2317  */
2318  foreach(lc2, evi_list)
2319  {
2321  List *best_path;
2322 
2323  if (evi2->installable)
2324  continue;
2325  if (find_install_path(evi_list, evi2, &best_path) == evi)
2326  {
2327  /*
2328  * Fetch parameters for this version (pcontrol is not changed)
2329  */
2330  control = read_extension_aux_control_file(pcontrol, evi2->name);
2331 
2332  /* name stays the same */
2333  /* version */
2334  values[1] = CStringGetTextDatum(evi2->name);
2335  /* superuser */
2336  values[2] = BoolGetDatum(control->superuser);
2337  /* trusted */
2338  values[3] = BoolGetDatum(control->trusted);
2339  /* relocatable */
2340  values[4] = BoolGetDatum(control->relocatable);
2341  /* schema stays the same */
2342  /* requires */
2343  if (control->requires == NIL)
2344  nulls[6] = true;
2345  else
2346  {
2347  values[6] = convert_requires_to_datum(control->requires);
2348  nulls[6] = false;
2349  }
2350  /* comment stays the same */
2351 
2352  tuplestore_putvalues(tupstore, tupdesc, values, nulls);
2353  }
2354  }
2355  }
2356 }
static Datum convert_requires_to_datum(List *requires)
Definition: extension.c:2420
void tuplestore_putvalues(Tuplestorestate *state, TupleDesc tdesc, const Datum *values, const bool *isnull)
Definition: tuplestore.c:784

References BoolGetDatum(), ExtensionControlFile::comment, convert_requires_to_datum(), CStringGetDatum(), CStringGetTextDatum, DirectFunctionCall1, find_install_path(), get_ext_ver_list(), ExtensionVersionInfo::installable, lfirst, ExtensionControlFile::name, ExtensionVersionInfo::name, namein(), NIL, read_extension_aux_control_file(), ExtensionControlFile::relocatable, ExtensionControlFile::requires, ExtensionControlFile::schema, ExtensionControlFile::superuser, ExtensionControlFile::trusted, tuplestore_putvalues(), and values.

Referenced by pg_available_extension_versions().

◆ get_ext_ver_info()

static ExtensionVersionInfo* get_ext_ver_info ( const char *  versionname,
List **  evi_list 
)
static

Definition at line 1250 of file extension.c.

1251 {
1252  ExtensionVersionInfo *evi;
1253  ListCell *lc;
1254 
1255  foreach(lc, *evi_list)
1256  {
1257  evi = (ExtensionVersionInfo *) lfirst(lc);
1258  if (strcmp(evi->name, versionname) == 0)
1259  return evi;
1260  }
1261 
1263  evi->name = pstrdup(versionname);
1264  evi->reachable = NIL;
1265  evi->installable = false;
1266  /* initialize for later application of Dijkstra's algorithm */
1267  evi->distance_known = false;
1268  evi->distance = INT_MAX;
1269  evi->previous = NULL;
1270 
1271  *evi_list = lappend(*evi_list, evi);
1272 
1273  return evi;
1274 }
List * lappend(List *list, void *datum)
Definition: list.c:339

References ExtensionVersionInfo::distance, ExtensionVersionInfo::distance_known, ExtensionVersionInfo::installable, lappend(), lfirst, ExtensionVersionInfo::name, NIL, palloc(), ExtensionVersionInfo::previous, pstrdup(), and ExtensionVersionInfo::reachable.

Referenced by CreateExtensionInternal(), get_ext_ver_list(), and identify_update_path().

◆ get_ext_ver_list()

static List* get_ext_ver_list ( ExtensionControlFile control)
static

Definition at line 1311 of file extension.c.

1312 {
1313  List *evi_list = NIL;
1314  int extnamelen = strlen(control->name);
1315  char *location;
1316  DIR *dir;
1317  struct dirent *de;
1318 
1319  location = get_extension_script_directory(control);
1320  dir = AllocateDir(location);
1321  while ((de = ReadDir(dir, location)) != NULL)
1322  {
1323  char *vername;
1324  char *vername2;
1325  ExtensionVersionInfo *evi;
1326  ExtensionVersionInfo *evi2;
1327 
1328  /* must be a .sql file ... */
1330  continue;
1331 
1332  /* ... matching extension name followed by separator */
1333  if (strncmp(de->d_name, control->name, extnamelen) != 0 ||
1334  de->d_name[extnamelen] != '-' ||
1335  de->d_name[extnamelen + 1] != '-')
1336  continue;
1337 
1338  /* extract version name(s) from 'extname--something.sql' filename */
1339  vername = pstrdup(de->d_name + extnamelen + 2);
1340  *strrchr(vername, '.') = '\0';
1341  vername2 = strstr(vername, "--");
1342  if (!vername2)
1343  {
1344  /* It's an install, not update, script; record its version name */
1345  evi = get_ext_ver_info(vername, &evi_list);
1346  evi->installable = true;
1347  continue;
1348  }
1349  *vername2 = '\0'; /* terminate first version */
1350  vername2 += 2; /* and point to second */
1351 
1352  /* if there's a third --, it's bogus, ignore it */
1353  if (strstr(vername2, "--"))
1354  continue;
1355 
1356  /* Create ExtensionVersionInfos and link them together */
1357  evi = get_ext_ver_info(vername, &evi_list);
1358  evi2 = get_ext_ver_info(vername2, &evi_list);
1359  evi->reachable = lappend(evi->reachable, evi2);
1360  }
1361  FreeDir(dir);
1362 
1363  return evi_list;
1364 }
static bool is_extension_script_filename(const char *filename)
Definition: extension.c:324
static char * get_extension_script_directory(ExtensionControlFile *control)
Definition: extension.c:359

References AllocateDir(), dirent::d_name, FreeDir(), get_ext_ver_info(), get_extension_script_directory(), ExtensionVersionInfo::installable, is_extension_script_filename(), lappend(), ExtensionControlFile::name, NIL, pstrdup(), ExtensionVersionInfo::reachable, and ReadDir().

Referenced by CreateExtensionInternal(), get_available_versions_for_extension(), identify_update_path(), and pg_extension_update_paths().

◆ get_extension_aux_control_filename()

static char* get_extension_aux_control_filename ( ExtensionControlFile control,
const char *  version 
)
static

Definition at line 382 of file extension.c.

384 {
385  char *result;
386  char *scriptdir;
387 
388  scriptdir = get_extension_script_directory(control);
389 
390  result = (char *) palloc(MAXPGPATH);
391  snprintf(result, MAXPGPATH, "%s/%s--%s.control",
392  scriptdir, control->name, version);
393 
394  pfree(scriptdir);
395 
396  return result;
397 }
void pfree(void *pointer)
Definition: mcxt.c:1521
#define MAXPGPATH
#define snprintf
Definition: port.h:238

References get_extension_script_directory(), MAXPGPATH, ExtensionControlFile::name, palloc(), pfree(), and snprintf.

Referenced by parse_extension_control_file().

◆ get_extension_control_directory()

static char* get_extension_control_directory ( void  )
static

Definition at line 332 of file extension.c.

333 {
334  char sharepath[MAXPGPATH];
335  char *result;
336 
337  get_share_path(my_exec_path, sharepath);
338  result = (char *) palloc(MAXPGPATH);
339  snprintf(result, MAXPGPATH, "%s/extension", sharepath);
340 
341  return result;
342 }
char my_exec_path[MAXPGPATH]
Definition: globals.c:80
void get_share_path(const char *my_exec_path, char *ret_path)
Definition: path.c:825

References get_share_path(), MAXPGPATH, my_exec_path, palloc(), and snprintf.

Referenced by extension_file_exists(), get_extension_script_directory(), pg_available_extension_versions(), and pg_available_extensions().

◆ get_extension_control_filename()

static char* get_extension_control_filename ( const char *  extname)
static

Definition at line 345 of file extension.c.

346 {
347  char sharepath[MAXPGPATH];
348  char *result;
349 
350  get_share_path(my_exec_path, sharepath);
351  result = (char *) palloc(MAXPGPATH);
352  snprintf(result, MAXPGPATH, "%s/extension/%s.control",
353  sharepath, extname);
354 
355  return result;
356 }

References get_share_path(), MAXPGPATH, my_exec_path, palloc(), and snprintf.

Referenced by parse_extension_control_file().

◆ get_extension_name()

char* get_extension_name ( Oid  ext_oid)

Definition at line 180 of file extension.c.

181 {
182  char *result;
183  HeapTuple tuple;
184 
185  tuple = SearchSysCache1(EXTENSIONOID, ObjectIdGetDatum(ext_oid));
186 
187  if (!HeapTupleIsValid(tuple))
188  return NULL;
189 
190  result = pstrdup(NameStr(((Form_pg_extension) GETSTRUCT(tuple))->extname));
191  ReleaseSysCache(tuple);
192 
193  return result;
194 }
void ReleaseSysCache(HeapTuple tuple)
Definition: syscache.c:269
HeapTuple SearchSysCache1(int cacheId, Datum key1)
Definition: syscache.c:221

References GETSTRUCT, HeapTupleIsValid, NameStr, ObjectIdGetDatum(), pstrdup(), ReleaseSysCache(), and SearchSysCache1().

Referenced by AlterExtensionNamespace(), checkMembershipInCurrentExtension(), ExecAlterExtensionContentsRecurse(), getObjectDescription(), getObjectIdentityParts(), recordDependencyOnCurrentExtension(), and RemoveExtensionById().

◆ get_extension_oid()

Oid get_extension_oid ( const char *  extname,
bool  missing_ok 
)

Definition at line 158 of file extension.c.

159 {
160  Oid result;
161 
162  result = GetSysCacheOid1(EXTENSIONNAME, Anum_pg_extension_oid,
163  CStringGetDatum(extname));
164 
165  if (!OidIsValid(result) && !missing_ok)
166  ereport(ERROR,
167  (errcode(ERRCODE_UNDEFINED_OBJECT),
168  errmsg("extension \"%s\" does not exist",
169  extname)));
170 
171  return result;
172 }
#define GetSysCacheOid1(cacheId, oidcol, key1)
Definition: syscache.h:109

References CStringGetDatum(), ereport, errcode(), errmsg(), ERROR, GetSysCacheOid1, and OidIsValid.

Referenced by AlterExtensionNamespace(), binary_upgrade_create_empty_extension(), CreateExtension(), ExtractExtensionList(), get_object_address_unqualified(), and get_required_extension().

◆ get_extension_schema()

Oid get_extension_schema ( Oid  ext_oid)

Definition at line 202 of file extension.c.

203 {
204  Oid result;
205  HeapTuple tuple;
206 
207  tuple = SearchSysCache1(EXTENSIONOID, ObjectIdGetDatum(ext_oid));
208 
209  if (!HeapTupleIsValid(tuple))
210  return InvalidOid;
211 
212  result = ((Form_pg_extension) GETSTRUCT(tuple))->extnamespace;
213  ReleaseSysCache(tuple);
214 
215  return result;
216 }

References GETSTRUCT, HeapTupleIsValid, InvalidOid, ObjectIdGetDatum(), ReleaseSysCache(), and SearchSysCache1().

Referenced by ApplyExtensionUpdates(), CreateExtensionInternal(), and ExecAlterExtensionContentsRecurse().

◆ get_extension_script_directory()

static char* get_extension_script_directory ( ExtensionControlFile control)
static

Definition at line 359 of file extension.c.

360 {
361  char sharepath[MAXPGPATH];
362  char *result;
363 
364  /*
365  * The directory parameter can be omitted, absolute, or relative to the
366  * installation's share directory.
367  */
368  if (!control->directory)
370 
371  if (is_absolute_path(control->directory))
372  return pstrdup(control->directory);
373 
374  get_share_path(my_exec_path, sharepath);
375  result = (char *) palloc(MAXPGPATH);
376  snprintf(result, MAXPGPATH, "%s/%s", sharepath, control->directory);
377 
378  return result;
379 }
#define is_absolute_path(filename)
Definition: port.h:103

References ExtensionControlFile::directory, get_extension_control_directory(), get_share_path(), is_absolute_path, MAXPGPATH, my_exec_path, palloc(), pstrdup(), and snprintf.

Referenced by get_ext_ver_list(), get_extension_aux_control_filename(), and get_extension_script_filename().

◆ get_extension_script_filename()

static char* get_extension_script_filename ( ExtensionControlFile control,
const char *  from_version,
const char *  version 
)
static

Definition at line 400 of file extension.c.

402 {
403  char *result;
404  char *scriptdir;
405 
406  scriptdir = get_extension_script_directory(control);
407 
408  result = (char *) palloc(MAXPGPATH);
409  if (from_version)
410  snprintf(result, MAXPGPATH, "%s/%s--%s--%s.sql",
411  scriptdir, control->name, from_version, version);
412  else
413  snprintf(result, MAXPGPATH, "%s/%s--%s.sql",
414  scriptdir, control->name, version);
415 
416  pfree(scriptdir);
417 
418  return result;
419 }

References get_extension_script_directory(), MAXPGPATH, ExtensionControlFile::name, palloc(), pfree(), and snprintf.

Referenced by CreateExtensionInternal(), and execute_extension_script().

◆ get_nearest_unprocessed_vertex()

static ExtensionVersionInfo* get_nearest_unprocessed_vertex ( List evi_list)
static

Definition at line 1283 of file extension.c.

1284 {
1285  ExtensionVersionInfo *evi = NULL;
1286  ListCell *lc;
1287 
1288  foreach(lc, evi_list)
1289  {
1291 
1292  /* only vertices whose distance is still uncertain are candidates */
1293  if (evi2->distance_known)
1294  continue;
1295  /* remember the closest such vertex */
1296  if (evi == NULL ||
1297  evi->distance > evi2->distance)
1298  evi = evi2;
1299  }
1300 
1301  return evi;
1302 }

References ExtensionVersionInfo::distance, ExtensionVersionInfo::distance_known, and lfirst.

Referenced by find_update_path().

◆ get_required_extension()

static Oid get_required_extension ( char *  reqExtensionName,
char *  extensionName,
char *  origSchemaName,
bool  cascade,
List parents,
bool  is_create 
)
static

Definition at line 1804 of file extension.c.

1810 {
1811  Oid reqExtensionOid;
1812 
1813  reqExtensionOid = get_extension_oid(reqExtensionName, true);
1814  if (!OidIsValid(reqExtensionOid))
1815  {
1816  if (cascade)
1817  {
1818  /* Must install it. */
1819  ObjectAddress addr;
1820  List *cascade_parents;
1821  ListCell *lc;
1822 
1823  /* Check extension name validity before trying to cascade. */
1824  check_valid_extension_name(reqExtensionName);
1825 
1826  /* Check for cyclic dependency between extensions. */
1827  foreach(lc, parents)
1828  {
1829  char *pname = (char *) lfirst(lc);
1830 
1831  if (strcmp(pname, reqExtensionName) == 0)
1832  ereport(ERROR,
1833  (errcode(ERRCODE_INVALID_RECURSION),
1834  errmsg("cyclic dependency detected between extensions \"%s\" and \"%s\"",
1835  reqExtensionName, extensionName)));
1836  }
1837 
1838  ereport(NOTICE,
1839  (errmsg("installing required extension \"%s\"",
1840  reqExtensionName)));
1841 
1842  /* Add current extension to list of parents to pass down. */
1843  cascade_parents = lappend(list_copy(parents), extensionName);
1844 
1845  /*
1846  * Create the required extension. We propagate the SCHEMA option
1847  * if any, and CASCADE, but no other options.
1848  */
1849  addr = CreateExtensionInternal(reqExtensionName,
1850  origSchemaName,
1851  NULL,
1852  cascade,
1853  cascade_parents,
1854  is_create);
1855 
1856  /* Get its newly-assigned OID. */
1857  reqExtensionOid = addr.objectId;
1858  }
1859  else
1860  ereport(ERROR,
1861  (errcode(ERRCODE_UNDEFINED_OBJECT),
1862  errmsg("required extension \"%s\" is not installed",
1863  reqExtensionName),
1864  is_create ?
1865  errhint("Use CREATE EXTENSION ... CASCADE to install required extensions too.") : 0));
1866  }
1867 
1868  return reqExtensionOid;
1869 }
List * list_copy(const List *oldlist)
Definition: list.c:1573

References check_valid_extension_name(), CreateExtensionInternal(), ereport, errcode(), errhint(), errmsg(), ERROR, get_extension_oid(), lappend(), lfirst, list_copy(), NOTICE, ObjectAddress::objectId, and OidIsValid.

Referenced by ApplyExtensionUpdates(), and CreateExtensionInternal().

◆ identify_update_path()

static List* identify_update_path ( ExtensionControlFile control,
const char *  oldVersion,
const char *  newVersion 
)
static

Definition at line 1374 of file extension.c.

1376 {
1377  List *result;
1378  List *evi_list;
1379  ExtensionVersionInfo *evi_start;
1380  ExtensionVersionInfo *evi_target;
1381 
1382  /* Extract the version update graph from the script directory */
1383  evi_list = get_ext_ver_list(control);
1384 
1385  /* Initialize start and end vertices */
1386  evi_start = get_ext_ver_info(oldVersion, &evi_list);
1387  evi_target = get_ext_ver_info(newVersion, &evi_list);
1388 
1389  /* Find shortest path */
1390  result = find_update_path(evi_list, evi_start, evi_target, false, false);
1391 
1392  if (result == NIL)
1393  ereport(ERROR,
1394  (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
1395  errmsg("extension \"%s\" has no update path from version \"%s\" to version \"%s\"",
1396  control->name, oldVersion, newVersion)));
1397 
1398  return result;
1399 }

References ereport, errcode(), errmsg(), ERROR, find_update_path(), get_ext_ver_info(), get_ext_ver_list(), ExtensionControlFile::name, and NIL.

Referenced by ExecAlterExtensionStmt().

◆ InsertExtensionTuple()

ObjectAddress InsertExtensionTuple ( const char *  extName,
Oid  extOwner,
Oid  schemaOid,
bool  relocatable,
const char *  extVersion,
Datum  extConfig,
Datum  extCondition,
List requiredExtensions 
)

Definition at line 1973 of file extension.c.

1977 {
1978  Oid extensionOid;
1979  Relation rel;
1980  Datum values[Natts_pg_extension];
1981  bool nulls[Natts_pg_extension];
1982  HeapTuple tuple;
1983  ObjectAddress myself;
1984  ObjectAddress nsp;
1985  ObjectAddresses *refobjs;
1986  ListCell *lc;
1987 
1988  /*
1989  * Build and insert the pg_extension tuple
1990  */
1991  rel = table_open(ExtensionRelationId, RowExclusiveLock);
1992 
1993  memset(values, 0, sizeof(values));
1994  memset(nulls, 0, sizeof(nulls));
1995 
1996  extensionOid = GetNewOidWithIndex(rel, ExtensionOidIndexId,
1997  Anum_pg_extension_oid);
1998  values[Anum_pg_extension_oid - 1] = ObjectIdGetDatum(extensionOid);
1999  values[Anum_pg_extension_extname - 1] =
2001  values[Anum_pg_extension_extowner - 1] = ObjectIdGetDatum(extOwner);
2002  values[Anum_pg_extension_extnamespace - 1] = ObjectIdGetDatum(schemaOid);
2003  values[Anum_pg_extension_extrelocatable - 1] = BoolGetDatum(relocatable);
2004  values[Anum_pg_extension_extversion - 1] = CStringGetTextDatum(extVersion);
2005 
2006  if (extConfig == PointerGetDatum(NULL))
2007  nulls[Anum_pg_extension_extconfig - 1] = true;
2008  else
2009  values[Anum_pg_extension_extconfig - 1] = extConfig;
2010 
2011  if (extCondition == PointerGetDatum(NULL))
2012  nulls[Anum_pg_extension_extcondition - 1] = true;
2013  else
2014  values[Anum_pg_extension_extcondition - 1] = extCondition;
2015 
2016  tuple = heap_form_tuple(rel->rd_att, values, nulls);
2017 
2018  CatalogTupleInsert(rel, tuple);
2019 
2020  heap_freetuple(tuple);
2022 
2023  /*
2024  * Record dependencies on owner, schema, and prerequisite extensions
2025  */
2026  recordDependencyOnOwner(ExtensionRelationId, extensionOid, extOwner);
2027 
2028  refobjs = new_object_addresses();
2029 
2030  ObjectAddressSet(myself, ExtensionRelationId, extensionOid);
2031 
2032  ObjectAddressSet(nsp, NamespaceRelationId, schemaOid);
2033  add_exact_object_address(&nsp, refobjs);
2034 
2035  foreach(lc, requiredExtensions)
2036  {
2037  Oid reqext = lfirst_oid(lc);
2038  ObjectAddress otherext;
2039 
2040  ObjectAddressSet(otherext, ExtensionRelationId, reqext);
2041  add_exact_object_address(&otherext, refobjs);
2042  }
2043 
2044  /* Record all of them (this includes duplicate elimination) */
2046  free_object_addresses(refobjs);
2047 
2048  /* Post creation hook for new extension */
2049  InvokeObjectPostCreateHook(ExtensionRelationId, extensionOid, 0);
2050 
2051  return myself;
2052 }
Oid GetNewOidWithIndex(Relation relation, Oid indexId, AttrNumber oidcolumn)
Definition: catalog.c:419
void record_object_address_dependencies(const ObjectAddress *depender, ObjectAddresses *referenced, DependencyType behavior)
Definition: dependency.c:2742
void add_exact_object_address(const ObjectAddress *object, ObjectAddresses *addrs)
Definition: dependency.c:2533
void free_object_addresses(ObjectAddresses *addrs)
Definition: dependency.c:2773
HeapTuple heap_form_tuple(TupleDesc tupleDescriptor, const Datum *values, const bool *isnull)
Definition: heaptuple.c:1116
void heap_freetuple(HeapTuple htup)
Definition: heaptuple.c:1434
void CatalogTupleInsert(Relation heapRel, HeapTuple tup)
Definition: indexing.c:233
#define InvokeObjectPostCreateHook(classId, objectId, subId)
Definition: objectaccess.h:173
void recordDependencyOnOwner(Oid classId, Oid objectId, Oid owner)
Definition: pg_shdepend.c:168
TupleDesc rd_att
Definition: rel.h:112

References add_exact_object_address(), BoolGetDatum(), CatalogTupleInsert(), CStringGetDatum(), CStringGetTextDatum, DEPENDENCY_NORMAL, DirectFunctionCall1, free_object_addresses(), GetNewOidWithIndex(), heap_form_tuple(), heap_freetuple(), InvokeObjectPostCreateHook, lfirst_oid, namein(), new_object_addresses(), ObjectAddressSet, ObjectIdGetDatum(), PointerGetDatum(), RelationData::rd_att, record_object_address_dependencies(), recordDependencyOnOwner(), RowExclusiveLock, table_close(), table_open(), and values.

Referenced by binary_upgrade_create_empty_extension(), and CreateExtensionInternal().

◆ is_extension_control_filename()

static bool is_extension_control_filename ( const char *  filename)
static

Definition at line 316 of file extension.c.

317 {
318  const char *extension = strrchr(filename, '.');
319 
320  return (extension != NULL) && (strcmp(extension, ".control") == 0);
321 }

References filename.

Referenced by extension_file_exists(), pg_available_extension_versions(), and pg_available_extensions().

◆ is_extension_script_filename()

static bool is_extension_script_filename ( const char *  filename)
static

Definition at line 324 of file extension.c.

325 {
326  const char *extension = strrchr(filename, '.');
327 
328  return (extension != NULL) && (strcmp(extension, ".sql") == 0);
329 }

References filename.

Referenced by get_ext_ver_list().

◆ parse_extension_control_file()

static void parse_extension_control_file ( ExtensionControlFile control,
const char *  version 
)
static

Definition at line 432 of file extension.c.

434 {
435  char *filename;
436  FILE *file;
437  ConfigVariable *item,
438  *head = NULL,
439  *tail = NULL;
440 
441  /*
442  * Locate the file to read. Auxiliary files are optional.
443  */
444  if (version)
445  filename = get_extension_aux_control_filename(control, version);
446  else
448 
449  if ((file = AllocateFile(filename, "r")) == NULL)
450  {
451  if (errno == ENOENT)
452  {
453  /* no complaint for missing auxiliary file */
454  if (version)
455  {
456  pfree(filename);
457  return;
458  }
459 
460  /* missing control file indicates extension is not installed */
461  ereport(ERROR,
462  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
463  errmsg("extension \"%s\" is not available", control->name),
464  errdetail("Could not open extension control file \"%s\": %m.",
465  filename),
466  errhint("The extension must first be installed on the system where PostgreSQL is running.")));
467  }
468  ereport(ERROR,
470  errmsg("could not open extension control file \"%s\": %m",
471  filename)));
472  }
473 
474  /*
475  * Parse the file content, using GUC's file parsing code. We need not
476  * check the return value since any errors will be thrown at ERROR level.
477  */
479  &head, &tail);
480 
481  FreeFile(file);
482 
483  /*
484  * Convert the ConfigVariable list into ExtensionControlFile entries.
485  */
486  for (item = head; item != NULL; item = item->next)
487  {
488  if (strcmp(item->name, "directory") == 0)
489  {
490  if (version)
491  ereport(ERROR,
492  (errcode(ERRCODE_SYNTAX_ERROR),
493  errmsg("parameter \"%s\" cannot be set in a secondary extension control file",
494  item->name)));
495 
496  control->directory = pstrdup(item->value);
497  }
498  else if (strcmp(item->name, "default_version") == 0)
499  {
500  if (version)
501  ereport(ERROR,
502  (errcode(ERRCODE_SYNTAX_ERROR),
503  errmsg("parameter \"%s\" cannot be set in a secondary extension control file",
504  item->name)));
505 
506  control->default_version = pstrdup(item->value);
507  }
508  else if (strcmp(item->name, "module_pathname") == 0)
509  {
510  control->module_pathname = pstrdup(item->value);
511  }
512  else if (strcmp(item->name, "comment") == 0)
513  {
514  control->comment = pstrdup(item->value);
515  }
516  else if (strcmp(item->name, "schema") == 0)
517  {
518  control->schema = pstrdup(item->value);
519  }
520  else if (strcmp(item->name, "relocatable") == 0)
521  {
522  if (!parse_bool(item->value, &control->relocatable))
523  ereport(ERROR,
524  (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
525  errmsg("parameter \"%s\" requires a Boolean value",
526  item->name)));
527  }
528  else if (strcmp(item->name, "superuser") == 0)
529  {
530  if (!parse_bool(item->value, &control->superuser))
531  ereport(ERROR,
532  (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
533  errmsg("parameter \"%s\" requires a Boolean value",
534  item->name)));
535  }
536  else if (strcmp(item->name, "trusted") == 0)
537  {
538  if (!parse_bool(item->value, &control->trusted))
539  ereport(ERROR,
540  (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
541  errmsg("parameter \"%s\" requires a Boolean value",
542  item->name)));
543  }
544  else if (strcmp(item->name, "encoding") == 0)
545  {
546  control->encoding = pg_valid_server_encoding(item->value);
547  if (control->encoding < 0)
548  ereport(ERROR,
549  (errcode(ERRCODE_UNDEFINED_OBJECT),
550  errmsg("\"%s\" is not a valid encoding name",
551  item->value)));
552  }
553  else if (strcmp(item->name, "requires") == 0)
554  {
555  /* Need a modifiable copy of string */
556  char *rawnames = pstrdup(item->value);
557 
558  /* Parse string into list of identifiers */
559  if (!SplitIdentifierString(rawnames, ',', &control->requires))
560  {
561  /* syntax error in name list */
562  ereport(ERROR,
563  (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
564  errmsg("parameter \"%s\" must be a list of extension names",
565  item->name)));
566  }
567  }
568  else if (strcmp(item->name, "no_relocate") == 0)
569  {
570  /* Need a modifiable copy of string */
571  char *rawnames = pstrdup(item->value);
572 
573  /* Parse string into list of identifiers */
574  if (!SplitIdentifierString(rawnames, ',', &control->no_relocate))
575  {
576  /* syntax error in name list */
577  ereport(ERROR,
578  (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
579  errmsg("parameter \"%s\" must be a list of extension names",
580  item->name)));
581  }
582  }
583  else
584  ereport(ERROR,
585  (errcode(ERRCODE_SYNTAX_ERROR),
586  errmsg("unrecognized parameter \"%s\" in file \"%s\"",
587  item->name, filename)));
588  }
589 
590  FreeConfigVariables(head);
591 
592  if (control->relocatable && control->schema != NULL)
593  ereport(ERROR,
594  (errcode(ERRCODE_SYNTAX_ERROR),
595  errmsg("parameter \"schema\" cannot be specified when \"relocatable\" is true")));
596 
597  pfree(filename);
598 }
bool parse_bool(const char *value, bool *result)
Definition: bool.c:31
#define CONF_FILE_START_DEPTH
Definition: conffiles.h:17
int errcode_for_file_access(void)
Definition: elog.c:876
static char * get_extension_control_filename(const char *extname)
Definition: extension.c:345
static char * get_extension_aux_control_filename(ExtensionControlFile *control, const char *version)
Definition: extension.c:382
FILE * AllocateFile(const char *name, const char *mode)
Definition: fd.c:2606
int FreeFile(FILE *file)
Definition: fd.c:2804
void FreeConfigVariables(ConfigVariable *list)
bool ParseConfigFp(FILE *fp, const char *config_file, int depth, int elevel, ConfigVariable **head_p, ConfigVariable **tail_p)
#define pg_valid_server_encoding
Definition: pg_wchar.h:631
char * name
Definition: guc.h:137
struct ConfigVariable * next
Definition: guc.h:144
char * value
Definition: guc.h:138
bool SplitIdentifierString(char *rawstring, char separator, List **namelist)
Definition: varlena.c:3432

References AllocateFile(), ExtensionControlFile::comment, CONF_FILE_START_DEPTH, ExtensionControlFile::default_version, ExtensionControlFile::directory, ExtensionControlFile::encoding, ereport, errcode(), errcode_for_file_access(), errdetail(), errhint(), errmsg(), ERROR, filename, FreeConfigVariables(), FreeFile(), get_extension_aux_control_filename(), get_extension_control_filename(), ExtensionControlFile::module_pathname, ExtensionControlFile::name, ConfigVariable::name, ConfigVariable::next, ExtensionControlFile::no_relocate, parse_bool(), ParseConfigFp(), pfree(), pg_valid_server_encoding, pstrdup(), ExtensionControlFile::relocatable, ExtensionControlFile::requires, ExtensionControlFile::schema, SplitIdentifierString(), ExtensionControlFile::superuser, ExtensionControlFile::trusted, and ConfigVariable::value.

Referenced by read_extension_aux_control_file(), and read_extension_control_file().

◆ pg_available_extension_versions()

Datum pg_available_extension_versions ( PG_FUNCTION_ARGS  )

Definition at line 2195 of file extension.c.

2196 {
2197  ReturnSetInfo *rsinfo = (ReturnSetInfo *) fcinfo->resultinfo;
2198  char *location;
2199  DIR *dir;
2200  struct dirent *de;
2201 
2202  /* Build tuplestore to hold the result rows */
2203  InitMaterializedSRF(fcinfo, 0);
2204 
2205  location = get_extension_control_directory();
2206  dir = AllocateDir(location);
2207 
2208  /*
2209  * If the control directory doesn't exist, we want to silently return an
2210  * empty set. Any other error will be reported by ReadDir.
2211  */
2212  if (dir == NULL && errno == ENOENT)
2213  {
2214  /* do nothing */
2215  }
2216  else
2217  {
2218  while ((de = ReadDir(dir, location)) != NULL)
2219  {
2220  ExtensionControlFile *control;
2221  char *extname;
2222 
2223  if (!is_extension_control_filename(de->d_name))
2224  continue;
2225 
2226  /* extract extension name from 'name.control' filename */
2227  extname = pstrdup(de->d_name);
2228  *strrchr(extname, '.') = '\0';
2229 
2230  /* ignore it if it's an auxiliary control file */
2231  if (strstr(extname, "--"))
2232  continue;
2233 
2234  /* read the control file */
2235  control = read_extension_control_file(extname);
2236 
2237  /* scan extension's script directory for install scripts */
2239  rsinfo->setDesc);
2240  }
2241 
2242  FreeDir(dir);
2243  }
2244 
2245  return (Datum) 0;
2246 }
static void get_available_versions_for_extension(ExtensionControlFile *pcontrol, Tuplestorestate *tupstore, TupleDesc tupdesc)
Definition: extension.c:2253
void InitMaterializedSRF(FunctionCallInfo fcinfo, bits32 flags)
Definition: funcapi.c:76
TupleDesc setDesc
Definition: execnodes.h:343
Tuplestorestate * setResult
Definition: execnodes.h:342

References AllocateDir(), FreeDir(), get_available_versions_for_extension(), get_extension_control_directory(), InitMaterializedSRF(), is_extension_control_filename(), pstrdup(), read_extension_control_file(), ReadDir(), ReturnSetInfo::setDesc, and ReturnSetInfo::setResult.

◆ pg_available_extensions()

Datum pg_available_extensions ( PG_FUNCTION_ARGS  )

Definition at line 2115 of file extension.c.

2116 {
2117  ReturnSetInfo *rsinfo = (ReturnSetInfo *) fcinfo->resultinfo;
2118  char *location;
2119  DIR *dir;
2120  struct dirent *de;
2121 
2122  /* Build tuplestore to hold the result rows */
2123  InitMaterializedSRF(fcinfo, 0);
2124 
2125  location = get_extension_control_directory();
2126  dir = AllocateDir(location);
2127 
2128  /*
2129  * If the control directory doesn't exist, we want to silently return an
2130  * empty set. Any other error will be reported by ReadDir.
2131  */
2132  if (dir == NULL && errno == ENOENT)
2133  {
2134  /* do nothing */
2135  }
2136  else
2137  {
2138  while ((de = ReadDir(dir, location)) != NULL)
2139  {
2140  ExtensionControlFile *control;
2141  char *extname;
2142  Datum values[3];
2143  bool nulls[3];
2144 
2145  if (!is_extension_control_filename(de->d_name))
2146  continue;
2147 
2148  /* extract extension name from 'name.control' filename */
2149  extname = pstrdup(de->d_name);
2150  *strrchr(extname, '.') = '\0';
2151 
2152  /* ignore it if it's an auxiliary control file */
2153  if (strstr(extname, "--"))
2154  continue;
2155 
2156  control = read_extension_control_file(extname);
2157 
2158  memset(values, 0, sizeof(values));
2159  memset(nulls, 0, sizeof(nulls));
2160 
2161  /* name */
2163  CStringGetDatum(control->name));
2164  /* default_version */
2165  if (control->default_version == NULL)
2166  nulls[1] = true;
2167  else
2169  /* comment */
2170  if (control->comment == NULL)
2171  nulls[2] = true;
2172  else
2173  values[2] = CStringGetTextDatum(control->comment);
2174 
2175  tuplestore_putvalues(rsinfo->setResult, rsinfo->setDesc,
2176  values, nulls);
2177  }
2178 
2179  FreeDir(dir);
2180  }
2181 
2182  return (Datum) 0;
2183 }

References AllocateDir(), ExtensionControlFile::comment, CStringGetDatum(), CStringGetTextDatum, ExtensionControlFile::default_version, DirectFunctionCall1, FreeDir(), get_extension_control_directory(), InitMaterializedSRF(), is_extension_control_filename(), ExtensionControlFile::name, namein(), pstrdup(), read_extension_control_file(), ReadDir(), ReturnSetInfo::setDesc, ReturnSetInfo::setResult, tuplestore_putvalues(), and values.

◆ pg_extension_config_dump()

Datum pg_extension_config_dump ( PG_FUNCTION_ARGS  )

Definition at line 2531 of file extension.c.

2532 {
2533  Oid tableoid = PG_GETARG_OID(0);
2534  text *wherecond = PG_GETARG_TEXT_PP(1);
2535  char *tablename;
2536  Relation extRel;
2537  ScanKeyData key[1];
2538  SysScanDesc extScan;
2539  HeapTuple extTup;
2540  Datum arrayDatum;
2541  Datum elementDatum;
2542  int arrayLength;
2543  int arrayIndex;
2544  bool isnull;
2545  Datum repl_val[Natts_pg_extension];
2546  bool repl_null[Natts_pg_extension];
2547  bool repl_repl[Natts_pg_extension];
2548  ArrayType *a;
2549 
2550  /*
2551  * We only allow this to be called from an extension's SQL script. We
2552  * shouldn't need any permissions check beyond that.
2553  */
2554  if (!creating_extension)
2555  ereport(ERROR,
2556  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2557  errmsg("%s can only be called from an SQL script executed by CREATE EXTENSION",
2558  "pg_extension_config_dump()")));
2559 
2560  /*
2561  * Check that the table exists and is a member of the extension being
2562  * created. This ensures that we don't need to register an additional
2563  * dependency to protect the extconfig entry.
2564  */
2565  tablename = get_rel_name(tableoid);
2566  if (tablename == NULL)
2567  ereport(ERROR,
2569  errmsg("OID %u does not refer to a table", tableoid)));
2570  if (getExtensionOfObject(RelationRelationId, tableoid) !=
2572  ereport(ERROR,
2573  (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
2574  errmsg("table \"%s\" is not a member of the extension being created",
2575  tablename)));
2576 
2577  /*
2578  * Add the table OID and WHERE condition to the extension's extconfig and
2579  * extcondition arrays.
2580  *
2581  * If the table is already in extconfig, treat this as an update of the
2582  * WHERE condition.
2583  */
2584 
2585  /* Find the pg_extension tuple */
2586  extRel = table_open(ExtensionRelationId, RowExclusiveLock);
2587 
2588  ScanKeyInit(&key[0],
2589  Anum_pg_extension_oid,
2590  BTEqualStrategyNumber, F_OIDEQ,
2592 
2593  extScan = systable_beginscan(extRel, ExtensionOidIndexId, true,
2594  NULL, 1, key);
2595 
2596  extTup = systable_getnext(extScan);
2597 
2598  if (!HeapTupleIsValid(extTup)) /* should not happen */
2599  elog(ERROR, "could not find tuple for extension %u",
2601 
2602  memset(repl_val, 0, sizeof(repl_val));
2603  memset(repl_null, false, sizeof(repl_null));
2604  memset(repl_repl, false, sizeof(repl_repl));
2605 
2606  /* Build or modify the extconfig value */
2607  elementDatum = ObjectIdGetDatum(tableoid);
2608 
2609  arrayDatum = heap_getattr(extTup, Anum_pg_extension_extconfig,
2610  RelationGetDescr(extRel), &isnull);
2611  if (isnull)
2612  {
2613  /* Previously empty extconfig, so build 1-element array */
2614  arrayLength = 0;
2615  arrayIndex = 1;
2616 
2617  a = construct_array_builtin(&elementDatum, 1, OIDOID);
2618  }
2619  else
2620  {
2621  /* Modify or extend existing extconfig array */
2622  Oid *arrayData;
2623  int i;
2624 
2625  a = DatumGetArrayTypeP(arrayDatum);
2626 
2627  arrayLength = ARR_DIMS(a)[0];
2628  if (ARR_NDIM(a) != 1 ||
2629  ARR_LBOUND(a)[0] != 1 ||
2630  arrayLength < 0 ||
2631  ARR_HASNULL(a) ||
2632  ARR_ELEMTYPE(a) != OIDOID)
2633  elog(ERROR, "extconfig is not a 1-D Oid array");
2634  arrayData = (Oid *) ARR_DATA_PTR(a);
2635 
2636  arrayIndex = arrayLength + 1; /* set up to add after end */
2637 
2638  for (i = 0; i < arrayLength; i++)
2639  {
2640  if (arrayData[i] == tableoid)
2641  {
2642  arrayIndex = i + 1; /* replace this element instead */
2643  break;
2644  }
2645  }
2646 
2647  a = array_set(a, 1, &arrayIndex,
2648  elementDatum,
2649  false,
2650  -1 /* varlena array */ ,
2651  sizeof(Oid) /* OID's typlen */ ,
2652  true /* OID's typbyval */ ,
2653  TYPALIGN_INT /* OID's typalign */ );
2654  }
2655  repl_val[Anum_pg_extension_extconfig - 1] = PointerGetDatum(a);
2656  repl_repl[Anum_pg_extension_extconfig - 1] = true;
2657 
2658  /* Build or modify the extcondition value */
2659  elementDatum = PointerGetDatum(wherecond);
2660 
2661  arrayDatum = heap_getattr(extTup, Anum_pg_extension_extcondition,
2662  RelationGetDescr(extRel), &isnull);
2663  if (isnull)
2664  {
2665  if (arrayLength != 0)
2666  elog(ERROR, "extconfig and extcondition arrays do not match");
2667 
2668  a = construct_array_builtin(&elementDatum, 1, TEXTOID);
2669  }
2670  else
2671  {
2672  a = DatumGetArrayTypeP(arrayDatum);
2673 
2674  if (ARR_NDIM(a) != 1 ||
2675  ARR_LBOUND(a)[0] != 1 ||
2676  ARR_HASNULL(a) ||
2677  ARR_ELEMTYPE(a) != TEXTOID)
2678  elog(ERROR, "extcondition is not a 1-D text array");
2679  if (ARR_DIMS(a)[0] != arrayLength)
2680  elog(ERROR, "extconfig and extcondition arrays do not match");
2681 
2682  /* Add or replace at same index as in extconfig */
2683  a = array_set(a, 1, &arrayIndex,
2684  elementDatum,
2685  false,
2686  -1 /* varlena array */ ,
2687  -1 /* TEXT's typlen */ ,
2688  false /* TEXT's typbyval */ ,
2689  TYPALIGN_INT /* TEXT's typalign */ );
2690  }
2691  repl_val[Anum_pg_extension_extcondition - 1] = PointerGetDatum(a);
2692  repl_repl[Anum_pg_extension_extcondition - 1] = true;
2693 
2694  extTup = heap_modify_tuple(extTup, RelationGetDescr(extRel),
2695  repl_val, repl_null, repl_repl);
2696 
2697  CatalogTupleUpdate(extRel, &extTup->t_self, extTup);
2698 
2699  systable_endscan(extScan);
2700 
2701  table_close(extRel, RowExclusiveLock);
2702 
2703  PG_RETURN_VOID();
2704 }
ArrayType * array_set(ArrayType *array, int nSubscripts, int *indx, Datum dataValue, bool isNull, int arraytyplen, int elmlen, bool elmbyval, char elmalign)
Definition: arrayfuncs.c:3163
#define PG_RETURN_VOID()
Definition: fmgr.h:349
#define PG_GETARG_OID(n)
Definition: fmgr.h:275
#define PG_GETARG_TEXT_PP(n)
Definition: fmgr.h:309
char * get_rel_name(Oid relid)
Definition: lsyscache.c:1928
#define ERRCODE_UNDEFINED_TABLE
Definition: pgbench.c:78
Definition: c.h:678

References a, ARR_DATA_PTR, ARR_DIMS, ARR_ELEMTYPE, ARR_HASNULL, ARR_LBOUND, ARR_NDIM, array_set(), BTEqualStrategyNumber, CatalogTupleUpdate(), construct_array_builtin(), creating_extension, CurrentExtensionObject, DatumGetArrayTypeP, elog, ereport, errcode(), ERRCODE_UNDEFINED_TABLE, errmsg(), ERROR, get_rel_name(), getExtensionOfObject(), heap_getattr(), heap_modify_tuple(), HeapTupleIsValid, i, sort-test::key, ObjectIdGetDatum(), PG_GETARG_OID, PG_GETARG_TEXT_PP, PG_RETURN_VOID, PointerGetDatum(), RelationGetDescr, RowExclusiveLock, ScanKeyInit(), systable_beginscan(), systable_endscan(), systable_getnext(), HeapTupleData::t_self, table_close(), and table_open().

◆ pg_extension_update_paths()

Datum pg_extension_update_paths ( PG_FUNCTION_ARGS  )

Definition at line 2446 of file extension.c.

2447 {
2448  Name extname = PG_GETARG_NAME(0);
2449  ReturnSetInfo *rsinfo = (ReturnSetInfo *) fcinfo->resultinfo;
2450  List *evi_list;
2451  ExtensionControlFile *control;
2452  ListCell *lc1;
2453 
2454  /* Check extension name validity before any filesystem access */
2456 
2457  /* Build tuplestore to hold the result rows */
2458  InitMaterializedSRF(fcinfo, 0);
2459 
2460  /* Read the extension's control file */
2461  control = read_extension_control_file(NameStr(*extname));
2462 
2463  /* Extract the version update graph from the script directory */
2464  evi_list = get_ext_ver_list(control);
2465 
2466  /* Iterate over all pairs of versions */
2467  foreach(lc1, evi_list)
2468  {
2470  ListCell *lc2;
2471 
2472  foreach(lc2, evi_list)
2473  {
2475  List *path;
2476  Datum values[3];
2477  bool nulls[3];
2478 
2479  if (evi1 == evi2)
2480  continue;
2481 
2482  /* Find shortest path from evi1 to evi2 */
2483  path = find_update_path(evi_list, evi1, evi2, false, true);
2484 
2485  /* Emit result row */
2486  memset(values, 0, sizeof(values));
2487  memset(nulls, 0, sizeof(nulls));
2488 
2489  /* source */
2490  values[0] = CStringGetTextDatum(evi1->name);
2491  /* target */
2492  values[1] = CStringGetTextDatum(evi2->name);
2493  /* path */
2494  if (path == NIL)
2495  nulls[2] = true;
2496  else
2497  {
2498  StringInfoData pathbuf;
2499  ListCell *lcv;
2500 
2501  initStringInfo(&pathbuf);
2502  /* The path doesn't include start vertex, but show it */
2503  appendStringInfoString(&pathbuf, evi1->name);
2504  foreach(lcv, path)
2505  {
2506  char *versionName = (char *) lfirst(lcv);
2507 
2508  appendStringInfoString(&pathbuf, "--");
2509  appendStringInfoString(&pathbuf, versionName);
2510  }
2511  values[2] = CStringGetTextDatum(pathbuf.data);
2512  pfree(pathbuf.data);
2513  }
2514 
2515  tuplestore_putvalues(rsinfo->setResult, rsinfo->setDesc,
2516  values, nulls);
2517  }
2518  }
2519 
2520  return (Datum) 0;
2521 }
#define PG_GETARG_NAME(n)
Definition: fmgr.h:278
Definition: c.h:732

References appendStringInfoString(), check_valid_extension_name(), CStringGetTextDatum, StringInfoData::data, find_update_path(), get_ext_ver_list(), InitMaterializedSRF(), initStringInfo(), lfirst, ExtensionVersionInfo::name, NameStr, NIL, pfree(), PG_GETARG_NAME, read_extension_control_file(), ReturnSetInfo::setDesc, ReturnSetInfo::setResult, tuplestore_putvalues(), and values.

◆ read_extension_aux_control_file()

static ExtensionControlFile* read_extension_aux_control_file ( const ExtensionControlFile pcontrol,
const char *  version 
)
static

Definition at line 633 of file extension.c.

635 {
636  ExtensionControlFile *acontrol;
637 
638  /*
639  * Flat-copy the struct. Pointer fields share values with original.
640  */
641  acontrol = (ExtensionControlFile *) palloc(sizeof(ExtensionControlFile));
642  memcpy(acontrol, pcontrol, sizeof(ExtensionControlFile));
643 
644  /*
645  * Parse the auxiliary control file, overwriting struct fields
646  */
647  parse_extension_control_file(acontrol, version);
648 
649  return acontrol;
650 }
static void parse_extension_control_file(ExtensionControlFile *control, const char *version)
Definition: extension.c:432

References palloc(), and parse_extension_control_file().

Referenced by ApplyExtensionUpdates(), CreateExtensionInternal(), and get_available_versions_for_extension().

◆ read_extension_control_file()

static ExtensionControlFile* read_extension_control_file ( const char *  extname)
static

Definition at line 604 of file extension.c.

605 {
606  ExtensionControlFile *control;
607 
608  /*
609  * Set up default values. Pointer fields are initially null.
610  */
611  control = (ExtensionControlFile *) palloc0(sizeof(ExtensionControlFile));
612  control->name = pstrdup(extname);
613  control->relocatable = false;
614  control->superuser = true;
615  control->trusted = false;
616  control->encoding = -1;
617 
618  /*
619  * Parse the primary control file.
620  */
621  parse_extension_control_file(control, NULL);
622 
623  return control;
624 }
void * palloc0(Size size)
Definition: mcxt.c:1347

References ExtensionControlFile::encoding, ExtensionControlFile::name, palloc0(), parse_extension_control_file(), pstrdup(), ExtensionControlFile::relocatable, ExtensionControlFile::superuser, and ExtensionControlFile::trusted.

Referenced by AlterExtensionNamespace(), CreateExtensionInternal(), ExecAlterExtensionStmt(), pg_available_extension_versions(), pg_available_extensions(), and pg_extension_update_paths().

◆ read_extension_script_file()

static char* read_extension_script_file ( const ExtensionControlFile control,
const char *  filename 
)
static

Definition at line 656 of file extension.c.

658 {
659  int src_encoding;
660  char *src_str;
661  char *dest_str;
662  int len;
663 
664  src_str = read_whole_file(filename, &len);
665 
666  /* use database encoding if not given */
667  if (control->encoding < 0)
668  src_encoding = GetDatabaseEncoding();
669  else
670  src_encoding = control->encoding;
671 
672  /* make sure that source string is valid in the expected encoding */
673  (void) pg_verify_mbstr(src_encoding, src_str, len, false);
674 
675  /*
676  * Convert the encoding to the database encoding. read_whole_file
677  * null-terminated the string, so if no conversion happens the string is
678  * valid as is.
679  */
680  dest_str = pg_any_to_server(src_str, len, src_encoding);
681 
682  return dest_str;
683 }
static char * read_whole_file(const char *filename, int *length)
Definition: extension.c:3624
char * pg_any_to_server(const char *s, int len, int encoding)
Definition: mbutils.c:676
int GetDatabaseEncoding(void)
Definition: mbutils.c:1261
bool pg_verify_mbstr(int encoding, const char *mbstr, int len, bool noError)
Definition: mbutils.c:1566
const void size_t len

References ExtensionControlFile::encoding, filename, GetDatabaseEncoding(), len, pg_any_to_server(), pg_verify_mbstr(), and read_whole_file().

Referenced by execute_extension_script().

◆ read_whole_file()

static char * read_whole_file ( const char *  filename,
int *  length 
)
static

Definition at line 3624 of file extension.c.

3625 {
3626  char *buf;
3627  FILE *file;
3628  size_t bytes_to_read;
3629  struct stat fst;
3630 
3631  if (stat(filename, &fst) < 0)
3632  ereport(ERROR,
3634  errmsg("could not stat file \"%s\": %m", filename)));
3635 
3636  if (fst.st_size > (MaxAllocSize - 1))
3637  ereport(ERROR,
3638  (errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED),
3639  errmsg("file \"%s\" is too large", filename)));
3640  bytes_to_read = (size_t) fst.st_size;
3641 
3642  if ((file = AllocateFile(filename, PG_BINARY_R)) == NULL)
3643  ereport(ERROR,
3645  errmsg("could not open file \"%s\" for reading: %m",
3646  filename)));
3647 
3648  buf = (char *) palloc(bytes_to_read + 1);
3649 
3650  *length = fread(buf, 1, bytes_to_read, file);
3651 
3652  if (ferror(file))
3653  ereport(ERROR,
3655  errmsg("could not read file \"%s\": %m", filename)));
3656 
3657  FreeFile(file);
3658 
3659  buf[*length] = '\0';
3660  return buf;
3661 }
#define PG_BINARY_R
Definition: c.h:1266
if(TABLE==NULL||TABLE_index==NULL)
Definition: isn.c:77
#define MaxAllocSize
Definition: memutils.h:40
static char * buf
Definition: pg_test_fsync.c:73

References AllocateFile(), buf, ereport, errcode(), errcode_for_file_access(), errmsg(), ERROR, filename, FreeFile(), if(), MaxAllocSize, palloc(), PG_BINARY_R, stat::st_size, and stat.

Referenced by read_extension_script_file().

◆ RemoveExtensionById()

void RemoveExtensionById ( Oid  extId)

Definition at line 2061 of file extension.c.

2062 {
2063  Relation rel;
2064  SysScanDesc scandesc;
2065  HeapTuple tuple;
2066  ScanKeyData entry[1];
2067 
2068  /*
2069  * Disallow deletion of any extension that's currently open for insertion;
2070  * else subsequent executions of recordDependencyOnCurrentExtension()
2071  * could create dangling pg_depend records that refer to a no-longer-valid
2072  * pg_extension OID. This is needed not so much because we think people
2073  * might write "DROP EXTENSION foo" in foo's own script files, as because
2074  * errors in dependency management in extension script files could give
2075  * rise to cases where an extension is dropped as a result of recursing
2076  * from some contained object. Because of that, we must test for the case
2077  * here, not at some higher level of the DROP EXTENSION command.
2078  */
2079  if (extId == CurrentExtensionObject)
2080  ereport(ERROR,
2081  (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
2082  errmsg("cannot drop extension \"%s\" because it is being modified",
2083  get_extension_name(extId))));
2084 
2085  rel = table_open(ExtensionRelationId, RowExclusiveLock);
2086 
2087  ScanKeyInit(&entry[0],
2088  Anum_pg_extension_oid,
2089  BTEqualStrategyNumber, F_OIDEQ,
2090  ObjectIdGetDatum(extId));
2091  scandesc = systable_beginscan(rel, ExtensionOidIndexId, true,
2092  NULL, 1, entry);
2093 
2094  tuple = systable_getnext(scandesc);
2095 
2096  /* We assume that there can be at most one matching tuple */
2097  if (HeapTupleIsValid(tuple))
2098  CatalogTupleDelete(rel, &tuple->t_self);
2099 
2100  systable_endscan(scandesc);
2101 
2103 }
void CatalogTupleDelete(Relation heapRel, ItemPointer tid)
Definition: indexing.c:365

References BTEqualStrategyNumber, CatalogTupleDelete(), CurrentExtensionObject, ereport, errcode(), errmsg(), ERROR, get_extension_name(), HeapTupleIsValid, ObjectIdGetDatum(), RowExclusiveLock, ScanKeyInit(), systable_beginscan(), systable_endscan(), systable_getnext(), HeapTupleData::t_self, table_close(), and table_open().

Referenced by doDeletion().

◆ script_error_callback()

static void script_error_callback ( void *  arg)
static

Definition at line 689 of file extension.c.

690 {
692  const char *query = callback_arg->sql;
693  int location = callback_arg->stmt_location;
694  int len = callback_arg->stmt_len;
695  int syntaxerrposition;
696  const char *lastslash;
697 
698  /*
699  * If there is a syntax error position, convert to internal syntax error;
700  * otherwise report the current query as an item of context stack.
701  *
702  * Note: we'll provide no context except the filename if there's neither
703  * an error position nor any known current query. That shouldn't happen
704  * though: all errors reported during raw parsing should come with an
705  * error position.
706  */
707  syntaxerrposition = geterrposition();
708  if (syntaxerrposition > 0)
709  {
710  /*
711  * If we do not know the bounds of the current statement (as would
712  * happen for an error occurring during initial raw parsing), we have
713  * to use a heuristic to decide how much of the script to show. We'll
714  * also use the heuristic in the unlikely case that syntaxerrposition
715  * is outside what we think the statement bounds are.
716  */
717  if (location < 0 || syntaxerrposition < location ||
718  (len > 0 && syntaxerrposition > location + len))
719  {
720  /*
721  * Our heuristic is pretty simple: look for semicolon-newline
722  * sequences, and break at the last one strictly before
723  * syntaxerrposition and the first one strictly after. It's
724  * certainly possible to fool this with semicolon-newline embedded
725  * in a string literal, but it seems better to do this than to
726  * show the entire extension script.
727  */
728  int slen = strlen(query);
729 
730  location = len = 0;
731  for (int loc = 0; loc < slen; loc++)
732  {
733  if (query[loc] != ';')
734  continue;
735  if (query[loc + 1] == '\r')
736  loc++;
737  if (query[loc + 1] == '\n')
738  {
739  int bkpt = loc + 2;
740 
741  if (bkpt < syntaxerrposition)
742  location = bkpt;
743  else if (bkpt > syntaxerrposition)
744  {
745  len = bkpt - location;
746  break; /* no need to keep searching */
747  }
748  }
749  }
750  }
751 
752  /* Trim leading/trailing whitespace, for consistency */
753  query = CleanQuerytext(query, &location, &len);
754 
755  /*
756  * Adjust syntaxerrposition. It shouldn't be pointing into the
757  * whitespace we just trimmed, but cope if it is.
758  */
759  syntaxerrposition -= location;
760  if (syntaxerrposition < 0)
761  syntaxerrposition = 0;
762  else if (syntaxerrposition > len)
763  syntaxerrposition = len;
764 
765  /* And report. */
766  errposition(0);
767  internalerrposition(syntaxerrposition);
768  internalerrquery(pnstrdup(query, len));
769  }
770  else if (location >= 0)
771  {
772  /*
773  * Since no syntax cursor will be shown, it's okay and helpful to trim
774  * the reported query string to just the current statement.
775  */
776  query = CleanQuerytext(query, &location, &len);
777  errcontext("SQL statement \"%.*s\"", len, query);
778  }
779 
780  /*
781  * Trim the reported file name to remove the path. We know that
782  * get_extension_script_filename() inserted a '/', regardless of whether
783  * we're on Windows.
784  */
785  lastslash = strrchr(callback_arg->filename, '/');
786  if (lastslash)
787  lastslash++;
788  else
789  lastslash = callback_arg->filename; /* shouldn't happen, but cope */
790 
791  /*
792  * If we have a location (which, as said above, we really always should)
793  * then report a line number to aid in localizing problems in big scripts.
794  */
795  if (location >= 0)
796  {
797  int linenumber = 1;
798 
799  for (query = callback_arg->sql; *query; query++)
800  {
801  if (--location < 0)
802  break;
803  if (*query == '\n')
804  linenumber++;
805  }
806  errcontext("extension script file \"%s\", near line %d",
807  lastslash, linenumber);
808  }
809  else
810  errcontext("extension script file \"%s\"", lastslash);
811 }
int internalerrquery(const char *query)
Definition: elog.c:1482
int internalerrposition(int cursorpos)
Definition: elog.c:1462
int geterrposition(void)
Definition: elog.c:1595
int errposition(int cursorpos)
Definition: elog.c:1446
#define errcontext
Definition: elog.h:196
char * pnstrdup(const char *in, Size len)
Definition: mcxt.c:1707
void * arg
const char * CleanQuerytext(const char *query, int *location, int *len)

References arg, CleanQuerytext(), errcontext, errposition(), script_error_callback_arg::filename, geterrposition(), internalerrposition(), internalerrquery(), len, pnstrdup(), script_error_callback_arg::sql, script_error_callback_arg::stmt_len, and script_error_callback_arg::stmt_location.

Referenced by execute_sql_string().

Variable Documentation

◆ creating_extension

◆ CurrentExtensionObject