PostgreSQL Source Code git master
Loading...
Searching...
No Matches
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_proc.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/pg_list.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/inval.h"
#include "utils/lsyscache.h"
#include "utils/memutils.h"
#include "utils/rel.h"
#include "utils/snapmgr.h"
#include "utils/syscache.h"
#include "utils/tuplestore.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
 
struct  ExtensionLocation
 
struct  ExtensionSiblingCache
 

Typedefs

typedef struct ExtensionControlFile ExtensionControlFile
 
typedef struct ExtensionVersionInfo ExtensionVersionInfo
 
typedef struct ExtensionSiblingCache ExtensionSiblingCache
 

Functions

static void ext_sibling_callback (Datum arg, SysCacheIdentifier cacheid, uint32 hashvalue)
 
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, ExtensionLocation *location)
 
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 charread_whole_file (const char *filename, int *length)
 
static ExtensionControlFilenew_ExtensionControlFile (const char *extname)
 
charfind_in_paths (const char *basename, List *paths)
 
static charget_extension_location (ExtensionLocation *loc)
 
Oid get_extension_oid (const char *extname, bool missing_ok)
 
charget_extension_name (Oid ext_oid)
 
Oid get_extension_schema (Oid ext_oid)
 
Oid get_function_sibling_type (Oid funcoid, const char *typname)
 
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 Listget_extension_control_directories (void)
 
static charfind_extension_control_filename (ExtensionControlFile *control)
 
static charget_extension_script_directory (ExtensionControlFile *control)
 
static charget_extension_aux_control_filename (ExtensionControlFile *control, const char *version)
 
static charget_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 charread_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)
 
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)
 
Datum pg_get_loaded_modules (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

charExtension_control_path
 
bool creating_extension = false
 
Oid CurrentExtensionObject = InvalidOid
 
static ExtensionSiblingCacheext_sibling_list = NULL
 

Typedef Documentation

◆ ExtensionControlFile

◆ ExtensionSiblingCache

◆ ExtensionVersionInfo

Function Documentation

◆ AlterExtensionNamespace()

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

Definition at line 3256 of file extension.c.

3257{
3259 Oid nspOid;
3260 Oid oldNspOid;
3263 ScanKeyData key[2];
3272
3274
3275 nspOid = LookupCreationNamespace(newschema);
3276
3277 /*
3278 * Permission check: must own extension. Note that we don't bother to
3279 * check ownership of the individual member objects ...
3280 */
3284
3285 /* Permission check: must have creation rights in target namespace */
3287 if (aclresult != ACLCHECK_OK)
3289
3290 /*
3291 * If the schema is currently a member of the extension, disallow moving
3292 * the extension into the schema. That would create a dependency loop.
3293 */
3295 ereport(ERROR,
3297 errmsg("cannot move extension \"%s\" into schema \"%s\" "
3298 "because the extension contains the schema",
3299 extensionName, newschema)));
3300
3301 /* Locate the pg_extension tuple */
3303
3304 ScanKeyInit(&key[0],
3308
3310 NULL, 1, key);
3311
3313
3314 if (!HeapTupleIsValid(extTup)) /* should not happen */
3315 elog(ERROR, "could not find tuple for extension %u",
3316 extensionOid);
3317
3318 /* Copy tuple so we can modify it below */
3321
3323
3324 /*
3325 * If the extension is already in the target schema, just silently do
3326 * nothing.
3327 */
3328 if (extForm->extnamespace == nspOid)
3329 {
3331 return InvalidObjectAddress;
3332 }
3333
3334 /* Check extension is supposed to be relocatable */
3335 if (!extForm->extrelocatable)
3336 ereport(ERROR,
3338 errmsg("extension \"%s\" does not support SET SCHEMA",
3339 NameStr(extForm->extname))));
3340
3342
3343 /* store the OID of the namespace to-be-changed */
3344 oldNspOid = extForm->extnamespace;
3345
3346 /*
3347 * Scan pg_depend to find objects that depend directly on the extension,
3348 * and alter each one's schema.
3349 */
3351
3352 ScanKeyInit(&key[0],
3356 ScanKeyInit(&key[1],
3360
3362 NULL, 2, key);
3363
3365 {
3369
3370 /*
3371 * If a dependent extension has a no_relocate request for this
3372 * extension, disallow SET SCHEMA. (XXX it's a bit ugly to do this in
3373 * the same loop that's actually executing the renames: we may detect
3374 * the error condition only after having expended a fair amount of
3375 * work. However, the alternative is to do two scans of pg_depend,
3376 * which seems like optimizing for failure cases. The rename work
3377 * will all roll back cleanly enough if we do fail here.)
3378 */
3379 if (pg_depend->deptype == DEPENDENCY_NORMAL &&
3380 pg_depend->classid == ExtensionRelationId)
3381 {
3382 char *depextname = get_extension_name(pg_depend->objid);
3384 ListCell *lc;
3385
3387 foreach(lc, dcontrol->no_relocate)
3388 {
3389 char *nrextname = (char *) lfirst(lc);
3390
3391 if (strcmp(nrextname, NameStr(extForm->extname)) == 0)
3392 {
3393 ereport(ERROR,
3395 errmsg("cannot SET SCHEMA of extension \"%s\" because other extensions prevent it",
3396 NameStr(extForm->extname)),
3397 errdetail("Extension \"%s\" requests no relocation of extension \"%s\".",
3398 depextname,
3399 NameStr(extForm->extname))));
3400 }
3401 }
3402 }
3403
3404 /*
3405 * Otherwise, ignore non-membership dependencies. (Currently, the
3406 * only other case we could see here is a normal dependency from
3407 * another extension.)
3408 */
3409 if (pg_depend->deptype != DEPENDENCY_EXTENSION)
3410 continue;
3411
3412 dep.classId = pg_depend->classid;
3413 dep.objectId = pg_depend->objid;
3414 dep.objectSubId = pg_depend->objsubid;
3415
3416 if (dep.objectSubId != 0) /* should not happen */
3417 elog(ERROR, "extension should not have a sub-object dependency");
3418
3419 /* Relocate the object */
3421 dep.objectId,
3422 nspOid,
3423 objsMoved);
3424
3425 /*
3426 * If not all the objects had the same old namespace (ignoring any
3427 * that are not in namespaces or are dependent types), complain.
3428 */
3430 ereport(ERROR,
3432 errmsg("extension \"%s\" does not support SET SCHEMA",
3433 NameStr(extForm->extname)),
3434 errdetail("%s is not in the extension's schema \"%s\"",
3435 getObjectDescription(&dep, false),
3437 }
3438
3439 /* report old schema, if caller wants it */
3440 if (oldschema)
3442
3444
3446
3447 /* Now adjust pg_extension.extnamespace */
3448 extForm->extnamespace = nspOid;
3449
3451
3453
3454 /* update dependency to point to the new schema */
3457 elog(ERROR, "could not change schema dependency for extension %s",
3458 NameStr(extForm->extname));
3459
3461
3463
3464 return extAddr;
3465}
AclResult
Definition acl.h:183
@ ACLCHECK_OK
Definition acl.h:184
@ ACLCHECK_NOT_OWNER
Definition acl.h:186
void aclcheck_error(AclResult aclerr, ObjectType objtype, const char *objectname)
Definition aclchk.c:2672
AclResult object_aclcheck(Oid classid, Oid objectid, Oid roleid, AclMode mode)
Definition aclchk.c:3879
bool object_ownercheck(Oid classid, Oid objectid, Oid roleid)
Definition aclchk.c:4133
Oid AlterObjectNamespace_oid(Oid classId, Oid objid, Oid nspOid, ObjectAddresses *objsMoved)
Definition alter.c:621
#define NameStr(name)
Definition c.h:835
ObjectAddresses * new_object_addresses(void)
@ DEPENDENCY_EXTENSION
Definition dependency.h:38
@ DEPENDENCY_NORMAL
Definition dependency.h:33
int errcode(int sqlerrcode)
Definition elog.c:875
int errdetail(const char *fmt,...) pg_attribute_printf(1
#define ERROR
Definition elog.h:40
#define elog(elevel,...)
Definition elog.h:228
#define ereport(elevel,...)
Definition elog.h:152
static ExtensionControlFile * read_extension_control_file(const char *extname)
Definition extension.c:879
Oid get_extension_oid(const char *extname, bool missing_ok)
Definition extension.c:229
char * get_extension_name(Oid ext_oid)
Definition extension.c:251
void systable_endscan(SysScanDesc sysscan)
Definition genam.c:612
HeapTuple systable_getnext(SysScanDesc sysscan)
Definition genam.c:523
SysScanDesc systable_beginscan(Relation heapRelation, Oid indexId, bool indexOK, Snapshot snapshot, int nkeys, ScanKey key)
Definition genam.c:388
HeapTuple heap_copytuple(HeapTuple tuple)
Definition heaptuple.c:686
#define HeapTupleIsValid(tuple)
Definition htup.h:78
static void * GETSTRUCT(const HeapTupleData *tuple)
void CatalogTupleUpdate(Relation heapRel, const ItemPointerData *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:3561
Oid GetUserId(void)
Definition miscinit.c:470
Oid LookupCreationNamespace(const char *nspname)
Definition namespace.c:3500
static char * errmsg
#define InvokeObjectPostAlterHook(classId, objectId, subId)
char * getObjectDescription(const ObjectAddress *object, bool missing_ok)
const ObjectAddress InvalidObjectAddress
#define ObjectAddressSet(addr, class_id, object_id)
@ OBJECT_SCHEMA
@ OBJECT_EXTENSION
#define ACL_CREATE
Definition parsenodes.h:85
long changeDependencyFor(Oid classId, Oid objectId, Oid refClassId, Oid oldRefObjectId, Oid newRefObjectId)
Definition pg_depend.c:459
Oid getExtensionOfObject(Oid classId, Oid objectId)
Definition pg_depend.c:734
END_CATALOG_STRUCT typedef FormData_pg_depend * Form_pg_depend
Definition pg_depend.h:76
END_CATALOG_STRUCT typedef FormData_pg_extension * Form_pg_extension
#define lfirst(lc)
Definition pg_list.h:172
static Datum ObjectIdGetDatum(Oid X)
Definition postgres.h:252
#define InvalidOid
unsigned int Oid
static int fb(int x)
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:206
#define BTEqualStrategyNumber
Definition stratnum.h:31
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(), DEPENDENCY_EXTENSION, DEPENDENCY_NORMAL, elog, ereport, errcode(), errdetail(), errmsg, ERROR, fb(), Form_pg_depend, Form_pg_extension, get_extension_name(), get_extension_oid(), get_namespace_name(), getExtensionOfObject(), getObjectDescription(), GETSTRUCT(), GetUserId(), heap_copytuple(), HeapTupleIsValid, InvalidObjectAddress, InvalidOid, InvokeObjectPostAlterHook, lfirst, LookupCreationNamespace(), NameStr, new_object_addresses(), object_aclcheck(), OBJECT_EXTENSION, object_ownercheck(), OBJECT_SCHEMA, ObjectAddressSet, ObjectIdGetDatum(), read_extension_control_file(), relation_close(), RowExclusiveLock, ScanKeyInit(), systable_beginscan(), systable_endscan(), systable_getnext(), 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 3618 of file extension.c.

3625{
3626 const char *oldVersionName = initialVersion;
3627 ListCell *lcv;
3628
3629 foreach(lcv, updateVersions)
3630 {
3631 char *versionName = (char *) lfirst(lcv);
3632 ExtensionControlFile *control;
3633 char *schemaName;
3634 Oid schemaOid;
3638 ScanKeyData key[1];
3643 bool nulls[Natts_pg_extension];
3644 bool repl[Natts_pg_extension];
3646 ListCell *lc;
3647
3648 /*
3649 * Fetch parameters for specific version (pcontrol is not changed)
3650 */
3652
3653 /* Find the pg_extension tuple */
3655
3656 ScanKeyInit(&key[0],
3660
3662 NULL, 1, key);
3663
3665
3666 if (!HeapTupleIsValid(extTup)) /* should not happen */
3667 elog(ERROR, "could not find tuple for extension %u",
3668 extensionOid);
3669
3671
3672 /*
3673 * Determine the target schema (set by original install)
3674 */
3675 schemaOid = extForm->extnamespace;
3677
3678 /*
3679 * Modify extrelocatable and extversion in the pg_extension tuple
3680 */
3681 memset(values, 0, sizeof(values));
3682 memset(nulls, 0, sizeof(nulls));
3683 memset(repl, 0, sizeof(repl));
3684
3686 BoolGetDatum(control->relocatable);
3687 repl[Anum_pg_extension_extrelocatable - 1] = true;
3690 repl[Anum_pg_extension_extversion - 1] = true;
3691
3693 values, nulls, repl);
3694
3696
3698
3700
3701 /*
3702 * Look up the prerequisite extensions for this version, install them
3703 * if necessary, and build lists of their OIDs and the OIDs of their
3704 * target schemas.
3705 */
3708 foreach(lc, control->requires)
3709 {
3710 char *curreq = (char *) lfirst(lc);
3711 Oid reqext;
3712 Oid reqschema;
3713
3715 control->name,
3717 cascade,
3718 NIL,
3719 is_create);
3723 }
3724
3725 /*
3726 * Remove and recreate dependencies on prerequisite extensions
3727 */
3731
3732 myself.classId = ExtensionRelationId;
3733 myself.objectId = extensionOid;
3734 myself.objectSubId = 0;
3735
3736 foreach(lc, requiredExtensions)
3737 {
3740
3742 otherext.objectId = reqext;
3743 otherext.objectSubId = 0;
3744
3746 }
3747
3749
3750 /*
3751 * Finally, execute the update script file
3752 */
3756 schemaName);
3757
3758 /*
3759 * Update prior-version name and loop around. Since
3760 * execute_sql_string did a final CommandCounterIncrement, we can
3761 * update the pg_extension row again.
3762 */
3764 }
3765}
static Datum values[MAXATTR]
Definition bootstrap.c:190
#define CStringGetTextDatum(s)
Definition builtins.h:98
Oid get_extension_schema(Oid ext_oid)
Definition extension.c:273
static Oid get_required_extension(char *reqExtensionName, char *extensionName, char *origSchemaName, bool cascade, List *parents, bool is_create)
Definition extension.c:2076
static ExtensionControlFile * read_extension_aux_control_file(const ExtensionControlFile *pcontrol, const char *version)
Definition extension.c:898
static void execute_extension_script(Oid extensionOid, ExtensionControlFile *control, const char *from_version, const char *version, List *requiredSchemas, const char *schemaName)
Definition extension.c:1246
HeapTuple heap_modify_tuple(HeapTuple tuple, TupleDesc tupleDesc, const Datum *replValues, const bool *replIsnull, const bool *doReplace)
Definition heaptuple.c:1118
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:47
long deleteDependencyRecordsForClass(Oid classId, Oid objectId, Oid refclassId, char deptype)
Definition pg_depend.c:353
#define NIL
Definition pg_list.h:68
#define lfirst_oid(lc)
Definition pg_list.h:174
static Datum BoolGetDatum(bool X)
Definition postgres.h:112
uint64_t Datum
Definition postgres.h:70
#define RelationGetDescr(relation)
Definition rel.h:542
Definition pg_list.h:54

References BoolGetDatum(), BTEqualStrategyNumber, CatalogTupleUpdate(), ObjectAddress::classId, CStringGetTextDatum, deleteDependencyRecordsForClass(), DEPENDENCY_NORMAL, elog, ERROR, execute_extension_script(), fb(), Form_pg_extension, get_extension_schema(), get_namespace_name(), get_required_extension(), GETSTRUCT(), heap_modify_tuple(), HeapTupleIsValid, InvokeObjectPostAlterHook, lappend_oid(), lfirst, lfirst_oid, ExtensionControlFile::name, NIL, ObjectIdGetDatum(), read_extension_aux_control_file(), recordDependencyOn(), RelationGetDescr, ExtensionControlFile::relocatable, RowExclusiveLock, ScanKeyInit(), systable_beginscan(), systable_endscan(), systable_getnext(), 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 401 of file extension.c.

402{
403 int namelen = strlen(extensionname);
404
405 /*
406 * Disallow empty names (the parser rejects empty identifiers anyway, but
407 * let's check).
408 */
409 if (namelen == 0)
412 errmsg("invalid extension name: \"%s\"", extensionname),
413 errdetail("Extension names must not be empty.")));
414
415 /*
416 * No double dashes, since that would make script filenames ambiguous.
417 */
418 if (strstr(extensionname, "--"))
421 errmsg("invalid extension name: \"%s\"", extensionname),
422 errdetail("Extension names must not contain \"--\".")));
423
424 /*
425 * No leading or trailing dash either. (We could probably allow this, but
426 * it would require much care in filename parsing and would make filenames
427 * visually if not formally ambiguous. Since there's no real-world use
428 * case, let's just forbid it.)
429 */
430 if (extensionname[0] == '-' || extensionname[namelen - 1] == '-')
433 errmsg("invalid extension name: \"%s\"", extensionname),
434 errdetail("Extension names must not begin or end with \"-\".")));
435
436 /*
437 * No directory separators either (this is sufficient to prevent ".."
438 * style attacks).
439 */
443 errmsg("invalid extension name: \"%s\"", extensionname),
444 errdetail("Extension names must not contain directory separator characters.")));
445}
char * first_dir_separator(const char *filename)
Definition path.c:110

References ereport, errcode(), errdetail(), errmsg, ERROR, fb(), 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 448 of file extension.c.

449{
450 int namelen = strlen(versionname);
451
452 /*
453 * Disallow empty names (we could possibly allow this, but there seems
454 * little point).
455 */
456 if (namelen == 0)
459 errmsg("invalid extension version name: \"%s\"", versionname),
460 errdetail("Version names must not be empty.")));
461
462 /*
463 * No double dashes, since that would make script filenames ambiguous.
464 */
465 if (strstr(versionname, "--"))
468 errmsg("invalid extension version name: \"%s\"", versionname),
469 errdetail("Version names must not contain \"--\".")));
470
471 /*
472 * No leading or trailing dash either.
473 */
474 if (versionname[0] == '-' || versionname[namelen - 1] == '-')
477 errmsg("invalid extension version name: \"%s\"", versionname),
478 errdetail("Version names must not begin or end with \"-\".")));
479
480 /*
481 * No directory separators either (this is sufficient to prevent ".."
482 * style attacks).
483 */
487 errmsg("invalid extension version name: \"%s\"", versionname),
488 errdetail("Version names must not contain directory separator characters.")));
489}

References ereport, errcode(), errdetail(), errmsg, ERROR, fb(), 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 2744 of file extension.c.

2745{
2746 Datum *datums;
2747 int ndatums;
2748 ArrayType *a;
2749 ListCell *lc;
2750
2751 ndatums = list_length(requires);
2752 datums = (Datum *) palloc(ndatums * sizeof(Datum));
2753 ndatums = 0;
2754 foreach(lc, requires)
2755 {
2756 char *curreq = (char *) lfirst(lc);
2757
2758 datums[ndatums++] =
2760 }
2761 a = construct_array_builtin(datums, ndatums, NAMEOID);
2762 return PointerGetDatum(a);
2763}
ArrayType * construct_array_builtin(Datum *elems, int nelems, Oid elmtype)
#define DirectFunctionCall1(func, arg1)
Definition fmgr.h:684
int a
Definition isn.c:73
void * palloc(Size size)
Definition mcxt.c:1387
Datum namein(PG_FUNCTION_ARGS)
Definition name.c:48
static int list_length(const List *l)
Definition pg_list.h:152
static Datum CStringGetDatum(const char *X)
Definition postgres.h:383
#define PointerGetDatum(X)
Definition postgres.h:354

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

Referenced by get_available_versions_for_extension().

◆ CreateExtension()

ObjectAddress CreateExtension ( ParseState pstate,
CreateExtensionStmt stmt 
)

Definition at line 2147 of file extension.c.

2148{
2152 char *schemaName = NULL;
2153 char *versionName = NULL;
2154 bool cascade = false;
2155 ListCell *lc;
2156
2157 /* Check extension name validity before any filesystem access */
2159
2160 /*
2161 * Check for duplicate extension name. The unique index on
2162 * pg_extension.extname would catch this anyway, and serves as a backstop
2163 * in case of race conditions; but this is a friendlier error message, and
2164 * besides we need a check to support IF NOT EXISTS.
2165 */
2166 if (get_extension_oid(stmt->extname, true) != InvalidOid)
2167 {
2168 if (stmt->if_not_exists)
2169 {
2172 errmsg("extension \"%s\" already exists, skipping",
2173 stmt->extname)));
2174 return InvalidObjectAddress;
2175 }
2176 else
2177 ereport(ERROR,
2179 errmsg("extension \"%s\" already exists",
2180 stmt->extname)));
2181 }
2182
2183 /*
2184 * We use global variables to track the extension being created, so we can
2185 * create only one extension at the same time.
2186 */
2188 ereport(ERROR,
2190 errmsg("nested CREATE EXTENSION is not supported")));
2191
2192 /* Deconstruct the statement option list */
2193 foreach(lc, stmt->options)
2194 {
2195 DefElem *defel = (DefElem *) lfirst(lc);
2196
2197 if (strcmp(defel->defname, "schema") == 0)
2198 {
2199 if (d_schema)
2201 d_schema = defel;
2203 }
2204 else if (strcmp(defel->defname, "new_version") == 0)
2205 {
2206 if (d_new_version)
2210 }
2211 else if (strcmp(defel->defname, "cascade") == 0)
2212 {
2213 if (d_cascade)
2215 d_cascade = defel;
2216 cascade = defGetBoolean(d_cascade);
2217 }
2218 else
2219 elog(ERROR, "unrecognized option: %s", defel->defname);
2220 }
2221
2222 /* Call CreateExtensionInternal to do the real work. */
2223 return CreateExtensionInternal(stmt->extname,
2224 schemaName,
2226 cascade,
2227 NIL,
2228 true);
2229}
char * defGetString(DefElem *def)
Definition define.c:34
bool defGetBoolean(DefElem *def)
Definition define.c:93
void errorConflictingDefElem(DefElem *defel, ParseState *pstate)
Definition define.c:370
#define NOTICE
Definition elog.h:36
static void check_valid_extension_name(const char *extensionname)
Definition extension.c:401
bool creating_extension
Definition extension.c:80
static ObjectAddress CreateExtensionInternal(char *extensionName, char *schemaName, const char *versionName, bool cascade, List *parents, bool is_create)
Definition extension.c:1834
#define stmt
#define ERRCODE_DUPLICATE_OBJECT
Definition streamutil.c:30

References check_valid_extension_name(), CreateExtensionInternal(), creating_extension, defGetBoolean(), defGetString(), elog, ereport, errcode(), ERRCODE_DUPLICATE_OBJECT, errmsg, ERROR, errorConflictingDefElem(), fb(), 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 1834 of file extension.c.

1840{
1841 char *origSchemaName = schemaName;
1845 ExtensionControlFile *control;
1846 char *filename;
1847 struct stat fst;
1852 ObjectAddress address;
1853 ListCell *lc;
1854
1855 /*
1856 * Read the primary control file. Note we assume that it does not contain
1857 * any non-ASCII data, so there is no need to worry about encoding at this
1858 * point.
1859 */
1861
1862 /*
1863 * Determine the version to install
1864 */
1865 if (versionName == NULL)
1866 {
1867 if (pcontrol->default_version)
1868 versionName = pcontrol->default_version;
1869 else
1870 ereport(ERROR,
1872 errmsg("version to install must be specified")));
1873 }
1875
1876 /*
1877 * Figure out which script(s) we need to run to install the desired
1878 * version of the extension. If we do not have a script that directly
1879 * does what is needed, we try to find a sequence of update scripts that
1880 * will get us there.
1881 */
1883 if (stat(filename, &fst) == 0)
1884 {
1885 /* Easy, no extra scripts */
1887 }
1888 else
1889 {
1890 /* Look for best way to install this version */
1891 List *evi_list;
1894
1895 /* Extract the version update graph from the script directory */
1897
1898 /* Identify the target version */
1900
1901 /* Identify best path to reach target */
1904
1905 /* Fail if no path ... */
1906 if (evi_start == NULL)
1907 ereport(ERROR,
1909 errmsg("extension \"%s\" has no installation script nor update path for version \"%s\"",
1910 pcontrol->name, versionName)));
1911
1912 /* Otherwise, install best starting point and then upgrade */
1913 versionName = evi_start->name;
1914 }
1915
1916 /*
1917 * Fetch control parameters for installation target version
1918 */
1920
1921 /*
1922 * Determine the target schema to install the extension into
1923 */
1924 if (schemaName)
1925 {
1926 /* If the user is giving us the schema name, it must exist already. */
1928 }
1929
1930 if (control->schema != NULL)
1931 {
1932 /*
1933 * The extension is not relocatable and the author gave us a schema
1934 * for it.
1935 *
1936 * Unless CASCADE parameter was given, it's an error to give a schema
1937 * different from control->schema if control->schema is specified.
1938 */
1939 if (schemaName && strcmp(control->schema, schemaName) != 0 &&
1940 !cascade)
1941 ereport(ERROR,
1943 errmsg("extension \"%s\" must be installed in schema \"%s\"",
1944 control->name,
1945 control->schema)));
1946
1947 /* Always use the schema from control file for current extension. */
1948 schemaName = control->schema;
1949
1950 /* Find or create the schema in case it does not exist. */
1952
1953 if (!OidIsValid(schemaOid))
1954 {
1955 ParseState *pstate = make_parsestate(NULL);
1957
1958 pstate->p_sourcetext = "(generated CREATE SCHEMA command)";
1959
1960 csstmt->schemaname = schemaName;
1961 csstmt->authrole = NULL; /* will be created by current user */
1962 csstmt->schemaElts = NIL;
1963 csstmt->if_not_exists = false;
1964
1965 CreateSchemaCommand(pstate, csstmt, -1, -1);
1966
1967 /*
1968 * CreateSchemaCommand includes CommandCounterIncrement, so new
1969 * schema is now visible.
1970 */
1972 }
1973 }
1974 else if (!OidIsValid(schemaOid))
1975 {
1976 /*
1977 * Neither user nor author of the extension specified schema; use the
1978 * current default creation namespace, which is the first explicit
1979 * entry in the search_path.
1980 */
1981 List *search_path = fetch_search_path(false);
1982
1983 if (search_path == NIL) /* nothing valid in search_path? */
1984 ereport(ERROR,
1986 errmsg("no schema has been selected to create in")));
1987 schemaOid = linitial_oid(search_path);
1989 if (schemaName == NULL) /* recently-deleted namespace? */
1990 ereport(ERROR,
1992 errmsg("no schema has been selected to create in")));
1993
1994 list_free(search_path);
1995 }
1996
1997 /*
1998 * Make note if a temporary namespace has been accessed in this
1999 * transaction.
2000 */
2003
2004 /*
2005 * We don't check creation rights on the target namespace here. If the
2006 * extension script actually creates any objects there, it will fail if
2007 * the user doesn't have such permissions. But there are cases such as
2008 * procedural languages where it's convenient to set schema = pg_catalog
2009 * yet we don't want to restrict the command to users with ACL_CREATE for
2010 * pg_catalog.
2011 */
2012
2013 /*
2014 * Look up the prerequisite extensions, install them if necessary, and
2015 * build lists of their OIDs and the OIDs of their target schemas.
2016 */
2019 foreach(lc, control->requires)
2020 {
2021 char *curreq = (char *) lfirst(lc);
2022 Oid reqext;
2023 Oid reqschema;
2024
2028 cascade,
2029 parents,
2030 is_create);
2034 }
2035
2036 /*
2037 * Insert new tuple into pg_extension, and create dependency entries.
2038 */
2039 address = InsertExtensionTuple(control->name, extowner,
2040 schemaOid, control->relocatable,
2045 extensionOid = address.objectId;
2046
2047 /*
2048 * Apply any control-file comment on extension
2049 */
2050 if (control->comment != NULL)
2052
2053 /*
2054 * Execute the installation script file
2055 */
2059 schemaName);
2060
2061 /*
2062 * If additional update scripts have to be executed, apply the updates as
2063 * though a series of ALTER EXTENSION UPDATE commands were given
2064 */
2067 origSchemaName, cascade, is_create);
2068
2069 return address;
2070}
#define OidIsValid(objectId)
Definition c.h:858
void CreateComments(Oid oid, Oid classoid, int32 subid, const char *comment)
Definition comment.c:153
ObjectAddress InsertExtensionTuple(const char *extName, Oid extOwner, Oid schemaOid, bool relocatable, const char *extVersion, Datum extConfig, Datum extCondition, List *requiredExtensions)
Definition extension.c:2245
static void check_valid_version_name(const char *versionname)
Definition extension.c:448
static ExtensionVersionInfo * find_install_path(List *evi_list, ExtensionVersionInfo *evi_target, List **best_path)
Definition extension.c:1779
static ExtensionVersionInfo * get_ext_ver_info(const char *versionname, List **evi_list)
Definition extension.c:1519
static List * get_ext_ver_list(ExtensionControlFile *control)
Definition extension.c:1580
static char * get_extension_script_filename(ExtensionControlFile *control, const char *from_version, const char *version)
Definition extension.c:656
static void ApplyExtensionUpdates(Oid extensionOid, ExtensionControlFile *pcontrol, const char *initialVersion, List *updateVersions, char *origSchemaName, bool cascade, bool is_create)
Definition extension.c:3618
void list_free(List *list)
Definition list.c:1546
bool isTempNamespace(Oid namespaceId)
Definition namespace.c:3721
List * fetch_search_path(bool includeImplicit)
Definition namespace.c:4891
Oid get_namespace_oid(const char *nspname, bool missing_ok)
Definition namespace.c:3607
#define makeNode(_type_)
Definition nodes.h:161
ParseState * make_parsestate(ParseState *parentParseState)
Definition parse_node.c:39
static char * filename
Definition pg_dumpall.c:133
#define linitial_oid(l)
Definition pg_list.h:180
Oid CreateSchemaCommand(ParseState *pstate, CreateSchemaStmt *stmt, int stmt_location, int stmt_len)
Definition schemacmds.c:52
const char * p_sourcetext
Definition parse_node.h:214
#define stat
Definition win32_port.h:74
int MyXactFlags
Definition xact.c:138
#define XACT_FLAGS_ACCESSEDTEMPNAMESPACE
Definition xact.h:103

References ApplyExtensionUpdates(), check_valid_version_name(), ExtensionControlFile::comment, CreateComments(), CreateSchemaCommand(), ereport, errcode(), errmsg, ERROR, execute_extension_script(), fb(), 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(), InsertExtensionTuple(), InvalidOid, isTempNamespace(), lappend_oid(), lfirst, linitial_oid, list_free(), make_parsestate(), makeNode, MyXactFlags, ExtensionControlFile::name, NIL, ObjectAddress::objectId, OidIsValid, ParseState::p_sourcetext, PointerGetDatum, read_extension_aux_control_file(), read_extension_control_file(), ExtensionControlFile::relocatable, ExtensionControlFile::schema, 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 3862 of file extension.c.

3865{
3867
3868 /*
3869 * Check existing extension membership.
3870 */
3871 oldExtension = getExtensionOfObject(object.classId, object.objectId);
3872
3873 if (stmt->action > 0)
3874 {
3875 /*
3876 * ADD, so complain if object is already attached to some extension.
3877 */
3879 ereport(ERROR,
3881 errmsg("%s is already a member of extension \"%s\"",
3882 getObjectDescription(&object, false),
3884
3885 /*
3886 * Prevent a schema from being added to an extension if the schema
3887 * contains the extension. That would create a dependency loop.
3888 */
3889 if (object.classId == NamespaceRelationId &&
3890 object.objectId == get_extension_schema(extension.objectId))
3891 ereport(ERROR,
3893 errmsg("cannot add schema \"%s\" to extension \"%s\" "
3894 "because the schema contains the extension",
3895 get_namespace_name(object.objectId),
3896 stmt->extname)));
3897
3898 /*
3899 * OK, add the dependency.
3900 */
3902
3903 /*
3904 * Also record the initial ACL on the object, if any.
3905 *
3906 * Note that this will handle the object's ACLs, as well as any ACLs
3907 * on object subIds. (In other words, when the object is a table,
3908 * this will record the table's ACL and the ACLs for the columns on
3909 * the table, if any).
3910 */
3911 recordExtObjInitPriv(object.objectId, object.classId);
3912 }
3913 else
3914 {
3915 /*
3916 * DROP, so complain if it's not a member.
3917 */
3918 if (oldExtension != extension.objectId)
3919 ereport(ERROR,
3921 errmsg("%s is not a member of extension \"%s\"",
3922 getObjectDescription(&object, false),
3923 stmt->extname)));
3924
3925 /*
3926 * OK, drop the dependency.
3927 */
3928 if (deleteDependencyRecordsForClass(object.classId, object.objectId,
3931 elog(ERROR, "unexpected number of extension dependency records");
3932
3933 /*
3934 * If it's a relation, it might have an entry in the extension's
3935 * extconfig array, which we must remove.
3936 */
3937 if (object.classId == RelationRelationId)
3938 extension_config_remove(extension.objectId, object.objectId);
3939
3940 /*
3941 * Remove all the initial ACLs, if any.
3942 *
3943 * Note that this will remove the object's ACLs, as well as any ACLs
3944 * on object subIds. (In other words, when the object is a table,
3945 * this will remove the table's ACL and the ACLs for the columns on
3946 * the table, if any).
3947 */
3948 removeExtObjInitPriv(object.objectId, object.classId);
3949 }
3950
3951 /*
3952 * Recurse to any dependent objects; currently, this includes the array
3953 * type of a base type, the multirange type associated with a range type,
3954 * and the rowtype of a table.
3955 */
3956 if (object.classId == TypeRelationId)
3957 {
3959
3961 depobject.objectSubId = 0;
3962
3963 /* If it has an array type, update that too */
3964 depobject.objectId = get_array_type(object.objectId);
3965 if (OidIsValid(depobject.objectId))
3967
3968 /* If it is a range type, update the associated multirange too */
3969 if (type_is_range(object.objectId))
3970 {
3971 depobject.objectId = get_range_multirange(object.objectId);
3972 if (!OidIsValid(depobject.objectId))
3973 ereport(ERROR,
3975 errmsg("could not find multirange type for data type %s",
3976 format_type_be(object.objectId))));
3978 }
3979 }
3980 if (object.classId == RelationRelationId)
3981 {
3983
3985 depobject.objectSubId = 0;
3986
3987 /* It might not have a rowtype, but if it does, update that */
3988 depobject.objectId = get_rel_type_id(object.objectId);
3989 if (OidIsValid(depobject.objectId))
3991 }
3992}
void recordExtObjInitPriv(Oid objoid, Oid classoid)
Definition aclchk.c:4397
void removeExtObjInitPriv(Oid objoid, Oid classoid)
Definition aclchk.c:4561
static void extension_config_remove(Oid extensionoid, Oid tableoid)
Definition extension.c:3091
static void ExecAlterExtensionContentsRecurse(AlterExtensionContentsStmt *stmt, ObjectAddress extension, ObjectAddress object)
Definition extension.c:3862
char * format_type_be(Oid type_oid)
bool type_is_range(Oid typid)
Definition lsyscache.c:2883
Oid get_rel_type_id(Oid relid)
Definition lsyscache.c:2172
Oid get_range_multirange(Oid rangeOid)
Definition lsyscache.c:3678
Oid get_array_type(Oid typid)
Definition lsyscache.c:2982

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

Referenced by ExecAlterExtensionContentsRecurse(), and ExecAlterExtensionContentsStmt().

◆ ExecAlterExtensionContentsStmt()

ObjectAddress ExecAlterExtensionContentsStmt ( AlterExtensionContentsStmt stmt,
ObjectAddress objAddr 
)

Definition at line 3776 of file extension.c.

3778{
3780 ObjectAddress object;
3781 Relation relation;
3782
3783 switch (stmt->objtype)
3784 {
3785 case OBJECT_DATABASE:
3786 case OBJECT_EXTENSION:
3787 case OBJECT_INDEX:
3788 case OBJECT_PUBLICATION:
3789 case OBJECT_ROLE:
3792 case OBJECT_TABLESPACE:
3793 ereport(ERROR,
3795 errmsg("cannot add an object of this type to an extension")));
3796 break;
3797 default:
3798 /* OK */
3799 break;
3800 }
3801
3802 /*
3803 * Find the extension and acquire a lock on it, to ensure it doesn't get
3804 * dropped concurrently. A sharable lock seems sufficient: there's no
3805 * reason not to allow other sorts of manipulations, such as add/drop of
3806 * other objects, to occur concurrently. Concurrently adding/dropping the
3807 * *same* object would be bad, but we prevent that by using a non-sharable
3808 * lock on the individual object, below.
3809 */
3811 (Node *) makeString(stmt->extname),
3812 &relation, AccessShareLock, false);
3813
3814 /* Permission check: must own extension */
3817 stmt->extname);
3818
3819 /*
3820 * Translate the parser representation that identifies the object into an
3821 * ObjectAddress. get_object_address() will throw an error if the object
3822 * does not exist, and will also acquire a lock on the object to guard
3823 * against concurrent DROP and ALTER EXTENSION ADD/DROP operations.
3824 */
3825 object = get_object_address(stmt->objtype, stmt->object,
3826 &relation, ShareUpdateExclusiveLock, false);
3827
3828 Assert(object.objectSubId == 0);
3829 if (objAddr)
3830 *objAddr = object;
3831
3832 /* Permission check: must own target object, too */
3833 check_object_ownership(GetUserId(), stmt->objtype, object,
3834 stmt->object, relation);
3835
3836 /* Do the update, recursing to any dependent objects */
3838
3839 /* Finish up */
3841
3842 /*
3843 * If get_object_address() opened the relation for us, we close it to keep
3844 * the reference count correct - but we retain any locks acquired by
3845 * get_object_address() until commit time, to guard against concurrent
3846 * activity.
3847 */
3848 if (relation != NULL)
3849 relation_close(relation, NoLock);
3850
3851 return extension;
3852}
#define Assert(condition)
Definition c.h:943
#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
@ OBJECT_ROLE
@ OBJECT_INDEX
@ OBJECT_DATABASE
@ OBJECT_PUBLICATION
@ OBJECT_SUBSCRIPTION
@ OBJECT_STATISTIC_EXT
Definition nodes.h:135
String * makeString(char *str)
Definition value.c:63

References AccessShareLock, aclcheck_error(), ACLCHECK_NOT_OWNER, Assert, check_object_ownership(), ereport, errcode(), errmsg, ERROR, ExecAlterExtensionContentsRecurse(), fb(), 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, relation_close(), ShareUpdateExclusiveLock, and stmt.

Referenced by ProcessUtilitySlow().

◆ ExecAlterExtensionStmt()

ObjectAddress ExecAlterExtensionStmt ( ParseState pstate,
AlterExtensionStmt stmt 
)

Definition at line 3471 of file extension.c.

3472{
3474 char *versionName;
3475 char *oldVersionName;
3476 ExtensionControlFile *control;
3479 ScanKeyData key[1];
3483 Datum datum;
3484 bool isnull;
3485 ListCell *lc;
3486 ObjectAddress address;
3487
3488 /*
3489 * We use global variables to track the extension being created, so we can
3490 * create/update only one extension at the same time.
3491 */
3493 ereport(ERROR,
3495 errmsg("nested ALTER EXTENSION is not supported")));
3496
3497 /*
3498 * Look up the extension --- it must already exist in pg_extension
3499 */
3501
3502 ScanKeyInit(&key[0],
3505 CStringGetDatum(stmt->extname));
3506
3508 NULL, 1, key);
3509
3511
3513 ereport(ERROR,
3515 errmsg("extension \"%s\" does not exist",
3516 stmt->extname)));
3517
3519
3520 /*
3521 * Determine the existing version we are updating from
3522 */
3524 RelationGetDescr(extRel), &isnull);
3525 if (isnull)
3526 elog(ERROR, "extversion is null");
3528
3530
3532
3533 /* Permission check: must own extension */
3536 stmt->extname);
3537
3538 /*
3539 * Read the primary control file. Note we assume that it does not contain
3540 * any non-ASCII data, so there is no need to worry about encoding at this
3541 * point.
3542 */
3543 control = read_extension_control_file(stmt->extname);
3544
3545 /*
3546 * Read the statement option list
3547 */
3548 foreach(lc, stmt->options)
3549 {
3550 DefElem *defel = (DefElem *) lfirst(lc);
3551
3552 if (strcmp(defel->defname, "new_version") == 0)
3553 {
3554 if (d_new_version)
3557 }
3558 else
3559 elog(ERROR, "unrecognized option: %s", defel->defname);
3560 }
3561
3562 /*
3563 * Determine the version to update to
3564 */
3565 if (d_new_version && d_new_version->arg)
3567 else if (control->default_version)
3568 versionName = control->default_version;
3569 else
3570 {
3571 ereport(ERROR,
3573 errmsg("version to install must be specified")));
3574 versionName = NULL; /* keep compiler quiet */
3575 }
3577
3578 /*
3579 * If we're already at that version, just say so
3580 */
3582 {
3584 (errmsg("version \"%s\" of extension \"%s\" is already installed",
3585 versionName, stmt->extname)));
3586 return InvalidObjectAddress;
3587 }
3588
3589 /*
3590 * Identify the series of update script files we need to execute
3591 */
3594 versionName);
3595
3596 /*
3597 * Update the pg_extension row and execute the update scripts, one at a
3598 * time
3599 */
3602 NULL, false, false);
3603
3605
3606 return address;
3607}
static List * identify_update_path(ExtensionControlFile *control, const char *oldVersion, const char *newVersion)
Definition extension.c:1643
#define DatumGetTextPP(X)
Definition fmgr.h:293
static Datum heap_getattr(HeapTuple tup, int attnum, TupleDesc tupleDesc, bool *isnull)
#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(), BTEqualStrategyNumber, check_valid_version_name(), creating_extension, CStringGetDatum(), DatumGetTextPP, ExtensionControlFile::default_version, elog, ereport, errcode(), errmsg, ERROR, errorConflictingDefElem(), fb(), Form_pg_extension, GETSTRUCT(), GetUserId(), heap_getattr(), HeapTupleIsValid, identify_update_path(), InvalidObjectAddress, 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 
)
static

Definition at line 1246 of file extension.c.

1251{
1252 bool switch_to_superuser = false;
1253 char *filename;
1254 Oid save_userid = 0;
1255 int save_sec_context = 0;
1256 int save_nestlevel;
1258 ListCell *lc;
1259 ListCell *lc2;
1260
1261 /*
1262 * Enforce superuser-ness if appropriate. We postpone these checks until
1263 * here so that the control flags are correctly associated with the right
1264 * script(s) if they happen to be set in secondary control files.
1265 */
1266 if (control->superuser && !superuser())
1267 {
1268 if (extension_is_trusted(control))
1269 switch_to_superuser = true;
1270 else if (from_version == NULL)
1271 ereport(ERROR,
1273 errmsg("permission denied to create extension \"%s\"",
1274 control->name),
1275 control->trusted
1276 ? errhint("Must have CREATE privilege on current database to create this extension.")
1277 : errhint("Must be superuser to create this extension.")));
1278 else
1279 ereport(ERROR,
1281 errmsg("permission denied to update extension \"%s\"",
1282 control->name),
1283 control->trusted
1284 ? errhint("Must have CREATE privilege on current database to update this extension.")
1285 : errhint("Must be superuser to update this extension.")));
1286 }
1287
1289
1290 if (from_version == NULL)
1291 elog(DEBUG1, "executing extension script for \"%s\" version '%s'", control->name, version);
1292 else
1293 elog(DEBUG1, "executing extension script for \"%s\" update from version '%s' to '%s'", control->name, from_version, version);
1294
1295 /*
1296 * If installing a trusted extension on behalf of a non-superuser, become
1297 * the bootstrap superuser. (This switch will be cleaned up automatically
1298 * if the transaction aborts, as will the GUC changes below.)
1299 */
1301 {
1302 GetUserIdAndSecContext(&save_userid, &save_sec_context);
1304 save_sec_context | SECURITY_LOCAL_USERID_CHANGE);
1305 }
1306
1307 /*
1308 * Force client_min_messages and log_min_messages to be at least WARNING,
1309 * so that we won't spam the user with useless NOTICE messages from common
1310 * script actions like creating shell types.
1311 *
1312 * We use the equivalent of a function SET option to allow the setting to
1313 * persist for exactly the duration of the script execution. guc.c also
1314 * takes care of undoing the setting on error.
1315 *
1316 * log_min_messages can't be set by ordinary users, so for that one we
1317 * pretend to be superuser.
1318 */
1319 save_nestlevel = NewGUCNestLevel();
1320
1322 (void) set_config_option("client_min_messages", "warning",
1324 GUC_ACTION_SAVE, true, 0, false);
1326 (void) set_config_option_ext("log_min_messages", "warning",
1329 GUC_ACTION_SAVE, true, 0, false);
1330
1331 /*
1332 * Similarly disable check_function_bodies, to ensure that SQL functions
1333 * won't be parsed during creation.
1334 */
1336 (void) set_config_option("check_function_bodies", "off",
1338 GUC_ACTION_SAVE, true, 0, false);
1339
1340 /*
1341 * Set up the search path to have the target schema first, making it be
1342 * the default creation target namespace. Then add the schemas of any
1343 * prerequisite extensions, unless they are in pg_catalog which would be
1344 * searched anyway. (Listing pg_catalog explicitly in a non-first
1345 * position would be bad for security.) Finally add pg_temp to ensure
1346 * that temp objects can't take precedence over others.
1347 */
1350 foreach(lc, requiredSchemas)
1351 {
1354
1355 if (reqname && strcmp(reqname, "pg_catalog") != 0)
1357 }
1358 appendStringInfoString(&pathbuf, ", pg_temp");
1359
1360 (void) set_config_option("search_path", pathbuf.data,
1362 GUC_ACTION_SAVE, true, 0, false);
1363
1364 /*
1365 * Set creating_extension and related variables so that
1366 * recordDependencyOnCurrentExtension and other functions do the right
1367 * things. On failure, ensure we reset these variables.
1368 */
1369 creating_extension = true;
1371 PG_TRY();
1372 {
1373 char *c_sql = read_extension_script_file(control, filename);
1374 Datum t_sql;
1375
1376 /*
1377 * We filter each substitution through quote_identifier(). When the
1378 * arg contains one of the following characters, no one collection of
1379 * quoting can work inside $$dollar-quoted string literals$$,
1380 * 'single-quoted string literals', and outside of any literal. To
1381 * avoid a security snare for extension authors, error on substitution
1382 * for arguments containing these.
1383 */
1384 const char *quoting_relevant_chars = "\"$'\\";
1385
1386 /* We use various functions that want to operate on text datums */
1388
1389 /*
1390 * Reduce any lines beginning with "\echo" to empty. This allows
1391 * scripts to contain messages telling people not to run them via
1392 * psql, which has been found to be necessary due to old habits.
1393 */
1396 t_sql,
1397 CStringGetTextDatum("^\\\\echo.*$"),
1399 CStringGetTextDatum("ng"));
1400
1401 /*
1402 * If the script uses @extowner@, substitute the calling username.
1403 */
1404 if (strstr(c_sql, "@extowner@"))
1405 {
1406 Oid uid = switch_to_superuser ? save_userid : GetUserId();
1407 const char *userName = GetUserNameFromId(uid, false);
1408 const char *qUserName = quote_identifier(userName);
1409
1412 t_sql,
1413 CStringGetTextDatum("@extowner@"),
1416 ereport(ERROR,
1418 errmsg("invalid character in extension owner: must not contain any of \"%s\"",
1420 }
1421
1422 /*
1423 * If it's not relocatable, substitute the target schema name for
1424 * occurrences of @extschema@.
1425 *
1426 * For a relocatable extension, we needn't do this. There cannot be
1427 * any need for @extschema@, else it wouldn't be relocatable.
1428 */
1429 if (!control->relocatable)
1430 {
1431 Datum old = t_sql;
1433
1436 t_sql,
1437 CStringGetTextDatum("@extschema@"),
1440 ereport(ERROR,
1442 errmsg("invalid character in extension \"%s\" schema: must not contain any of \"%s\"",
1443 control->name, quoting_relevant_chars)));
1444 }
1445
1446 /*
1447 * Likewise, substitute required extensions' schema names for
1448 * occurrences of @extschema:extension_name@.
1449 */
1450 Assert(list_length(control->requires) == list_length(requiredSchemas));
1451 forboth(lc, control->requires, lc2, requiredSchemas)
1452 {
1453 Datum old = t_sql;
1454 char *reqextname = (char *) lfirst(lc);
1458 char *repltoken;
1459
1460 repltoken = psprintf("@extschema:%s@", reqextname);
1463 t_sql,
1467 ereport(ERROR,
1469 errmsg("invalid character in extension \"%s\" schema: must not contain any of \"%s\"",
1471 }
1472
1473 /*
1474 * If module_pathname was set in the control file, substitute its
1475 * value for occurrences of MODULE_PATHNAME.
1476 */
1477 if (control->module_pathname)
1478 {
1481 t_sql,
1482 CStringGetTextDatum("MODULE_PATHNAME"),
1484 }
1485
1486 /* And now back to C string */
1488
1490 }
1491 PG_FINALLY();
1492 {
1493 creating_extension = false;
1495 }
1496 PG_END_TRY();
1497
1498 /*
1499 * Restore the GUC variables we set above.
1500 */
1501 AtEOXact_GUC(true, save_nestlevel);
1502
1503 /*
1504 * Restore authentication state if needed.
1505 */
1507 SetUserIdAndSecContext(save_userid, save_sec_context);
1508}
int errhint(const char *fmt,...) pg_attribute_printf(1
#define PG_TRY(...)
Definition elog.h:374
#define WARNING
Definition elog.h:37
#define PG_END_TRY(...)
Definition elog.h:399
#define DEBUG1
Definition elog.h:31
#define PG_FINALLY(...)
Definition elog.h:391
static void execute_sql_string(const char *sql, const char *filename)
Definition extension.c:1096
Oid CurrentExtensionObject
Definition extension.c:81
static char * read_extension_script_file(const ExtensionControlFile *control, const char *filename)
Definition extension.c:921
static bool extension_is_trusted(ExtensionControlFile *control)
Definition extension.c:1224
Datum DirectFunctionCall4Coll(PGFunction func, Oid collation, Datum arg1, Datum arg2, Datum arg3, Datum arg4)
Definition fmgr.c:861
Datum DirectFunctionCall3Coll(PGFunction func, Oid collation, Datum arg1, Datum arg2, Datum arg3)
Definition fmgr.c:836
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:3288
int NewGUCNestLevel(void)
Definition guc.c:2142
void AtEOXact_GUC(bool isCommit, int nestLevel)
Definition guc.c:2169
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:3248
@ GUC_ACTION_SAVE
Definition guc.h:205
@ PGC_S_SESSION
Definition guc.h:126
@ PGC_SUSET
Definition guc.h:78
@ PGC_USERSET
Definition guc.h:79
bool check_function_bodies
Definition guc_tables.c:557
int client_min_messages
Definition guc_tables.c:568
int log_min_messages[]
Definition guc_tables.c:681
#define SECURITY_LOCAL_USERID_CHANGE
Definition miscadmin.h:330
void GetUserIdAndSecContext(Oid *userid, int *sec_context)
Definition miscinit.c:613
BackendType MyBackendType
Definition miscinit.c:65
char * GetUserNameFromId(Oid roleid, bool noerr)
Definition miscinit.c:990
void SetUserIdAndSecContext(Oid userid, int sec_context)
Definition miscinit.c:620
#define forboth(cell1, list1, cell2, list2)
Definition pg_list.h:550
char * psprintf(const char *fmt,...)
Definition psprintf.c:43
Datum textregexreplace(PG_FUNCTION_ARGS)
Definition regexp.c:658
const char * quote_identifier(const char *ident)
void appendStringInfo(StringInfo str, const char *fmt,...)
Definition stringinfo.c:145
void appendStringInfoString(StringInfo str, const char *s)
Definition stringinfo.c:230
void initStringInfo(StringInfo str)
Definition stringinfo.c:97
bool superuser(void)
Definition superuser.c:47
Datum replace_text(PG_FUNCTION_ARGS)
Definition varlena.c:3134

References appendStringInfo(), appendStringInfoString(), Assert, AtEOXact_GUC(), check_function_bodies, client_min_messages, creating_extension, CStringGetTextDatum, CurrentExtensionObject, DatumGetTextPP, DEBUG1, DirectFunctionCall3Coll(), DirectFunctionCall4Coll(), elog, ereport, errcode(), errhint(), errmsg, ERROR, execute_sql_string(), extension_is_trusted(), fb(), 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, MyBackendType, 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(), 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 1096 of file extension.c.

1097{
1098 script_error_callback_arg callback_arg;
1102 ListCell *lc1;
1103
1104 /*
1105 * Setup error traceback support for ereport().
1106 */
1107 callback_arg.sql = sql;
1108 callback_arg.filename = filename;
1109 callback_arg.stmt_location = -1;
1110 callback_arg.stmt_len = -1;
1111
1113 scripterrcontext.arg = &callback_arg;
1116
1117 /*
1118 * Parse the SQL string into a list of raw parse trees.
1119 */
1121
1122 /* All output from SELECTs goes to the bit bucket */
1124
1125 /*
1126 * Do parse analysis, rule rewrite, planning, and execution for each raw
1127 * parsetree. We must fully execute each query before beginning parse
1128 * analysis on the next one, since there may be interdependencies.
1129 */
1130 foreach(lc1, raw_parsetree_list)
1131 {
1132 RawStmt *parsetree = lfirst_node(RawStmt, lc1);
1134 oldcontext;
1135 List *stmt_list;
1136 ListCell *lc2;
1137
1138 /* Report location of this query for error context callback */
1139 callback_arg.stmt_location = parsetree->stmt_location;
1140 callback_arg.stmt_len = parsetree->stmt_len;
1141
1142 /*
1143 * We do the work for each parsetree in a short-lived context, to
1144 * limit the memory used when there are many commands in the string.
1145 */
1148 "execute_sql_string per-statement context",
1151
1152 /* Be sure parser can see any DDL done so far */
1154
1155 stmt_list = pg_analyze_and_rewrite_fixedparams(parsetree,
1156 sql,
1157 NULL,
1158 0,
1159 NULL);
1160 stmt_list = pg_plan_queries(stmt_list, sql, CURSOR_OPT_PARALLEL_OK, NULL);
1161
1162 foreach(lc2, stmt_list)
1163 {
1165
1167
1169
1170 if (stmt->utilityStmt == NULL)
1171 {
1173
1175 sql,
1177 dest, NULL, NULL, 0);
1178
1179 ExecutorStart(qdesc, 0);
1183
1185 }
1186 else
1187 {
1188 if (IsA(stmt->utilityStmt, TransactionStmt))
1189 ereport(ERROR,
1191 errmsg("transaction control statements are not allowed within an extension script")));
1192
1194 sql,
1195 false,
1197 NULL,
1198 NULL,
1199 dest,
1200 NULL);
1201 }
1202
1204 }
1205
1206 /* Clean up per-parsetree context. */
1207 MemoryContextSwitchTo(oldcontext);
1209 }
1210
1212
1213 /* Be sure to advance the command counter after the last script command */
1215}
DestReceiver * CreateDestReceiver(CommandDest dest)
Definition dest.c:113
@ DestNone
Definition dest.h:87
ErrorContextCallback * error_context_stack
Definition elog.c:100
void ExecutorEnd(QueryDesc *queryDesc)
Definition execMain.c:477
void ExecutorFinish(QueryDesc *queryDesc)
Definition execMain.c:417
void ExecutorStart(QueryDesc *queryDesc, int eflags)
Definition execMain.c:124
void ExecutorRun(QueryDesc *queryDesc, ScanDirection direction, uint64 count)
Definition execMain.c:308
static void script_error_callback(void *arg)
Definition extension.c:954
MemoryContext CurrentMemoryContext
Definition mcxt.c:160
void MemoryContextDelete(MemoryContext context)
Definition mcxt.c:472
#define AllocSetContextCreate
Definition memutils.h:129
#define ALLOCSET_DEFAULT_SIZES
Definition memutils.h:160
#define IsA(nodeptr, _type_)
Definition nodes.h:164
static MemoryContext MemoryContextSwitchTo(MemoryContext context)
Definition palloc.h:124
#define CURSOR_OPT_PARALLEL_OK
#define lfirst_node(type, lc)
Definition pg_list.h:176
List * pg_parse_query(const char *query_string)
Definition postgres.c:615
List * pg_plan_queries(List *querytrees, const char *query_string, int cursorOptions, ParamListInfo boundParams)
Definition postgres.c:986
List * pg_analyze_and_rewrite_fixedparams(RawStmt *parsetree, const char *query_string, const Oid *paramTypes, int numParams, QueryEnvironment *queryEnv)
Definition postgres.c:681
void FreeQueryDesc(QueryDesc *qdesc)
Definition pquery.c:107
QueryDesc * CreateQueryDesc(PlannedStmt *plannedstmt, const char *sourceText, Snapshot snapshot, Snapshot crosscheck_snapshot, DestReceiver *dest, ParamListInfo params, QueryEnvironment *queryEnv, int instrument_options)
Definition pquery.c:68
@ ForwardScanDirection
Definition sdir.h:28
Snapshot GetTransactionSnapshot(void)
Definition snapmgr.c:272
void PushActiveSnapshot(Snapshot snapshot)
Definition snapmgr.c:682
void PopActiveSnapshot(void)
Definition snapmgr.c:775
Snapshot GetActiveSnapshot(void)
Definition snapmgr.c:800
struct ErrorContextCallback * previous
Definition elog.h:299
ParseLoc stmt_location
ParseLoc stmt_len
void ProcessUtility(PlannedStmt *pstmt, const char *queryString, bool readOnlyTree, ProcessUtilityContext context, ParamListInfo params, QueryEnvironment *queryEnv, DestReceiver *dest, QueryCompletion *qc)
Definition utility.c:504
@ PROCESS_UTILITY_QUERY
Definition utility.h:23
void CommandCounterIncrement(void)
Definition xact.c:1130

References ALLOCSET_DEFAULT_SIZES, AllocSetContextCreate, CommandCounterIncrement(), CreateDestReceiver(), CreateQueryDesc(), CurrentMemoryContext, CURSOR_OPT_PARALLEL_OK, DestNone, ereport, errcode(), errmsg, ERROR, error_context_stack, ExecutorEnd(), ExecutorFinish(), ExecutorRun(), ExecutorStart(), fb(), 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().

◆ ext_sibling_callback()

static void ext_sibling_callback ( Datum  arg,
SysCacheIdentifier  cacheid,
uint32  hashvalue 
)
static

Definition at line 384 of file extension.c.

385{
387
390 {
391 if (hashvalue == 0 ||
392 cache_entry->exthash == hashvalue)
393 cache_entry->valid = false;
394 }
395}
static ExtensionSiblingCache * ext_sibling_list
Definition extension.c:163
struct ExtensionSiblingCache * next
Definition extension.c:153

References ext_sibling_list, fb(), ExtensionSiblingCache::next, and ExtensionSiblingCache::valid.

Referenced by get_function_sibling_type().

◆ extension_config_remove()

static void extension_config_remove ( Oid  extensionoid,
Oid  tableoid 
)
static

Definition at line 3091 of file extension.c.

3092{
3094 ScanKeyData key[1];
3098 int arrayLength;
3099 int arrayIndex;
3100 bool isnull;
3104 ArrayType *a;
3105
3106 /* Find the pg_extension tuple */
3108
3109 ScanKeyInit(&key[0],
3113
3115 NULL, 1, key);
3116
3118
3119 if (!HeapTupleIsValid(extTup)) /* should not happen */
3120 elog(ERROR, "could not find tuple for extension %u",
3121 extensionoid);
3122
3123 /* Search extconfig for the tableoid */
3125 RelationGetDescr(extRel), &isnull);
3126 if (isnull)
3127 {
3128 /* nothing to do */
3129 a = NULL;
3130 arrayLength = 0;
3131 arrayIndex = -1;
3132 }
3133 else
3134 {
3135 Oid *arrayData;
3136 int i;
3137
3139
3140 arrayLength = ARR_DIMS(a)[0];
3141 if (ARR_NDIM(a) != 1 ||
3142 ARR_LBOUND(a)[0] != 1 ||
3143 arrayLength < 0 ||
3144 ARR_HASNULL(a) ||
3145 ARR_ELEMTYPE(a) != OIDOID)
3146 elog(ERROR, "extconfig is not a 1-D Oid array");
3147 arrayData = (Oid *) ARR_DATA_PTR(a);
3148
3149 arrayIndex = -1; /* flag for no deletion needed */
3150
3151 for (i = 0; i < arrayLength; i++)
3152 {
3153 if (arrayData[i] == tableoid)
3154 {
3155 arrayIndex = i; /* index to remove */
3156 break;
3157 }
3158 }
3159 }
3160
3161 /* If tableoid is not in extconfig, nothing to do */
3162 if (arrayIndex < 0)
3163 {
3166 return;
3167 }
3168
3169 /* Modify or delete the extconfig value */
3170 memset(repl_val, 0, sizeof(repl_val));
3171 memset(repl_null, false, sizeof(repl_null));
3172 memset(repl_repl, false, sizeof(repl_repl));
3173
3174 if (arrayLength <= 1)
3175 {
3176 /* removing only element, just set array to null */
3178 }
3179 else
3180 {
3181 /* squeeze out the target element */
3182 Datum *dvalues;
3183 int nelems;
3184 int i;
3185
3186 /* We already checked there are no nulls */
3187 deconstruct_array_builtin(a, OIDOID, &dvalues, NULL, &nelems);
3188
3189 for (i = arrayIndex; i < arrayLength - 1; i++)
3190 dvalues[i] = dvalues[i + 1];
3191
3193
3195 }
3197
3198 /* Modify or delete the extcondition value */
3200 RelationGetDescr(extRel), &isnull);
3201 if (isnull)
3202 {
3203 elog(ERROR, "extconfig and extcondition arrays do not match");
3204 }
3205 else
3206 {
3208
3209 if (ARR_NDIM(a) != 1 ||
3210 ARR_LBOUND(a)[0] != 1 ||
3211 ARR_HASNULL(a) ||
3213 elog(ERROR, "extcondition is not a 1-D text array");
3214 if (ARR_DIMS(a)[0] != arrayLength)
3215 elog(ERROR, "extconfig and extcondition arrays do not match");
3216 }
3217
3218 if (arrayLength <= 1)
3219 {
3220 /* removing only element, just set array to null */
3222 }
3223 else
3224 {
3225 /* squeeze out the target element */
3226 Datum *dvalues;
3227 int nelems;
3228 int i;
3229
3230 /* We already checked there are no nulls */
3231 deconstruct_array_builtin(a, TEXTOID, &dvalues, NULL, &nelems);
3232
3233 for (i = arrayIndex; i < arrayLength - 1; i++)
3234 dvalues[i] = dvalues[i + 1];
3235
3237
3239 }
3241
3244
3246
3248
3250}
#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(const ArrayType *array, Oid elmtype, Datum **elemsp, bool **nullsp, int *nelemsp)
int i
Definition isn.c:77

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, fb(), heap_getattr(), heap_modify_tuple(), HeapTupleIsValid, i, ObjectIdGetDatum(), PointerGetDatum, RelationGetDescr, RowExclusiveLock, ScanKeyInit(), systable_beginscan(), systable_endscan(), systable_getnext(), table_close(), and table_open().

Referenced by ExecAlterExtensionContentsRecurse().

◆ extension_file_exists()

bool extension_file_exists ( const char extensionName)

Definition at line 2685 of file extension.c.

2686{
2687 bool result = false;
2688 List *locations;
2689 DIR *dir;
2690 struct dirent *de;
2691
2693
2695 {
2696 dir = AllocateDir(location->loc);
2697
2698 /*
2699 * If the control directory doesn't exist, we want to silently return
2700 * false. Any other error will be reported by ReadDir.
2701 */
2702 if (dir == NULL && errno == ENOENT)
2703 {
2704 /* do nothing */
2705 }
2706 else
2707 {
2708 while ((de = ReadDir(dir, location->loc)) != NULL)
2709 {
2710 char *extname;
2711
2712 if (!is_extension_control_filename(de->d_name))
2713 continue;
2714
2715 /* extract extension name from 'name.control' filename */
2716 extname = pstrdup(de->d_name);
2717 *strrchr(extname, '.') = '\0';
2718
2719 /* ignore it if it's an auxiliary control file */
2720 if (strstr(extname, "--"))
2721 continue;
2722
2723 /* done if it matches request */
2724 if (strcmp(extname, extensionName) == 0)
2725 {
2726 result = true;
2727 break;
2728 }
2729 }
2730
2731 FreeDir(dir);
2732 }
2733 if (result)
2734 break;
2735 }
2736
2737 return result;
2738}
uint32 result
static bool is_extension_control_filename(const char *filename)
Definition extension.c:495
static List * get_extension_control_directories(void)
Definition extension.c:514
int FreeDir(DIR *dir)
Definition fd.c:3009
DIR * AllocateDir(const char *dirname)
Definition fd.c:2891
struct dirent * ReadDir(DIR *dir, const char *dirname)
Definition fd.c:2957
char * pstrdup(const char *in)
Definition mcxt.c:1781
#define foreach_ptr(type, var, lst)
Definition pg_list.h:501
Definition dirent.c:26

References AllocateDir(), fb(), foreach_ptr, FreeDir(), get_extension_control_directories(), is_extension_control_filename(), pstrdup(), ReadDir(), and result.

Referenced by CreateFunction(), and ExecuteDoStmt().

◆ extension_is_trusted()

static bool extension_is_trusted ( ExtensionControlFile control)
static

Definition at line 1224 of file extension.c.

1225{
1227
1228 /* Never trust unless extension's control file says it's okay */
1229 if (!control->trusted)
1230 return false;
1231 /* Allow if user has CREATE privilege on current database */
1233 if (aclresult == ACLCHECK_OK)
1234 return true;
1235 return false;
1236}
Oid MyDatabaseId
Definition globals.c:96

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

Referenced by execute_extension_script().

◆ find_extension_control_filename()

static char * find_extension_control_filename ( ExtensionControlFile control)
static

Definition at line 593 of file extension.c.

594{
595 char *basename;
596 char *result;
597 List *paths;
598
599 Assert(control->name);
600
601 basename = psprintf("%s.control", control->name);
602
604 result = find_in_paths(basename, paths);
605
606 if (result)
607 {
608 const char *p;
609
610 p = strrchr(result, '/');
611 Assert(p);
612 control->control_dir = pnstrdup(result, p - result);
613 }
614
615 return result;
616}
char * find_in_paths(const char *basename, List *paths)
Definition extension.c:4090
char * pnstrdup(const char *in, Size len)
Definition mcxt.c:1792

References Assert, ExtensionControlFile::control_dir, fb(), find_in_paths(), get_extension_control_directories(), ExtensionControlFile::name, pnstrdup(), psprintf(), and result.

Referenced by parse_extension_control_file().

◆ find_in_paths()

char * find_in_paths ( const char basename,
List paths 
)

Definition at line 4090 of file extension.c.

4091{
4092 ListCell *cell;
4093
4094 foreach(cell, paths)
4095 {
4096 ExtensionLocation *location = lfirst(cell);
4097 char *path = location->loc;
4098 char *full;
4099
4100 Assert(path != NULL);
4101
4102 path = pstrdup(path);
4103 canonicalize_path(path);
4104
4105 /* only absolute paths */
4106 if (!is_absolute_path(path))
4107 ereport(ERROR,
4109 errmsg("component in parameter \"%s\" is not an absolute path", "extension_control_path"));
4110
4111 full = psprintf("%s/%s", path, basename);
4112
4113 if (pg_file_exists(full))
4114 return full;
4115
4116 pfree(path);
4117 pfree(full);
4118 }
4119
4120 return NULL;
4121}
bool pg_file_exists(const char *name)
Definition fd.c:504
void pfree(void *pointer)
Definition mcxt.c:1616
#define is_absolute_path(filename)
Definition port.h:104
void canonicalize_path(char *path)
Definition path.c:337

References Assert, canonicalize_path(), ereport, errcode(), errmsg, ERROR, fb(), is_absolute_path, lfirst, ExtensionLocation::loc, pfree(), pg_file_exists(), psprintf(), and pstrdup().

Referenced by find_extension_control_filename().

◆ find_install_path()

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

Definition at line 1779 of file extension.c.

1781{
1783 ListCell *lc;
1784
1785 *best_path = NIL;
1786
1787 /*
1788 * We don't expect to be called for an installable target, but if we are,
1789 * the answer is easy: just start from there, with an empty update path.
1790 */
1791 if (evi_target->installable)
1792 return evi_target;
1793
1794 /* Consider all installable versions as start points */
1795 foreach(lc, evi_list)
1796 {
1798 List *path;
1799
1800 if (!evi1->installable)
1801 continue;
1802
1803 /*
1804 * Find shortest path from evi1 to evi_target; but no need to consider
1805 * paths going through other installable versions.
1806 */
1807 path = find_update_path(evi_list, evi1, evi_target, true, true);
1808 if (path == NIL)
1809 continue;
1810
1811 /* Remember best path */
1812 if (evi_start == NULL ||
1813 list_length(path) < list_length(*best_path) ||
1814 (list_length(path) == list_length(*best_path) &&
1815 strcmp(evi_start->name, evi1->name) < 0))
1816 {
1817 evi_start = evi1;
1818 *best_path = path;
1819 }
1820 }
1821
1822 return evi_start;
1823}
static List * find_update_path(List *evi_list, ExtensionVersionInfo *evi_start, ExtensionVersionInfo *evi_target, bool reject_indirect, bool reinitialize)
Definition extension.c:1686

References fb(), find_update_path(), lfirst, list_length(), 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 1686 of file extension.c.

1691{
1692 List *result;
1694 ListCell *lc;
1695
1696 /* Caller error if start == target */
1698 /* Caller error if reject_indirect and target is installable */
1699 Assert(!(reject_indirect && evi_target->installable));
1700
1701 if (reinitialize)
1702 {
1703 foreach(lc, evi_list)
1704 {
1706 evi->distance_known = false;
1707 evi->distance = INT_MAX;
1708 evi->previous = NULL;
1709 }
1710 }
1711
1712 evi_start->distance = 0;
1713
1715 {
1716 if (evi->distance == INT_MAX)
1717 break; /* all remaining vertices are unreachable */
1718 evi->distance_known = true;
1719 if (evi == evi_target)
1720 break; /* found shortest path to target */
1721 foreach(lc, evi->reachable)
1722 {
1724 int newdist;
1725
1726 /* if reject_indirect, treat installable versions as unreachable */
1727 if (reject_indirect && evi2->installable)
1728 continue;
1729 newdist = evi->distance + 1;
1730 if (newdist < evi2->distance)
1731 {
1732 evi2->distance = newdist;
1733 evi2->previous = evi;
1734 }
1735 else if (newdist == evi2->distance &&
1736 evi2->previous != NULL &&
1737 strcmp(evi->name, evi2->previous->name) < 0)
1738 {
1739 /*
1740 * Break ties in favor of the version name that comes first
1741 * according to strcmp(). This behavior is undocumented and
1742 * users shouldn't rely on it. We do it just to ensure that
1743 * if there is a tie, the update path that is chosen does not
1744 * depend on random factors like the order in which directory
1745 * entries get visited.
1746 */
1747 evi2->previous = evi;
1748 }
1749 }
1750 }
1751
1752 /* Return NIL if target is not reachable from start */
1753 if (!evi_target->distance_known)
1754 return NIL;
1755
1756 /* Build and return list of version names representing the update path */
1757 result = NIL;
1758 for (evi = evi_target; evi != evi_start; evi = evi->previous)
1759 result = lcons(evi->name, result);
1760
1761 return result;
1762}
static ExtensionVersionInfo * get_nearest_unprocessed_vertex(List *evi_list)
Definition extension.c:1552
List * lcons(void *datum, List *list)
Definition list.c:495

References Assert, ExtensionVersionInfo::distance, fb(), get_nearest_unprocessed_vertex(), lcons(), lfirst, NIL, and result.

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,
ExtensionLocation location 
)
static

Definition at line 2566 of file extension.c.

2570{
2571 List *evi_list;
2572 ListCell *lc;
2573
2574 /* Extract the version update graph from the script directory */
2576
2577 /* For each installable version ... */
2578 foreach(lc, evi_list)
2579 {
2581 ExtensionControlFile *control;
2582 Datum values[9];
2583 bool nulls[9];
2584 ListCell *lc2;
2585
2586 if (!evi->installable)
2587 continue;
2588
2589 /*
2590 * Fetch parameters for specific version (pcontrol is not changed)
2591 */
2593
2594 memset(values, 0, sizeof(values));
2595 memset(nulls, 0, sizeof(nulls));
2596
2597 /* name */
2599 CStringGetDatum(control->name));
2600 /* version */
2601 values[1] = CStringGetTextDatum(evi->name);
2602 /* superuser */
2603 values[2] = BoolGetDatum(control->superuser);
2604 /* trusted */
2605 values[3] = BoolGetDatum(control->trusted);
2606 /* relocatable */
2607 values[4] = BoolGetDatum(control->relocatable);
2608 /* schema */
2609 if (control->schema == NULL)
2610 nulls[5] = true;
2611 else
2613 CStringGetDatum(control->schema));
2614 /* requires */
2615 if (control->requires == NIL)
2616 nulls[6] = true;
2617 else
2618 values[6] = convert_requires_to_datum(control->requires);
2619
2620 /* location */
2622
2623 /* comment */
2624 if (control->comment == NULL)
2625 nulls[8] = true;
2626 else
2627 values[8] = CStringGetTextDatum(control->comment);
2628
2629 tuplestore_putvalues(tupstore, tupdesc, values, nulls);
2630
2631 /*
2632 * Find all non-directly-installable versions that would be installed
2633 * starting from this version, and report them, inheriting the
2634 * parameters that aren't changed in updates from this version.
2635 */
2636 foreach(lc2, evi_list)
2637 {
2639 List *best_path;
2640
2641 if (evi2->installable)
2642 continue;
2644 {
2645 /*
2646 * Fetch parameters for this version (pcontrol is not changed)
2647 */
2649
2650 /* name stays the same */
2651 /* version */
2652 values[1] = CStringGetTextDatum(evi2->name);
2653 /* superuser */
2654 values[2] = BoolGetDatum(control->superuser);
2655 /* trusted */
2656 values[3] = BoolGetDatum(control->trusted);
2657 /* relocatable */
2658 values[4] = BoolGetDatum(control->relocatable);
2659 /* schema stays the same */
2660 /* requires */
2661 if (control->requires == NIL)
2662 nulls[6] = true;
2663 else
2664 {
2665 values[6] = convert_requires_to_datum(control->requires);
2666 nulls[6] = false;
2667 }
2668 /* comment and location stay the same */
2669
2670 tuplestore_putvalues(tupstore, tupdesc, values, nulls);
2671 }
2672 }
2673 }
2674}
static char * get_extension_location(ExtensionLocation *loc)
Definition extension.c:204
static Datum convert_requires_to_datum(List *requires)
Definition extension.c:2744
void tuplestore_putvalues(Tuplestorestate *state, TupleDesc tdesc, const Datum *values, const bool *isnull)
Definition tuplestore.c:785

References BoolGetDatum(), ExtensionControlFile::comment, convert_requires_to_datum(), CStringGetDatum(), CStringGetTextDatum, DirectFunctionCall1, fb(), find_install_path(), get_ext_ver_list(), get_extension_location(), lfirst, ExtensionControlFile::name, namein(), NIL, read_extension_aux_control_file(), ExtensionControlFile::relocatable, 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 1519 of file extension.c.

1520{
1522 ListCell *lc;
1523
1524 foreach(lc, *evi_list)
1525 {
1527 if (strcmp(evi->name, versionname) == 0)
1528 return evi;
1529 }
1530
1532 evi->name = pstrdup(versionname);
1533 evi->reachable = NIL;
1534 evi->installable = false;
1535 /* initialize for later application of Dijkstra's algorithm */
1536 evi->distance_known = false;
1537 evi->distance = INT_MAX;
1538 evi->previous = NULL;
1539
1541
1542 return evi;
1543}
#define palloc_object(type)
Definition fe_memutils.h:74
List * lappend(List *list, void *datum)
Definition list.c:339

References fb(), lappend(), lfirst, NIL, palloc_object, and pstrdup().

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 1580 of file extension.c.

1581{
1582 List *evi_list = NIL;
1583 int extnamelen = strlen(control->name);
1584 char *location;
1585 DIR *dir;
1586 struct dirent *de;
1587
1588 location = get_extension_script_directory(control);
1589 dir = AllocateDir(location);
1590 while ((de = ReadDir(dir, location)) != NULL)
1591 {
1592 char *vername;
1593 char *vername2;
1596
1597 /* must be a .sql file ... */
1598 if (!is_extension_script_filename(de->d_name))
1599 continue;
1600
1601 /* ... matching extension name followed by separator */
1602 if (strncmp(de->d_name, control->name, extnamelen) != 0 ||
1603 de->d_name[extnamelen] != '-' ||
1604 de->d_name[extnamelen + 1] != '-')
1605 continue;
1606
1607 /* extract version name(s) from 'extname--something.sql' filename */
1608 vername = pstrdup(de->d_name + extnamelen + 2);
1609 *strrchr(vername, '.') = '\0';
1610 vername2 = strstr(vername, "--");
1611 if (!vername2)
1612 {
1613 /* It's an install, not update, script; record its version name */
1615 evi->installable = true;
1616 continue;
1617 }
1618 *vername2 = '\0'; /* terminate first version */
1619 vername2 += 2; /* and point to second */
1620
1621 /* if there's a third --, it's bogus, ignore it */
1622 if (strstr(vername2, "--"))
1623 continue;
1624
1625 /* Create ExtensionVersionInfos and link them together */
1628 evi->reachable = lappend(evi->reachable, evi2);
1629 }
1630 FreeDir(dir);
1631
1632 return evi_list;
1633}
static bool is_extension_script_filename(const char *filename)
Definition extension.c:503
static char * get_extension_script_directory(ExtensionControlFile *control)
Definition extension.c:619

References AllocateDir(), fb(), FreeDir(), get_ext_ver_info(), get_extension_script_directory(), is_extension_script_filename(), lappend(), ExtensionControlFile::name, NIL, pstrdup(), 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 638 of file extension.c.

640{
641 char *result;
642 char *scriptdir;
643
645
646 result = (char *) palloc(MAXPGPATH);
647 snprintf(result, MAXPGPATH, "%s/%s--%s.control",
648 scriptdir, control->name, version);
649
651
652 return result;
653}
#define MAXPGPATH
#define snprintf
Definition port.h:260

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

Referenced by parse_extension_control_file().

◆ get_extension_control_directories()

static List * get_extension_control_directories ( void  )
static

Definition at line 514 of file extension.c.

515{
516 char sharepath[MAXPGPATH];
517 char *system_dir;
518 char *ecp;
519 List *paths = NIL;
520
522
523 system_dir = psprintf("%s/extension", sharepath);
524
526 {
528
529 location->macro = NULL;
530 location->loc = system_dir;
531 paths = lappend(paths, location);
532 }
533 else
534 {
535 /* Duplicate the string so we can modify it */
537
538 for (;;)
539 {
540 int len;
541 char *mangled;
544
545 /* Get the length of the next path on ecp */
546 if (piece == NULL)
547 len = strlen(ecp);
548 else
549 len = piece - ecp;
550
551 /* Copy the next path found on ecp */
552 piece = palloc(len + 1);
553 strlcpy(piece, ecp, len + 1);
554
555 /*
556 * Substitute the path macro if needed or append "extension"
557 * suffix if it is a custom extension control path.
558 */
559 if (strcmp(piece, "$system") == 0)
560 {
561 location->macro = pstrdup(piece);
563 }
564 else
565 {
566 location->macro = NULL;
567 mangled = psprintf("%s/extension", piece);
568 }
569 pfree(piece);
570
571 /* Canonicalize the path based on the OS and add to the list */
573 location->loc = mangled;
574 paths = lappend(paths, location);
575
576 /* Break if ecp is empty or move to the next path on ecp */
577 if (ecp[len] == '\0')
578 break;
579 else
580 ecp += len + 1;
581 }
582 }
583
584 return paths;
585}
char * substitute_path_macro(const char *str, const char *macro, const char *value)
Definition dfmgr.c:536
char * Extension_control_path
Definition extension.c:77
char my_exec_path[MAXPGPATH]
Definition globals.c:83
const void size_t len
void get_share_path(const char *my_exec_path, char *ret_path)
Definition path.c:902
char * first_path_var_separator(const char *pathlist)
Definition path.c:127
size_t strlcpy(char *dst, const char *src, size_t siz)
Definition strlcpy.c:45

References canonicalize_path(), Extension_control_path, fb(), first_path_var_separator(), get_share_path(), lappend(), len, ExtensionLocation::loc, ExtensionLocation::macro, MAXPGPATH, my_exec_path, NIL, palloc(), palloc_object, pfree(), psprintf(), pstrdup(), strlcpy(), and substitute_path_macro().

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

◆ get_extension_location()

static char * get_extension_location ( ExtensionLocation loc)
static

Definition at line 204 of file extension.c.

205{
206 /* We only want to show extension paths for superusers. */
207 if (superuser())
208 {
209 /* Return the macro value if present to avoid showing system paths. */
210 if (loc->macro != NULL)
211 return loc->macro;
212 else
213 return loc->loc;
214 }
215 else
216 {
217 /* Similar to pg_stat_activity for unprivileged users */
218 return "<insufficient privilege>";
219 }
220}

References fb(), ExtensionLocation::loc, ExtensionLocation::macro, and superuser().

Referenced by get_available_versions_for_extension(), and pg_available_extensions().

◆ get_extension_name()

char * get_extension_name ( Oid  ext_oid)

Definition at line 251 of file extension.c.

252{
253 char *result;
254 HeapTuple tuple;
255
257
258 if (!HeapTupleIsValid(tuple))
259 return NULL;
260
261 result = pstrdup(NameStr(((Form_pg_extension) GETSTRUCT(tuple))->extname));
262 ReleaseSysCache(tuple);
263
264 return result;
265}
void ReleaseSysCache(HeapTuple tuple)
Definition syscache.c:265
HeapTuple SearchSysCache1(SysCacheIdentifier cacheId, Datum key1)
Definition syscache.c:221

References fb(), Form_pg_extension, GETSTRUCT(), HeapTupleIsValid, NameStr, ObjectIdGetDatum(), pstrdup(), ReleaseSysCache(), result, 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 229 of file extension.c.

230{
231 Oid result;
232
234 CStringGetDatum(extname));
235
236 if (!OidIsValid(result) && !missing_ok)
239 errmsg("extension \"%s\" does not exist",
240 extname)));
241
242 return result;
243}
#define GetSysCacheOid1(cacheId, oidcol, key1)
Definition syscache.h:109

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

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)

◆ get_extension_script_directory()

static char * get_extension_script_directory ( ExtensionControlFile control)
static

Definition at line 619 of file extension.c.

620{
621 /*
622 * The directory parameter can be omitted, absolute, or relative to the
623 * installation's base directory, which can be the sharedir or a custom
624 * path that was set via extension_control_path. It depends on where the
625 * .control file was found.
626 */
627 if (!control->directory)
628 return pstrdup(control->control_dir);
629
630 if (is_absolute_path(control->directory))
631 return pstrdup(control->directory);
632
633 Assert(control->basedir != NULL);
634 return psprintf("%s/%s", control->basedir, control->directory);
635}

References Assert, ExtensionControlFile::basedir, ExtensionControlFile::control_dir, ExtensionControlFile::directory, fb(), is_absolute_path, psprintf(), and pstrdup().

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 656 of file extension.c.

658{
659 char *result;
660 char *scriptdir;
661
663
664 result = (char *) palloc(MAXPGPATH);
665 if (from_version)
666 snprintf(result, MAXPGPATH, "%s/%s--%s--%s.sql",
667 scriptdir, control->name, from_version, version);
668 else
669 snprintf(result, MAXPGPATH, "%s/%s--%s.sql",
670 scriptdir, control->name, version);
671
673
674 return result;
675}

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

Referenced by CreateExtensionInternal(), and execute_extension_script().

◆ get_function_sibling_type()

Oid get_function_sibling_type ( Oid  funcoid,
const char typname 
)

Definition at line 313 of file extension.c.

314{
316 Oid extoid;
317 Oid typeoid;
318
319 /*
320 * See if we have the answer cached. Someday there may be enough callers
321 * to justify a hash table, but for now, a simple linked list is fine.
322 */
325 {
326 if (funcoid == cache_entry->reqfuncoid &&
327 strcmp(typname, cache_entry->typname) == 0)
328 break;
329 }
330 if (cache_entry && cache_entry->valid)
331 return cache_entry->typeoid;
332
333 /*
334 * Nope, so do the expensive lookups. We do not expect failures, so we do
335 * not cache negative results.
336 */
338 if (!OidIsValid(extoid))
339 return InvalidOid;
340 typeoid = getExtensionType(extoid, typname);
341 if (!OidIsValid(typeoid))
342 return InvalidOid;
343
344 /*
345 * Build, or revalidate, cache entry.
346 */
347 if (cache_entry == NULL)
348 {
349 /* Register invalidation hook if this is first entry */
350 if (ext_sibling_list == NULL)
353 (Datum) 0);
354
355 /* Momentarily zero the space to ensure valid flag is false */
358 sizeof(ExtensionSiblingCache));
361 }
362
364 cache_entry->typname = typname;
367 cache_entry->typeoid = typeoid;
368 /* Mark it valid only once it's fully populated */
369 cache_entry->valid = true;
370
371 return typeoid;
372}
static void ext_sibling_callback(Datum arg, SysCacheIdentifier cacheid, uint32 hashvalue)
Definition extension.c:384
void CacheRegisterSyscacheCallback(SysCacheIdentifier cacheid, SyscacheCallbackFunction func, Datum arg)
Definition inval.c:1816
void * MemoryContextAllocZero(MemoryContext context, Size size)
Definition mcxt.c:1266
MemoryContext CacheMemoryContext
Definition mcxt.c:169
Oid getExtensionType(Oid extensionOid, const char *typname)
Definition pg_depend.c:832
NameData typname
Definition pg_type.h:43
#define GetSysCacheHashValue1(cacheId, key1)
Definition syscache.h:118

References CacheMemoryContext, CacheRegisterSyscacheCallback(), ext_sibling_callback(), ext_sibling_list, fb(), getExtensionOfObject(), getExtensionType(), GetSysCacheHashValue1, InvalidOid, MemoryContextAllocZero(), ExtensionSiblingCache::next, ObjectIdGetDatum(), OidIsValid, ExtensionSiblingCache::reqfuncoid, ExtensionSiblingCache::typeoid, and typname.

Referenced by _int_matchsel().

◆ get_nearest_unprocessed_vertex()

static ExtensionVersionInfo * get_nearest_unprocessed_vertex ( List evi_list)
static

Definition at line 1552 of file extension.c.

1553{
1555 ListCell *lc;
1556
1557 foreach(lc, evi_list)
1558 {
1560
1561 /* only vertices whose distance is still uncertain are candidates */
1562 if (evi2->distance_known)
1563 continue;
1564 /* remember the closest such vertex */
1565 if (evi == NULL ||
1566 evi->distance > evi2->distance)
1567 evi = evi2;
1568 }
1569
1570 return evi;
1571}

References fb(), 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 2076 of file extension.c.

2082{
2084
2087 {
2088 if (cascade)
2089 {
2090 /* Must install it. */
2091 ObjectAddress addr;
2093 ListCell *lc;
2094
2095 /* Check extension name validity before trying to cascade. */
2097
2098 /* Check for cyclic dependency between extensions. */
2099 foreach(lc, parents)
2100 {
2101 char *pname = (char *) lfirst(lc);
2102
2103 if (strcmp(pname, reqExtensionName) == 0)
2104 ereport(ERROR,
2106 errmsg("cyclic dependency detected between extensions \"%s\" and \"%s\"",
2108 }
2109
2111 (errmsg("installing required extension \"%s\"",
2113
2114 /* Add current extension to list of parents to pass down. */
2116
2117 /*
2118 * Create the required extension. We propagate the SCHEMA option
2119 * if any, and CASCADE, but no other options.
2120 */
2123 NULL,
2124 cascade,
2126 is_create);
2127
2128 /* Get its newly-assigned OID. */
2130 }
2131 else
2132 ereport(ERROR,
2134 errmsg("required extension \"%s\" is not installed",
2136 is_create ?
2137 errhint("Use CREATE EXTENSION ... CASCADE to install required extensions too.") : 0));
2138 }
2139
2140 return reqExtensionOid;
2141}
List * list_copy(const List *oldlist)
Definition list.c:1573

References check_valid_extension_name(), CreateExtensionInternal(), ereport, errcode(), errhint(), errmsg, ERROR, fb(), 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 1643 of file extension.c.

1645{
1646 List *result;
1647 List *evi_list;
1650
1651 /* Extract the version update graph from the script directory */
1652 evi_list = get_ext_ver_list(control);
1653
1654 /* Initialize start and end vertices */
1657
1658 /* Find shortest path */
1660
1661 if (result == NIL)
1662 ereport(ERROR,
1664 errmsg("extension \"%s\" has no update path from version \"%s\" to version \"%s\"",
1665 control->name, oldVersion, newVersion)));
1666
1667 return result;
1668}

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

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 2245 of file extension.c.

2249{
2251 Relation rel;
2253 bool nulls[Natts_pg_extension];
2254 HeapTuple tuple;
2258 ListCell *lc;
2259
2260 /*
2261 * Build and insert the pg_extension tuple
2262 */
2264
2265 memset(values, 0, sizeof(values));
2266 memset(nulls, 0, sizeof(nulls));
2267
2277
2279 nulls[Anum_pg_extension_extconfig - 1] = true;
2280 else
2282
2284 nulls[Anum_pg_extension_extcondition - 1] = true;
2285 else
2287
2288 tuple = heap_form_tuple(rel->rd_att, values, nulls);
2289
2290 CatalogTupleInsert(rel, tuple);
2291
2292 heap_freetuple(tuple);
2294
2295 /*
2296 * Record dependencies on owner, schema, and prerequisite extensions
2297 */
2299
2301
2303
2306
2307 foreach(lc, requiredExtensions)
2308 {
2311
2314 }
2315
2316 /* Record all of them (this includes duplicate elimination) */
2319
2320 /* Post creation hook for new extension */
2322
2323 return myself;
2324}
Oid GetNewOidWithIndex(Relation relation, Oid indexId, AttrNumber oidcolumn)
Definition catalog.c:448
void record_object_address_dependencies(const ObjectAddress *depender, ObjectAddresses *referenced, DependencyType behavior)
void add_exact_object_address(const ObjectAddress *object, ObjectAddresses *addrs)
void free_object_addresses(ObjectAddresses *addrs)
HeapTuple heap_form_tuple(TupleDesc tupleDescriptor, const Datum *values, const bool *isnull)
Definition heaptuple.c:1025
void heap_freetuple(HeapTuple htup)
Definition heaptuple.c:1372
void CatalogTupleInsert(Relation heapRel, HeapTuple tup)
Definition indexing.c:233
#define InvokeObjectPostCreateHook(classId, objectId, subId)
void recordDependencyOnOwner(Oid classId, Oid objectId, Oid owner)
TupleDesc rd_att
Definition rel.h:112

References add_exact_object_address(), BoolGetDatum(), CatalogTupleInsert(), CStringGetDatum(), CStringGetTextDatum, DEPENDENCY_NORMAL, DirectFunctionCall1, fb(), 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 495 of file extension.c.

496{
497 const char *extension = strrchr(filename, '.');
498
499 return (extension != NULL) && (strcmp(extension, ".control") == 0);
500}

References fb(), and 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 503 of file extension.c.

504{
505 const char *extension = strrchr(filename, '.');
506
507 return (extension != NULL) && (strcmp(extension, ".sql") == 0);
508}

References fb(), and filename.

Referenced by get_ext_ver_list().

◆ new_ExtensionControlFile()

static ExtensionControlFile * new_ExtensionControlFile ( const char extname)
static

Definition at line 4067 of file extension.c.

4068{
4069 /*
4070 * Set up default values. Pointer fields are initially null.
4071 */
4073
4074 control->name = pstrdup(extname);
4075 control->relocatable = false;
4076 control->superuser = true;
4077 control->trusted = false;
4078 control->encoding = -1;
4079
4080 return control;
4081}
#define palloc0_object(type)
Definition fe_memutils.h:75

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

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

◆ parse_extension_control_file()

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

Definition at line 691 of file extension.c.

693{
694 char *filename;
695 FILE *file;
696 ConfigVariable *item,
697 *head = NULL,
698 *tail = NULL;
699
700 /*
701 * Locate the file to read. Auxiliary files are optional.
702 */
703 if (version)
705 else
706 {
707 /*
708 * If control_dir is already set, use it, else do a path search.
709 */
710 if (control->control_dir)
711 {
712 filename = psprintf("%s/%s.control", control->control_dir, control->name);
713 }
714 else
716 }
717
718 if (!filename)
719 {
722 errmsg("extension \"%s\" is not available", control->name),
723 errhint("The extension must first be installed on the system where PostgreSQL is running.")));
724 }
725
726 /* Assert that the control_dir ends with /extension */
727 Assert(control->control_dir != NULL);
728 Assert(strcmp(control->control_dir + strlen(control->control_dir) - strlen("/extension"), "/extension") == 0);
729
730 control->basedir = pnstrdup(
731 control->control_dir,
732 strlen(control->control_dir) - strlen("/extension"));
733
734 if ((file = AllocateFile(filename, "r")) == NULL)
735 {
736 /* no complaint for missing auxiliary file */
737 if (errno == ENOENT && version)
738 {
740 return;
741 }
742
745 errmsg("could not open extension control file \"%s\": %m",
746 filename)));
747 }
748
749 /*
750 * Parse the file content, using GUC's file parsing code. We need not
751 * check the return value since any errors will be thrown at ERROR level.
752 */
754 &head, &tail);
755
756 FreeFile(file);
757
758 /*
759 * Convert the ConfigVariable list into ExtensionControlFile entries.
760 */
761 for (item = head; item != NULL; item = item->next)
762 {
763 if (strcmp(item->name, "directory") == 0)
764 {
765 if (version)
768 errmsg("parameter \"%s\" cannot be set in a secondary extension control file",
769 item->name)));
770
771 control->directory = pstrdup(item->value);
772 }
773 else if (strcmp(item->name, "default_version") == 0)
774 {
775 if (version)
778 errmsg("parameter \"%s\" cannot be set in a secondary extension control file",
779 item->name)));
780
781 control->default_version = pstrdup(item->value);
782 }
783 else if (strcmp(item->name, "module_pathname") == 0)
784 {
785 control->module_pathname = pstrdup(item->value);
786 }
787 else if (strcmp(item->name, "comment") == 0)
788 {
789 control->comment = pstrdup(item->value);
790 }
791 else if (strcmp(item->name, "schema") == 0)
792 {
793 control->schema = pstrdup(item->value);
794 }
795 else if (strcmp(item->name, "relocatable") == 0)
796 {
797 if (!parse_bool(item->value, &control->relocatable))
800 errmsg("parameter \"%s\" requires a Boolean value",
801 item->name)));
802 }
803 else if (strcmp(item->name, "superuser") == 0)
804 {
805 if (!parse_bool(item->value, &control->superuser))
808 errmsg("parameter \"%s\" requires a Boolean value",
809 item->name)));
810 }
811 else if (strcmp(item->name, "trusted") == 0)
812 {
813 if (!parse_bool(item->value, &control->trusted))
816 errmsg("parameter \"%s\" requires a Boolean value",
817 item->name)));
818 }
819 else if (strcmp(item->name, "encoding") == 0)
820 {
821 control->encoding = pg_valid_server_encoding(item->value);
822 if (control->encoding < 0)
825 errmsg("\"%s\" is not a valid encoding name",
826 item->value)));
827 }
828 else if (strcmp(item->name, "requires") == 0)
829 {
830 /* Need a modifiable copy of string */
831 char *rawnames = pstrdup(item->value);
832
833 /* Parse string into list of identifiers */
834 if (!SplitIdentifierString(rawnames, ',', &control->requires))
835 {
836 /* syntax error in name list */
839 errmsg("parameter \"%s\" must be a list of extension names",
840 item->name)));
841 }
842 }
843 else if (strcmp(item->name, "no_relocate") == 0)
844 {
845 /* Need a modifiable copy of string */
846 char *rawnames = pstrdup(item->value);
847
848 /* Parse string into list of identifiers */
849 if (!SplitIdentifierString(rawnames, ',', &control->no_relocate))
850 {
851 /* syntax error in name list */
854 errmsg("parameter \"%s\" must be a list of extension names",
855 item->name)));
856 }
857 }
858 else
861 errmsg("unrecognized parameter \"%s\" in file \"%s\"",
862 item->name, filename)));
863 }
864
866
867 if (control->relocatable && control->schema != NULL)
870 errmsg("parameter \"schema\" cannot be specified when \"relocatable\" is true")));
871
873}
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:898
static char * get_extension_aux_control_filename(ExtensionControlFile *control, const char *version)
Definition extension.c:638
static char * find_extension_control_filename(ExtensionControlFile *control)
Definition extension.c:593
int FreeFile(FILE *file)
Definition fd.c:2827
FILE * AllocateFile(const char *name, const char *mode)
Definition fd.c:2628
void FreeConfigVariables(ConfigVariable *list)
Definition guc-file.l:617
bool ParseConfigFp(FILE *fp, const char *config_file, int depth, int elevel, ConfigVariable **head_p, ConfigVariable **tail_p)
Definition guc-file.l:350
#define pg_valid_server_encoding
Definition pg_wchar.h:484
char * name
Definition guc.h:141
struct ConfigVariable * next
Definition guc.h:148
char * value
Definition guc.h:142
List *List * no_relocate
Definition extension.c:103
bool SplitIdentifierString(char *rawstring, char separator, List **namelist)
Definition varlena.c:2867

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

Referenced by pg_available_extension_versions(), pg_available_extensions(), 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 2489 of file extension.c.

2490{
2491 ReturnSetInfo *rsinfo = (ReturnSetInfo *) fcinfo->resultinfo;
2492 List *locations;
2493 DIR *dir;
2494 struct dirent *de;
2495 List *found_ext = NIL;
2496
2497 /* Build tuplestore to hold the result rows */
2498 InitMaterializedSRF(fcinfo, 0);
2499
2501
2503 {
2504 dir = AllocateDir(location->loc);
2505
2506 /*
2507 * If the control directory doesn't exist, we want to silently return
2508 * an empty set. Any other error will be reported by ReadDir.
2509 */
2510 if (dir == NULL && errno == ENOENT)
2511 {
2512 /* do nothing */
2513 }
2514 else
2515 {
2516 while ((de = ReadDir(dir, location->loc)) != NULL)
2517 {
2518 ExtensionControlFile *control;
2519 char *extname;
2521
2522 if (!is_extension_control_filename(de->d_name))
2523 continue;
2524
2525 /* extract extension name from 'name.control' filename */
2526 extname = pstrdup(de->d_name);
2527 *strrchr(extname, '.') = '\0';
2528
2529 /* ignore it if it's an auxiliary control file */
2530 if (strstr(extname, "--"))
2531 continue;
2532
2533 /*
2534 * Ignore already-found names. They are not reachable by the
2535 * path search, so don't show them.
2536 */
2537 extname_str = makeString(extname);
2539 continue;
2540 else
2542
2543 /* read the control file */
2544 control = new_ExtensionControlFile(extname);
2545 control->control_dir = pstrdup(location->loc);
2547
2548 /* scan extension's script directory for install scripts */
2549 get_available_versions_for_extension(control, rsinfo->setResult,
2550 rsinfo->setDesc,
2551 location);
2552 }
2553
2554 FreeDir(dir);
2555 }
2556 }
2557
2558 return (Datum) 0;
2559}
static void get_available_versions_for_extension(ExtensionControlFile *pcontrol, Tuplestorestate *tupstore, TupleDesc tupdesc, ExtensionLocation *location)
Definition extension.c:2566
static void parse_extension_control_file(ExtensionControlFile *control, const char *version)
Definition extension.c:691
static ExtensionControlFile * new_ExtensionControlFile(const char *extname)
Definition extension.c:4067
void InitMaterializedSRF(FunctionCallInfo fcinfo, uint32 flags)
Definition funcapi.c:76
bool list_member(const List *list, const void *datum)
Definition list.c:661
Definition value.h:64

References AllocateDir(), ExtensionControlFile::control_dir, fb(), foreach_ptr, FreeDir(), get_available_versions_for_extension(), get_extension_control_directories(), InitMaterializedSRF(), is_extension_control_filename(), lappend(), list_member(), makeString(), new_ExtensionControlFile(), NIL, parse_extension_control_file(), pstrdup(), and ReadDir().

◆ pg_available_extensions()

Datum pg_available_extensions ( PG_FUNCTION_ARGS  )

Definition at line 2387 of file extension.c.

2388{
2389 ReturnSetInfo *rsinfo = (ReturnSetInfo *) fcinfo->resultinfo;
2390 List *locations;
2391 DIR *dir;
2392 struct dirent *de;
2393 List *found_ext = NIL;
2394
2395 /* Build tuplestore to hold the result rows */
2396 InitMaterializedSRF(fcinfo, 0);
2397
2399
2401 {
2402 dir = AllocateDir(location->loc);
2403
2404 /*
2405 * If the control directory doesn't exist, we want to silently return
2406 * an empty set. Any other error will be reported by ReadDir.
2407 */
2408 if (dir == NULL && errno == ENOENT)
2409 {
2410 /* do nothing */
2411 }
2412 else
2413 {
2414 while ((de = ReadDir(dir, location->loc)) != NULL)
2415 {
2416 ExtensionControlFile *control;
2417 char *extname;
2419 Datum values[4];
2420 bool nulls[4];
2421
2422 if (!is_extension_control_filename(de->d_name))
2423 continue;
2424
2425 /* extract extension name from 'name.control' filename */
2426 extname = pstrdup(de->d_name);
2427 *strrchr(extname, '.') = '\0';
2428
2429 /* ignore it if it's an auxiliary control file */
2430 if (strstr(extname, "--"))
2431 continue;
2432
2433 /*
2434 * Ignore already-found names. They are not reachable by the
2435 * path search, so don't show them.
2436 */
2437 extname_str = makeString(extname);
2439 continue;
2440 else
2442
2443 control = new_ExtensionControlFile(extname);
2444 control->control_dir = pstrdup(location->loc);
2446
2447 memset(values, 0, sizeof(values));
2448 memset(nulls, 0, sizeof(nulls));
2449
2450 /* name */
2452 CStringGetDatum(control->name));
2453 /* default_version */
2454 if (control->default_version == NULL)
2455 nulls[1] = true;
2456 else
2458
2459 /* location */
2461
2462 /* comment */
2463 if (control->comment == NULL)
2464 nulls[3] = true;
2465 else
2466 values[3] = CStringGetTextDatum(control->comment);
2467
2468 tuplestore_putvalues(rsinfo->setResult, rsinfo->setDesc,
2469 values, nulls);
2470 }
2471
2472 FreeDir(dir);
2473 }
2474 }
2475
2476 return (Datum) 0;
2477}

References AllocateDir(), ExtensionControlFile::comment, ExtensionControlFile::control_dir, CStringGetDatum(), CStringGetTextDatum, ExtensionControlFile::default_version, DirectFunctionCall1, fb(), foreach_ptr, FreeDir(), get_extension_control_directories(), get_extension_location(), InitMaterializedSRF(), is_extension_control_filename(), lappend(), list_member(), makeString(), ExtensionControlFile::name, namein(), new_ExtensionControlFile(), NIL, parse_extension_control_file(), pstrdup(), ReadDir(), tuplestore_putvalues(), and values.

◆ pg_extension_config_dump()

Datum pg_extension_config_dump ( PG_FUNCTION_ARGS  )

Definition at line 2855 of file extension.c.

2856{
2857 Oid tableoid = PG_GETARG_OID(0);
2859 char *tablename;
2861 ScanKeyData key[1];
2866 int arrayLength;
2867 int arrayIndex;
2868 bool isnull;
2872 ArrayType *a;
2873
2874 /*
2875 * We only allow this to be called from an extension's SQL script. We
2876 * shouldn't need any permissions check beyond that.
2877 */
2878 if (!creating_extension)
2879 ereport(ERROR,
2881 errmsg("%s can only be called from an SQL script executed by CREATE EXTENSION",
2882 "pg_extension_config_dump()")));
2883
2884 /*
2885 * Check that the table exists and is a member of the extension being
2886 * created. This ensures that we don't need to register an additional
2887 * dependency to protect the extconfig entry.
2888 */
2889 tablename = get_rel_name(tableoid);
2890 if (tablename == NULL)
2891 ereport(ERROR,
2893 errmsg("OID %u does not refer to a table", tableoid)));
2896 ereport(ERROR,
2898 errmsg("table \"%s\" is not a member of the extension being created",
2899 tablename)));
2900
2901 /*
2902 * Add the table OID and WHERE condition to the extension's extconfig and
2903 * extcondition arrays.
2904 *
2905 * If the table is already in extconfig, treat this as an update of the
2906 * WHERE condition.
2907 */
2908
2909 /* Find the pg_extension tuple */
2911
2912 ScanKeyInit(&key[0],
2916
2918 NULL, 1, key);
2919
2921
2922 if (!HeapTupleIsValid(extTup)) /* should not happen */
2923 elog(ERROR, "could not find tuple for extension %u",
2925
2926 memset(repl_val, 0, sizeof(repl_val));
2927 memset(repl_null, false, sizeof(repl_null));
2928 memset(repl_repl, false, sizeof(repl_repl));
2929
2930 /* Build or modify the extconfig value */
2931 elementDatum = ObjectIdGetDatum(tableoid);
2932
2934 RelationGetDescr(extRel), &isnull);
2935 if (isnull)
2936 {
2937 /* Previously empty extconfig, so build 1-element array */
2938 arrayLength = 0;
2939 arrayIndex = 1;
2940
2942 }
2943 else
2944 {
2945 /* Modify or extend existing extconfig array */
2946 Oid *arrayData;
2947 int i;
2948
2950
2951 arrayLength = ARR_DIMS(a)[0];
2952 if (ARR_NDIM(a) != 1 ||
2953 ARR_LBOUND(a)[0] != 1 ||
2954 arrayLength < 0 ||
2955 ARR_HASNULL(a) ||
2956 ARR_ELEMTYPE(a) != OIDOID)
2957 elog(ERROR, "extconfig is not a 1-D Oid array");
2958 arrayData = (Oid *) ARR_DATA_PTR(a);
2959
2960 arrayIndex = arrayLength + 1; /* set up to add after end */
2961
2962 for (i = 0; i < arrayLength; i++)
2963 {
2964 if (arrayData[i] == tableoid)
2965 {
2966 arrayIndex = i + 1; /* replace this element instead */
2967 break;
2968 }
2969 }
2970
2971 a = array_set(a, 1, &arrayIndex,
2973 false,
2974 -1 /* varlena array */ ,
2975 sizeof(Oid) /* OID's typlen */ ,
2976 true /* OID's typbyval */ ,
2977 TYPALIGN_INT /* OID's typalign */ );
2978 }
2981
2982 /* Build or modify the extcondition value */
2984
2986 RelationGetDescr(extRel), &isnull);
2987 if (isnull)
2988 {
2989 if (arrayLength != 0)
2990 elog(ERROR, "extconfig and extcondition arrays do not match");
2991
2993 }
2994 else
2995 {
2997
2998 if (ARR_NDIM(a) != 1 ||
2999 ARR_LBOUND(a)[0] != 1 ||
3000 ARR_HASNULL(a) ||
3002 elog(ERROR, "extcondition is not a 1-D text array");
3003 if (ARR_DIMS(a)[0] != arrayLength)
3004 elog(ERROR, "extconfig and extcondition arrays do not match");
3005
3006 /* Add or replace at same index as in extconfig */
3007 a = array_set(a, 1, &arrayIndex,
3009 false,
3010 -1 /* varlena array */ ,
3011 -1 /* TEXT's typlen */ ,
3012 false /* TEXT's typbyval */ ,
3013 TYPALIGN_INT /* TEXT's typalign */ );
3014 }
3017
3020
3022
3024
3026
3028}
ArrayType * array_set(ArrayType *array, int nSubscripts, int *indx, Datum dataValue, bool isNull, int arraytyplen, int elmlen, bool elmbyval, char elmalign)
#define PG_RETURN_VOID()
Definition fmgr.h:350
#define PG_GETARG_OID(n)
Definition fmgr.h:275
#define PG_GETARG_TEXT_PP(n)
Definition fmgr.h:310
char * get_rel_name(Oid relid)
Definition lsyscache.c:2121
#define ERRCODE_UNDEFINED_TABLE
Definition pgbench.c:79
Definition c.h:776

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, fb(), get_rel_name(), getExtensionOfObject(), heap_getattr(), heap_modify_tuple(), HeapTupleIsValid, i, ObjectIdGetDatum(), PG_GETARG_OID, PG_GETARG_TEXT_PP, PG_RETURN_VOID, PointerGetDatum, RelationGetDescr, RowExclusiveLock, ScanKeyInit(), systable_beginscan(), systable_endscan(), systable_getnext(), table_close(), and table_open().

◆ pg_extension_update_paths()

Datum pg_extension_update_paths ( PG_FUNCTION_ARGS  )

Definition at line 2770 of file extension.c.

2771{
2772 Name extname = PG_GETARG_NAME(0);
2773 ReturnSetInfo *rsinfo = (ReturnSetInfo *) fcinfo->resultinfo;
2774 List *evi_list;
2775 ExtensionControlFile *control;
2776 ListCell *lc1;
2777
2778 /* Check extension name validity before any filesystem access */
2780
2781 /* Build tuplestore to hold the result rows */
2782 InitMaterializedSRF(fcinfo, 0);
2783
2784 /* Read the extension's control file */
2785 control = read_extension_control_file(NameStr(*extname));
2786
2787 /* Extract the version update graph from the script directory */
2788 evi_list = get_ext_ver_list(control);
2789
2790 /* Iterate over all pairs of versions */
2791 foreach(lc1, evi_list)
2792 {
2794 ListCell *lc2;
2795
2796 foreach(lc2, evi_list)
2797 {
2799 List *path;
2800 Datum values[3];
2801 bool nulls[3];
2802
2803 if (evi1 == evi2)
2804 continue;
2805
2806 /* Find shortest path from evi1 to evi2 */
2807 path = find_update_path(evi_list, evi1, evi2, false, true);
2808
2809 /* Emit result row */
2810 memset(values, 0, sizeof(values));
2811 memset(nulls, 0, sizeof(nulls));
2812
2813 /* source */
2814 values[0] = CStringGetTextDatum(evi1->name);
2815 /* target */
2816 values[1] = CStringGetTextDatum(evi2->name);
2817 /* path */
2818 if (path == NIL)
2819 nulls[2] = true;
2820 else
2821 {
2823 ListCell *lcv;
2824
2826 /* The path doesn't include start vertex, but show it */
2828 foreach(lcv, path)
2829 {
2830 char *versionName = (char *) lfirst(lcv);
2831
2834 }
2836 pfree(pathbuf.data);
2837 }
2838
2839 tuplestore_putvalues(rsinfo->setResult, rsinfo->setDesc,
2840 values, nulls);
2841 }
2842 }
2843
2844 return (Datum) 0;
2845}
#define PG_GETARG_NAME(n)
Definition fmgr.h:279
Definition c.h:830

References appendStringInfoString(), check_valid_extension_name(), CStringGetTextDatum, fb(), find_update_path(), get_ext_ver_list(), InitMaterializedSRF(), initStringInfo(), lfirst, NameStr, NIL, pfree(), PG_GETARG_NAME, read_extension_control_file(), tuplestore_putvalues(), and values.

◆ pg_get_loaded_modules()

Datum pg_get_loaded_modules ( PG_FUNCTION_ARGS  )

Definition at line 3038 of file extension.c.

3039{
3040 ReturnSetInfo *rsinfo = (ReturnSetInfo *) fcinfo->resultinfo;
3042
3043 /* Build tuplestore to hold the result rows */
3044 InitMaterializedSRF(fcinfo, 0);
3045
3048 {
3049 const char *library_path,
3050 *module_name,
3052 const char *sep;
3053 Datum values[3] = {0};
3054 bool nulls[3] = {0};
3055
3057 &library_path,
3058 &module_name,
3060
3061 if (module_name == NULL)
3062 nulls[0] = true;
3063 else
3065 if (module_version == NULL)
3066 nulls[1] = true;
3067 else
3069
3070 /* For security reasons, we don't show the directory path */
3072 if (sep)
3073 library_path = sep + 1;
3075
3076 tuplestore_putvalues(rsinfo->setResult, rsinfo->setDesc,
3077 values, nulls);
3078 }
3079
3080 return (Datum) 0;
3081}
DynamicFileList * get_next_loaded_module(DynamicFileList *dfptr)
Definition dfmgr.c:431
DynamicFileList * get_first_loaded_module(void)
Definition dfmgr.c:425
void get_loaded_module_details(DynamicFileList *dfptr, const char **library_path, const char **module_name, const char **module_version)
Definition dfmgr.c:445
char * last_dir_separator(const char *filename)
Definition path.c:145

References CStringGetTextDatum, fb(), get_first_loaded_module(), get_loaded_module_details(), get_next_loaded_module(), InitMaterializedSRF(), last_dir_separator(), 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 898 of file extension.c.

900{
902
903 /*
904 * Flat-copy the struct. Pointer fields share values with original.
905 */
908
909 /*
910 * Parse the auxiliary control file, overwriting struct fields
911 */
913
914 return acontrol;
915}
memcpy(sums, checksumBaseOffsets, sizeof(checksumBaseOffsets))

References fb(), memcpy(), palloc_object, 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 879 of file extension.c.

880{
882
883 /*
884 * Parse the primary control file.
885 */
887
888 return control;
889}

References fb(), new_ExtensionControlFile(), and parse_extension_control_file().

Referenced by AlterExtensionNamespace(), CreateExtensionInternal(), ExecAlterExtensionStmt(), 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 921 of file extension.c.

923{
924 int src_encoding;
925 char *src_str;
926 char *dest_str;
927 int len;
928
930
931 /* use database encoding if not given */
932 if (control->encoding < 0)
934 else
935 src_encoding = control->encoding;
936
937 /* make sure that source string is valid in the expected encoding */
939
940 /*
941 * Convert the encoding to the database encoding. read_whole_file
942 * null-terminated the string, so if no conversion happens the string is
943 * valid as is.
944 */
946
947 return dest_str;
948}
static char * read_whole_file(const char *filename, int *length)
Definition extension.c:4002
int GetDatabaseEncoding(void)
Definition mbutils.c:1388
char * pg_any_to_server(const char *s, int len, int encoding)
Definition mbutils.c:687
bool pg_verify_mbstr(int encoding, const char *mbstr, int len, bool noError)
Definition mbutils.c:1692

References ExtensionControlFile::encoding, fb(), 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 4002 of file extension.c.

4003{
4004 char *buf;
4005 FILE *file;
4006 size_t bytes_to_read;
4007 struct stat fst;
4008
4009 if (stat(filename, &fst) < 0)
4010 ereport(ERROR,
4012 errmsg("could not stat file \"%s\": %m", filename)));
4013
4014 if (fst.st_size > (MaxAllocSize - 1))
4015 ereport(ERROR,
4017 errmsg("file \"%s\" is too large", filename)));
4018 bytes_to_read = (size_t) fst.st_size;
4019
4020 if ((file = AllocateFile(filename, PG_BINARY_R)) == NULL)
4021 ereport(ERROR,
4023 errmsg("could not open file \"%s\" for reading: %m",
4024 filename)));
4025
4026 buf = (char *) palloc(bytes_to_read + 1);
4027
4028 bytes_to_read = fread(buf, 1, bytes_to_read, file);
4029
4030 if (ferror(file))
4031 ereport(ERROR,
4033 errmsg("could not read file \"%s\": %m", filename)));
4034
4035 FreeFile(file);
4036
4037 buf[bytes_to_read] = '\0';
4038
4039 /*
4040 * On Windows, manually convert Windows-style newlines (\r\n) to the Unix
4041 * convention of \n only. This avoids gotchas due to script files
4042 * possibly getting converted when being transferred between platforms.
4043 * Ideally we'd do this by using text mode to read the file, but that also
4044 * causes control-Z to be treated as end-of-file. Historically we've
4045 * allowed control-Z in script files, so breaking that seems unwise.
4046 */
4047#ifdef WIN32
4048 {
4049 char *s,
4050 *d;
4051
4052 for (s = d = buf; *s; s++)
4053 {
4054 if (!(*s == '\r' && s[1] == '\n'))
4055 *d++ = *s;
4056 }
4057 *d = '\0';
4058 bytes_to_read = d - buf;
4059 }
4060#endif
4061
4062 *length = bytes_to_read;
4063 return buf;
4064}
#define PG_BINARY_R
Definition c.h:1376
#define MaxAllocSize
Definition fe_memutils.h:22
static char buf[DEFAULT_XLOG_SEG_SIZE]

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

Referenced by read_extension_script_file().

◆ RemoveExtensionById()

void RemoveExtensionById ( Oid  extId)

Definition at line 2333 of file extension.c.

2334{
2335 Relation rel;
2336 SysScanDesc scandesc;
2337 HeapTuple tuple;
2338 ScanKeyData entry[1];
2339
2340 /*
2341 * Disallow deletion of any extension that's currently open for insertion;
2342 * else subsequent executions of recordDependencyOnCurrentExtension()
2343 * could create dangling pg_depend records that refer to a no-longer-valid
2344 * pg_extension OID. This is needed not so much because we think people
2345 * might write "DROP EXTENSION foo" in foo's own script files, as because
2346 * errors in dependency management in extension script files could give
2347 * rise to cases where an extension is dropped as a result of recursing
2348 * from some contained object. Because of that, we must test for the case
2349 * here, not at some higher level of the DROP EXTENSION command.
2350 */
2352 ereport(ERROR,
2354 errmsg("cannot drop extension \"%s\" because it is being modified",
2356
2358
2359 ScanKeyInit(&entry[0],
2363 scandesc = systable_beginscan(rel, ExtensionOidIndexId, true,
2364 NULL, 1, entry);
2365
2366 tuple = systable_getnext(scandesc);
2367
2368 /* We assume that there can be at most one matching tuple */
2369 if (HeapTupleIsValid(tuple))
2370 CatalogTupleDelete(rel, &tuple->t_self);
2371
2372 systable_endscan(scandesc);
2373
2375}
void CatalogTupleDelete(Relation heapRel, const ItemPointerData *tid)
Definition indexing.c:365
ItemPointerData t_self
Definition htup.h:65

References BTEqualStrategyNumber, CatalogTupleDelete(), CurrentExtensionObject, ereport, errcode(), errmsg, ERROR, fb(), 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 954 of file extension.c.

955{
957 const char *query = callback_arg->sql;
958 int location = callback_arg->stmt_location;
959 int len = callback_arg->stmt_len;
961 const char *lastslash;
962
963 /*
964 * If there is a syntax error position, convert to internal syntax error;
965 * otherwise report the current query as an item of context stack.
966 *
967 * Note: we'll provide no context except the filename if there's neither
968 * an error position nor any known current query. That shouldn't happen
969 * though: all errors reported during raw parsing should come with an
970 * error position.
971 */
973 if (syntaxerrposition > 0)
974 {
975 /*
976 * If we do not know the bounds of the current statement (as would
977 * happen for an error occurring during initial raw parsing), we have
978 * to use a heuristic to decide how much of the script to show. We'll
979 * also use the heuristic in the unlikely case that syntaxerrposition
980 * is outside what we think the statement bounds are.
981 */
982 if (location < 0 || syntaxerrposition < location ||
983 (len > 0 && syntaxerrposition > location + len))
984 {
985 /*
986 * Our heuristic is pretty simple: look for semicolon-newline
987 * sequences, and break at the last one strictly before
988 * syntaxerrposition and the first one strictly after. It's
989 * certainly possible to fool this with semicolon-newline embedded
990 * in a string literal, but it seems better to do this than to
991 * show the entire extension script.
992 *
993 * Notice we cope with Windows-style newlines (\r\n) regardless of
994 * platform. This is because there might be such newlines in
995 * script files on other platforms.
996 */
997 int slen = strlen(query);
998
999 location = len = 0;
1000 for (int loc = 0; loc < slen; loc++)
1001 {
1002 if (query[loc] != ';')
1003 continue;
1004 if (query[loc + 1] == '\r')
1005 loc++;
1006 if (query[loc + 1] == '\n')
1007 {
1008 int bkpt = loc + 2;
1009
1010 if (bkpt < syntaxerrposition)
1011 location = bkpt;
1012 else if (bkpt > syntaxerrposition)
1013 {
1014 len = bkpt - location;
1015 break; /* no need to keep searching */
1016 }
1017 }
1018 }
1019 }
1020
1021 /* Trim leading/trailing whitespace, for consistency */
1022 query = CleanQuerytext(query, &location, &len);
1023
1024 /*
1025 * Adjust syntaxerrposition. It shouldn't be pointing into the
1026 * whitespace we just trimmed, but cope if it is.
1027 */
1028 syntaxerrposition -= location;
1029 if (syntaxerrposition < 0)
1031 else if (syntaxerrposition > len)
1033
1034 /* And report. */
1035 errposition(0);
1037 internalerrquery(pnstrdup(query, len));
1038 }
1039 else if (location >= 0)
1040 {
1041 /*
1042 * Since no syntax cursor will be shown, it's okay and helpful to trim
1043 * the reported query string to just the current statement.
1044 */
1045 query = CleanQuerytext(query, &location, &len);
1046 errcontext("SQL statement \"%.*s\"", len, query);
1047 }
1048
1049 /*
1050 * Trim the reported file name to remove the path. We know that
1051 * get_extension_script_filename() inserted a '/', regardless of whether
1052 * we're on Windows.
1053 */
1054 lastslash = strrchr(callback_arg->filename, '/');
1055 if (lastslash)
1056 lastslash++;
1057 else
1058 lastslash = callback_arg->filename; /* shouldn't happen, but cope */
1059
1060 /*
1061 * If we have a location (which, as said above, we really always should)
1062 * then report a line number to aid in localizing problems in big scripts.
1063 */
1064 if (location >= 0)
1065 {
1066 int linenumber = 1;
1067
1068 for (query = callback_arg->sql; *query; query++)
1069 {
1070 if (--location < 0)
1071 break;
1072 if (*query == '\n')
1073 linenumber++;
1074 }
1075 errcontext("extension script file \"%s\", near line %d",
1076 lastslash, linenumber);
1077 }
1078 else
1079 errcontext("extension script file \"%s\"", lastslash);
1080}
Datum arg
Definition elog.c:1323
#define errcontext
Definition elog.h:200
int internalerrquery(const char *query)
int internalerrposition(int cursorpos)
int geterrposition(void)
int errposition(int cursorpos)
const char * CleanQuerytext(const char *query, int *location, int *len)

References arg, CleanQuerytext(), errcontext, errposition(), fb(), 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

◆ ext_sibling_list

ExtensionSiblingCache* ext_sibling_list = NULL
static

Definition at line 163 of file extension.c.

Referenced by ext_sibling_callback(), and get_function_sibling_type().

◆ Extension_control_path

char* Extension_control_path

Definition at line 77 of file extension.c.

Referenced by get_extension_control_directories().