Branch data Line data Source code
1 : : /*-------------------------------------------------------------------------
2 : : *
3 : : * extension.c
4 : : * Commands to manipulate extensions
5 : : *
6 : : * Extensions in PostgreSQL allow management of collections of SQL objects.
7 : : *
8 : : * All we need internally to manage an extension is an OID so that the
9 : : * dependent objects can be associated with it. An extension is created by
10 : : * populating the pg_extension catalog from a "control" file.
11 : : * The extension control file is parsed with the same parser we use for
12 : : * postgresql.conf. An extension also has an installation script file,
13 : : * containing SQL commands to create the extension's objects.
14 : : *
15 : : * Portions Copyright (c) 1996-2026, PostgreSQL Global Development Group
16 : : * Portions Copyright (c) 1994, Regents of the University of California
17 : : *
18 : : *
19 : : * IDENTIFICATION
20 : : * src/backend/commands/extension.c
21 : : *
22 : : *-------------------------------------------------------------------------
23 : : */
24 : : #include "postgres.h"
25 : :
26 : : #include <dirent.h>
27 : : #include <limits.h>
28 : : #include <sys/file.h>
29 : : #include <sys/stat.h>
30 : : #include <unistd.h>
31 : :
32 : : #include "access/genam.h"
33 : : #include "access/htup_details.h"
34 : : #include "access/relation.h"
35 : : #include "access/table.h"
36 : : #include "access/xact.h"
37 : : #include "catalog/catalog.h"
38 : : #include "catalog/dependency.h"
39 : : #include "catalog/indexing.h"
40 : : #include "catalog/namespace.h"
41 : : #include "catalog/objectaccess.h"
42 : : #include "catalog/pg_authid.h"
43 : : #include "catalog/pg_collation.h"
44 : : #include "catalog/pg_database.h"
45 : : #include "catalog/pg_depend.h"
46 : : #include "catalog/pg_extension.h"
47 : : #include "catalog/pg_namespace.h"
48 : : #include "catalog/pg_proc.h"
49 : : #include "catalog/pg_type.h"
50 : : #include "commands/alter.h"
51 : : #include "commands/comment.h"
52 : : #include "commands/defrem.h"
53 : : #include "commands/extension.h"
54 : : #include "commands/schemacmds.h"
55 : : #include "funcapi.h"
56 : : #include "mb/pg_wchar.h"
57 : : #include "miscadmin.h"
58 : : #include "nodes/pg_list.h"
59 : : #include "nodes/queryjumble.h"
60 : : #include "storage/fd.h"
61 : : #include "storage/lmgr.h"
62 : : #include "storage/lock.h"
63 : : #include "tcop/utility.h"
64 : : #include "utils/acl.h"
65 : : #include "utils/builtins.h"
66 : : #include "utils/conffiles.h"
67 : : #include "utils/fmgroids.h"
68 : : #include "utils/inval.h"
69 : : #include "utils/lsyscache.h"
70 : : #include "utils/memutils.h"
71 : : #include "utils/rel.h"
72 : : #include "utils/snapmgr.h"
73 : : #include "utils/syscache.h"
74 : : #include "utils/tuplestore.h"
75 : : #include "utils/varlena.h"
76 : :
77 : :
78 : : /* GUC */
79 : : char *Extension_control_path;
80 : :
81 : : /* Globally visible state variables */
82 : : bool creating_extension = false;
83 : : Oid CurrentExtensionObject = InvalidOid;
84 : :
85 : : /*
86 : : * Internal data structure to hold the results of parsing a control file
87 : : */
88 : : typedef struct ExtensionControlFile
89 : : {
90 : : char *name; /* name of the extension */
91 : : char *basedir; /* base directory where control and script
92 : : * files are located */
93 : : char *control_dir; /* directory where control file was found */
94 : : char *directory; /* directory for script files */
95 : : char *default_version; /* default install target version, if any */
96 : : char *module_pathname; /* string to substitute for
97 : : * MODULE_PATHNAME */
98 : : char *comment; /* comment, if any */
99 : : char *schema; /* target schema (allowed if !relocatable) */
100 : : bool relocatable; /* is ALTER EXTENSION SET SCHEMA supported? */
101 : : bool superuser; /* must be superuser to install? */
102 : : bool trusted; /* allow becoming superuser on the fly? */
103 : : int encoding; /* encoding of the script file, or -1 */
104 : : List *requires; /* names of prerequisite extensions */
105 : : List *no_relocate; /* names of prerequisite extensions that
106 : : * should not be relocated */
107 : : } ExtensionControlFile;
108 : :
109 : : /*
110 : : * Internal data structure for update path information
111 : : */
112 : : typedef struct ExtensionVersionInfo
113 : : {
114 : : char *name; /* name of the starting version */
115 : : List *reachable; /* List of ExtensionVersionInfo's */
116 : : bool installable; /* does this version have an install script? */
117 : : /* working state for Dijkstra's algorithm: */
118 : : bool distance_known; /* is distance from start known yet? */
119 : : int distance; /* current worst-case distance estimate */
120 : : struct ExtensionVersionInfo *previous; /* current best predecessor */
121 : : } ExtensionVersionInfo;
122 : :
123 : : /*
124 : : * Information for script_error_callback()
125 : : */
126 : : typedef struct
127 : : {
128 : : const char *sql; /* entire script file contents */
129 : : const char *filename; /* script file pathname */
130 : : ParseLoc stmt_location; /* current stmt start loc, or -1 if unknown */
131 : : ParseLoc stmt_len; /* length in bytes; 0 means "rest of string" */
132 : : } script_error_callback_arg;
133 : :
134 : : /*
135 : : * A location based on the extension_control_path GUC.
136 : : *
137 : : * The macro field stores the name of a macro (for example “$system”) that
138 : : * the extension_control_path processing supports, and which can be replaced
139 : : * by a system value stored in loc.
140 : : *
141 : : * For non-system paths the macro field is NULL.
142 : : */
143 : : typedef struct
144 : : {
145 : : char *macro;
146 : : char *loc;
147 : : } ExtensionLocation;
148 : :
149 : : /*
150 : : * Cache structure for get_function_sibling_type (and maybe later,
151 : : * allied lookup functions).
152 : : */
153 : : typedef struct ExtensionSiblingCache
154 : : {
155 : : struct ExtensionSiblingCache *next; /* list link */
156 : : /* lookup key: requesting function's OID and type name */
157 : : Oid reqfuncoid;
158 : : const char *typname;
159 : : bool valid; /* is entry currently valid? */
160 : : uint32 exthash; /* cache hash of owning extension's OID */
161 : : Oid typeoid; /* OID associated with typname */
162 : : } ExtensionSiblingCache;
163 : :
164 : : /* Head of linked list of ExtensionSiblingCache structs */
165 : : static ExtensionSiblingCache *ext_sibling_list = NULL;
166 : :
167 : : /* Local functions */
168 : : static void ext_sibling_callback(Datum arg, SysCacheIdentifier cacheid,
169 : : uint32 hashvalue);
170 : : static List *find_update_path(List *evi_list,
171 : : ExtensionVersionInfo *evi_start,
172 : : ExtensionVersionInfo *evi_target,
173 : : bool reject_indirect,
174 : : bool reinitialize);
175 : : static Oid get_required_extension(char *reqExtensionName,
176 : : char *extensionName,
177 : : char *origSchemaName,
178 : : bool cascade,
179 : : List *parents,
180 : : bool is_create);
181 : : static void get_available_versions_for_extension(ExtensionControlFile *pcontrol,
182 : : Tuplestorestate *tupstore,
183 : : TupleDesc tupdesc,
184 : : ExtensionLocation *location);
185 : : static Datum convert_requires_to_datum(List *requires);
186 : : static void ApplyExtensionUpdates(Oid extensionOid,
187 : : ExtensionControlFile *pcontrol,
188 : : const char *initialVersion,
189 : : List *updateVersions,
190 : : char *origSchemaName,
191 : : bool cascade,
192 : : bool is_create);
193 : : static void ExecAlterExtensionContentsRecurse(AlterExtensionContentsStmt *stmt,
194 : : ObjectAddress extension,
195 : : ObjectAddress object);
196 : : static char *read_whole_file(const char *filename, int *length);
197 : : static ExtensionControlFile *new_ExtensionControlFile(const char *extname);
198 : :
199 : : char *find_in_paths(const char *basename, List *paths);
200 : :
201 : : /*
202 : : * Return the extension location. If the current user doesn't have sufficient
203 : : * privilege, don't show the location.
204 : : */
205 : : static char *
206 : 9928 : get_extension_location(ExtensionLocation *loc)
207 : : {
208 : : /* We only want to show extension paths for superusers. */
209 [ + + ]: 9928 : if (superuser())
210 : : {
211 : : /* Return the macro value if present to avoid showing system paths. */
212 [ + + ]: 9688 : if (loc->macro != NULL)
213 : 9676 : return loc->macro;
214 : : else
215 : 12 : return loc->loc;
216 : : }
217 : : else
218 : : {
219 : : /* Similar to pg_stat_activity for unprivileged users */
220 : 240 : return "<insufficient privilege>";
221 : : }
222 : : }
223 : :
224 : : /*
225 : : * get_extension_oid - given an extension name, look up the OID
226 : : *
227 : : * If missing_ok is false, throw an error if extension name not found. If
228 : : * true, just return InvalidOid.
229 : : */
230 : : Oid
231 : 1771 : get_extension_oid(const char *extname, bool missing_ok)
232 : : {
233 : : Oid result;
234 : :
235 : 1771 : result = GetSysCacheOid1(EXTENSIONNAME, Anum_pg_extension_oid,
236 : : CStringGetDatum(extname));
237 : :
238 [ + + + + ]: 1771 : if (!OidIsValid(result) && !missing_ok)
239 [ + - ]: 8 : ereport(ERROR,
240 : : (errcode(ERRCODE_UNDEFINED_OBJECT),
241 : : errmsg("extension \"%s\" does not exist",
242 : : extname)));
243 : :
244 : 1763 : return result;
245 : : }
246 : :
247 : : /*
248 : : * get_extension_name - given an extension OID, look up the name
249 : : *
250 : : * Returns a palloc'd string, or NULL if no such extension.
251 : : */
252 : : char *
253 : 65 : get_extension_name(Oid ext_oid)
254 : : {
255 : : char *result;
256 : : HeapTuple tuple;
257 : :
258 : 65 : tuple = SearchSysCache1(EXTENSIONOID, ObjectIdGetDatum(ext_oid));
259 : :
260 [ + + ]: 65 : if (!HeapTupleIsValid(tuple))
261 : 12 : return NULL;
262 : :
263 : 53 : result = pstrdup(NameStr(((Form_pg_extension) GETSTRUCT(tuple))->extname));
264 : 53 : ReleaseSysCache(tuple);
265 : :
266 : 53 : return result;
267 : : }
268 : :
269 : : /*
270 : : * get_extension_schema - given an extension OID, fetch its extnamespace
271 : : *
272 : : * Returns InvalidOid if no such extension.
273 : : */
274 : : Oid
275 : 28 : get_extension_schema(Oid ext_oid)
276 : : {
277 : : Oid result;
278 : : HeapTuple tuple;
279 : :
280 : 28 : tuple = SearchSysCache1(EXTENSIONOID, ObjectIdGetDatum(ext_oid));
281 : :
282 [ - + ]: 28 : if (!HeapTupleIsValid(tuple))
283 : 0 : return InvalidOid;
284 : :
285 : 28 : result = ((Form_pg_extension) GETSTRUCT(tuple))->extnamespace;
286 : 28 : ReleaseSysCache(tuple);
287 : :
288 : 28 : return result;
289 : : }
290 : :
291 : : /*
292 : : * get_function_sibling_type - find a type belonging to same extension as func
293 : : *
294 : : * Returns the type's OID, or InvalidOid if not found.
295 : : *
296 : : * This is useful in extensions, which won't have fixed object OIDs.
297 : : * We work from the calling function's own OID, which it can get from its
298 : : * FunctionCallInfo parameter, and look up the owning extension and thence
299 : : * a type belonging to the same extension.
300 : : *
301 : : * Notice that the type is specified by name only, without a schema.
302 : : * That's because this will typically be used by relocatable extensions
303 : : * which can't make a-priori assumptions about which schema their objects
304 : : * are in. As long as the extension only defines one type of this name,
305 : : * the answer is unique anyway.
306 : : *
307 : : * We might later add the ability to look up functions, operators, etc.
308 : : *
309 : : * This code is simply a frontend for some pg_depend lookups. Those lookups
310 : : * are fairly expensive, so we provide a simple cache facility. We assume
311 : : * that the passed typname is actually a C constant, or at least permanently
312 : : * allocated, so that we need not copy that string.
313 : : */
314 : : Oid
315 : 49 : get_function_sibling_type(Oid funcoid, const char *typname)
316 : : {
317 : : ExtensionSiblingCache *cache_entry;
318 : : Oid extoid;
319 : : Oid typeoid;
320 : :
321 : : /*
322 : : * See if we have the answer cached. Someday there may be enough callers
323 : : * to justify a hash table, but for now, a simple linked list is fine.
324 : : */
325 [ + + ]: 49 : for (cache_entry = ext_sibling_list; cache_entry != NULL;
326 : 0 : cache_entry = cache_entry->next)
327 : : {
328 [ + - ]: 48 : if (funcoid == cache_entry->reqfuncoid &&
329 [ + - ]: 48 : strcmp(typname, cache_entry->typname) == 0)
330 : 48 : break;
331 : : }
332 [ + + + - ]: 49 : if (cache_entry && cache_entry->valid)
333 : 48 : return cache_entry->typeoid;
334 : :
335 : : /*
336 : : * Nope, so do the expensive lookups. We do not expect failures, so we do
337 : : * not cache negative results.
338 : : */
339 : 1 : extoid = getExtensionOfObject(ProcedureRelationId, funcoid);
340 [ - + ]: 1 : if (!OidIsValid(extoid))
341 : 0 : return InvalidOid;
342 : 1 : typeoid = getExtensionType(extoid, typname);
343 [ - + ]: 1 : if (!OidIsValid(typeoid))
344 : 0 : return InvalidOid;
345 : :
346 : : /*
347 : : * Build, or revalidate, cache entry.
348 : : */
349 [ + - ]: 1 : if (cache_entry == NULL)
350 : : {
351 : : /* Register invalidation hook if this is first entry */
352 [ + - ]: 1 : if (ext_sibling_list == NULL)
353 : 1 : CacheRegisterSyscacheCallback(EXTENSIONOID,
354 : : ext_sibling_callback,
355 : : (Datum) 0);
356 : :
357 : : /* Momentarily zero the space to ensure valid flag is false */
358 : : cache_entry = (ExtensionSiblingCache *)
359 : 1 : MemoryContextAllocZero(CacheMemoryContext,
360 : : sizeof(ExtensionSiblingCache));
361 : 1 : cache_entry->next = ext_sibling_list;
362 : 1 : ext_sibling_list = cache_entry;
363 : : }
364 : :
365 : 1 : cache_entry->reqfuncoid = funcoid;
366 : 1 : cache_entry->typname = typname;
367 : 1 : cache_entry->exthash = GetSysCacheHashValue1(EXTENSIONOID,
368 : : ObjectIdGetDatum(extoid));
369 : 1 : cache_entry->typeoid = typeoid;
370 : : /* Mark it valid only once it's fully populated */
371 : 1 : cache_entry->valid = true;
372 : :
373 : 1 : return typeoid;
374 : : }
375 : :
376 : : /*
377 : : * ext_sibling_callback
378 : : * Syscache inval callback function for EXTENSIONOID cache
379 : : *
380 : : * It seems sufficient to invalidate ExtensionSiblingCache entries when
381 : : * the owning extension's pg_extension entry is modified or deleted.
382 : : * Neither a requesting function's OID, nor the OID of the object it's
383 : : * looking for, could change without an extension update or drop/recreate.
384 : : */
385 : : static void
386 : 0 : ext_sibling_callback(Datum arg, SysCacheIdentifier cacheid, uint32 hashvalue)
387 : : {
388 : : ExtensionSiblingCache *cache_entry;
389 : :
390 [ # # ]: 0 : for (cache_entry = ext_sibling_list; cache_entry != NULL;
391 : 0 : cache_entry = cache_entry->next)
392 : : {
393 [ # # ]: 0 : if (hashvalue == 0 ||
394 [ # # ]: 0 : cache_entry->exthash == hashvalue)
395 : 0 : cache_entry->valid = false;
396 : : }
397 : 0 : }
398 : :
399 : : /*
400 : : * Utility functions to check validity of extension and version names
401 : : */
402 : : static void
403 : 401 : check_valid_extension_name(const char *extensionname)
404 : : {
405 : 401 : int namelen = strlen(extensionname);
406 : :
407 : : /*
408 : : * Disallow empty names (the parser rejects empty identifiers anyway, but
409 : : * let's check).
410 : : */
411 [ - + ]: 401 : if (namelen == 0)
412 [ # # ]: 0 : ereport(ERROR,
413 : : (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
414 : : errmsg("invalid extension name: \"%s\"", extensionname),
415 : : errdetail("Extension names must not be empty.")));
416 : :
417 : : /*
418 : : * No double dashes, since that would make script filenames ambiguous.
419 : : */
420 [ - + ]: 401 : if (strstr(extensionname, "--"))
421 [ # # ]: 0 : ereport(ERROR,
422 : : (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
423 : : errmsg("invalid extension name: \"%s\"", extensionname),
424 : : errdetail("Extension names must not contain \"--\".")));
425 : :
426 : : /*
427 : : * No leading or trailing dash either. (We could probably allow this, but
428 : : * it would require much care in filename parsing and would make filenames
429 : : * visually if not formally ambiguous. Since there's no real-world use
430 : : * case, let's just forbid it.)
431 : : */
432 [ + - - + ]: 401 : if (extensionname[0] == '-' || extensionname[namelen - 1] == '-')
433 [ # # ]: 0 : ereport(ERROR,
434 : : (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
435 : : errmsg("invalid extension name: \"%s\"", extensionname),
436 : : errdetail("Extension names must not begin or end with \"-\".")));
437 : :
438 : : /*
439 : : * No directory separators either (this is sufficient to prevent ".."
440 : : * style attacks).
441 : : */
442 [ - + ]: 401 : if (first_dir_separator(extensionname) != NULL)
443 [ # # ]: 0 : ereport(ERROR,
444 : : (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
445 : : errmsg("invalid extension name: \"%s\"", extensionname),
446 : : errdetail("Extension names must not contain directory separator characters.")));
447 : 401 : }
448 : :
449 : : static void
450 : 416 : check_valid_version_name(const char *versionname)
451 : : {
452 : 416 : int namelen = strlen(versionname);
453 : :
454 : : /*
455 : : * Disallow empty names (we could possibly allow this, but there seems
456 : : * little point).
457 : : */
458 [ - + ]: 416 : if (namelen == 0)
459 [ # # ]: 0 : ereport(ERROR,
460 : : (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
461 : : errmsg("invalid extension version name: \"%s\"", versionname),
462 : : errdetail("Version names must not be empty.")));
463 : :
464 : : /*
465 : : * No double dashes, since that would make script filenames ambiguous.
466 : : */
467 [ - + ]: 416 : if (strstr(versionname, "--"))
468 [ # # ]: 0 : ereport(ERROR,
469 : : (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
470 : : errmsg("invalid extension version name: \"%s\"", versionname),
471 : : errdetail("Version names must not contain \"--\".")));
472 : :
473 : : /*
474 : : * No leading or trailing dash either.
475 : : */
476 [ + - - + ]: 416 : if (versionname[0] == '-' || versionname[namelen - 1] == '-')
477 [ # # ]: 0 : ereport(ERROR,
478 : : (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
479 : : errmsg("invalid extension version name: \"%s\"", versionname),
480 : : errdetail("Version names must not begin or end with \"-\".")));
481 : :
482 : : /*
483 : : * No directory separators either (this is sufficient to prevent ".."
484 : : * style attacks).
485 : : */
486 [ - + ]: 416 : if (first_dir_separator(versionname) != NULL)
487 [ # # ]: 0 : ereport(ERROR,
488 : : (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
489 : : errmsg("invalid extension version name: \"%s\"", versionname),
490 : : errdetail("Version names must not contain directory separator characters.")));
491 : 416 : }
492 : :
493 : : /*
494 : : * Utility functions to handle extension-related path names
495 : : */
496 : : static bool
497 : 31235 : is_extension_control_filename(const char *filename)
498 : : {
499 : 31235 : const char *extension = strrchr(filename, '.');
500 : :
501 [ + - + + ]: 31235 : return (extension != NULL) && (strcmp(extension, ".control") == 0);
502 : : }
503 : :
504 : : static bool
505 : 342828 : is_extension_script_filename(const char *filename)
506 : : {
507 : 342828 : const char *extension = strrchr(filename, '.');
508 : :
509 [ + - + + ]: 342828 : return (extension != NULL) && (strcmp(extension, ".sql") == 0);
510 : : }
511 : :
512 : : /*
513 : : * Return a list of directories declared in the extension_control_path GUC.
514 : : */
515 : : static List *
516 : 505 : get_extension_control_directories(void)
517 : : {
518 : : #define EXTENSION_SYSTEM_MACRO "$system"
519 : : char sharepath[MAXPGPATH];
520 : : char *system_dir;
521 : : char *ecp;
522 : 505 : List *paths = NIL;
523 : :
524 : 505 : get_share_path(my_exec_path, sharepath);
525 : :
526 : 505 : system_dir = psprintf("%s/extension", sharepath);
527 : :
528 [ + + ]: 505 : if (strlen(Extension_control_path) == 0)
529 : : {
530 : 1 : ExtensionLocation *location = palloc_object(ExtensionLocation);
531 : :
532 : 1 : location->macro = pstrdup(EXTENSION_SYSTEM_MACRO);
533 : 1 : location->loc = system_dir;
534 : 1 : paths = lappend(paths, location);
535 : : }
536 : : else
537 : : {
538 : : /* Duplicate the string so we can modify it */
539 : 504 : ecp = pstrdup(Extension_control_path);
540 : :
541 : : for (;;)
542 : 23 : {
543 : : int len;
544 : : char *mangled;
545 : 527 : char *piece = first_path_var_separator(ecp);
546 : 527 : ExtensionLocation *location = palloc_object(ExtensionLocation);
547 : :
548 : : /* Get the length of the next path on ecp */
549 [ + + ]: 527 : if (piece == NULL)
550 : 504 : len = strlen(ecp);
551 : : else
552 : 23 : len = piece - ecp;
553 : :
554 : : /* Copy the next path found on ecp */
555 : 527 : piece = palloc(len + 1);
556 : 527 : strlcpy(piece, ecp, len + 1);
557 : :
558 : : /*
559 : : * Substitute the path macro if needed or append "extension"
560 : : * suffix if it is a custom extension control path.
561 : : */
562 [ + + ]: 527 : if (strcmp(piece, EXTENSION_SYSTEM_MACRO) == 0)
563 : : {
564 : 504 : location->macro = pstrdup(piece);
565 : 504 : mangled = substitute_path_macro(piece, EXTENSION_SYSTEM_MACRO, system_dir);
566 : : }
567 : : else
568 : : {
569 : 23 : location->macro = NULL;
570 : 23 : mangled = psprintf("%s/extension", piece);
571 : : }
572 : 527 : pfree(piece);
573 : :
574 : : /* Canonicalize the path based on the OS and add to the list */
575 : 527 : canonicalize_path(mangled);
576 : 527 : location->loc = mangled;
577 : 527 : paths = lappend(paths, location);
578 : :
579 : : /* Break if ecp is empty or move to the next path on ecp */
580 [ + + ]: 527 : if (ecp[len] == '\0')
581 : 504 : break;
582 : : else
583 : 23 : ecp += len + 1;
584 : : }
585 : : }
586 : :
587 : 505 : return paths;
588 : : #undef EXTENSION_SYSTEM_MACRO
589 : : }
590 : :
591 : : /*
592 : : * Find control file for extension with name in control->name, looking in
593 : : * available paths. Return the full file name, or NULL if not found.
594 : : * If found, the directory is recorded in control->control_dir.
595 : : */
596 : : static char *
597 : 421 : find_extension_control_filename(ExtensionControlFile *control)
598 : : {
599 : : char *basename;
600 : : char *result;
601 : : List *paths;
602 : :
603 : : Assert(control->name);
604 : :
605 : 421 : basename = psprintf("%s.control", control->name);
606 : :
607 : 421 : paths = get_extension_control_directories();
608 : 421 : result = find_in_paths(basename, paths);
609 : :
610 [ + + ]: 421 : if (result)
611 : : {
612 : : const char *p;
613 : :
614 : 420 : p = strrchr(result, '/');
615 : : Assert(p);
616 : 420 : control->control_dir = pnstrdup(result, p - result);
617 : : }
618 : :
619 : 421 : return result;
620 : : }
621 : :
622 : : static char *
623 : 4088 : get_extension_script_directory(ExtensionControlFile *control)
624 : : {
625 : : /*
626 : : * The directory parameter can be omitted, absolute, or relative to the
627 : : * installation's base directory, which can be the sharedir or a custom
628 : : * path that was set via extension_control_path. It depends on where the
629 : : * .control file was found.
630 : : */
631 [ + + ]: 4088 : if (!control->directory)
632 : 4079 : return pstrdup(control->control_dir);
633 : :
634 [ - + ]: 9 : if (is_absolute_path(control->directory))
635 : 0 : return pstrdup(control->directory);
636 : :
637 : : Assert(control->basedir != NULL);
638 : 9 : return psprintf("%s/%s", control->basedir, control->directory);
639 : : }
640 : :
641 : : static char *
642 : 2062 : get_extension_aux_control_filename(ExtensionControlFile *control,
643 : : const char *version)
644 : : {
645 : : char *result;
646 : : char *scriptdir;
647 : :
648 : 2062 : scriptdir = get_extension_script_directory(control);
649 : :
650 : 2062 : result = (char *) palloc(MAXPGPATH);
651 : 2062 : snprintf(result, MAXPGPATH, "%s/%s--%s.control",
652 : : scriptdir, control->name, version);
653 : :
654 : 2062 : pfree(scriptdir);
655 : :
656 : 2062 : return result;
657 : : }
658 : :
659 : : static char *
660 : 1096 : get_extension_script_filename(ExtensionControlFile *control,
661 : : const char *from_version, const char *version)
662 : : {
663 : : char *result;
664 : : char *scriptdir;
665 : :
666 : 1096 : scriptdir = get_extension_script_directory(control);
667 : :
668 : 1096 : result = (char *) palloc(MAXPGPATH);
669 [ + + ]: 1096 : if (from_version)
670 : 316 : snprintf(result, MAXPGPATH, "%s/%s--%s--%s.sql",
671 : : scriptdir, control->name, from_version, version);
672 : : else
673 : 780 : snprintf(result, MAXPGPATH, "%s/%s--%s.sql",
674 : : scriptdir, control->name, version);
675 : :
676 : 1096 : pfree(scriptdir);
677 : :
678 : 1096 : return result;
679 : : }
680 : :
681 : :
682 : : /*
683 : : * Parse contents of primary or auxiliary control file, and fill in
684 : : * fields of *control. We parse primary file if version == NULL,
685 : : * else the optional auxiliary file for that version.
686 : : *
687 : : * If control->control_dir is not NULL, use that to read and parse the
688 : : * control file, otherwise search for the file in extension_control_path.
689 : : *
690 : : * Control files are supposed to be very short, half a dozen lines,
691 : : * so we don't worry about memory allocation risks here. Also we don't
692 : : * worry about what encoding it's in; all values are expected to be ASCII.
693 : : */
694 : : static void
695 : 12411 : parse_extension_control_file(ExtensionControlFile *control,
696 : : const char *version)
697 : : {
698 : : char *filename;
699 : : FILE *file;
700 : : ConfigVariable *item,
701 : 12411 : *head = NULL,
702 : 12411 : *tail = NULL;
703 : :
704 : : /*
705 : : * Locate the file to read. Auxiliary files are optional.
706 : : */
707 [ + + ]: 12411 : if (version)
708 : 2062 : filename = get_extension_aux_control_filename(control, version);
709 : : else
710 : : {
711 : : /*
712 : : * If control_dir is already set, use it, else do a path search.
713 : : */
714 [ + + ]: 10349 : if (control->control_dir)
715 : : {
716 : 9928 : filename = psprintf("%s/%s.control", control->control_dir, control->name);
717 : : }
718 : : else
719 : 421 : filename = find_extension_control_filename(control);
720 : : }
721 : :
722 [ + + ]: 12411 : if (!filename)
723 : : {
724 [ + - ]: 1 : ereport(ERROR,
725 : : (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
726 : : errmsg("extension \"%s\" is not available", control->name),
727 : : errhint("The extension must first be installed on the system where PostgreSQL is running.")));
728 : : }
729 : :
730 : : /* Assert that the control_dir ends with /extension */
731 : : Assert(control->control_dir != NULL);
732 : : Assert(strcmp(control->control_dir + strlen(control->control_dir) - strlen("/extension"), "/extension") == 0);
733 : :
734 : 24820 : control->basedir = pnstrdup(
735 : 12410 : control->control_dir,
736 : 12410 : strlen(control->control_dir) - strlen("/extension"));
737 : :
738 [ + + ]: 12410 : if ((file = AllocateFile(filename, "r")) == NULL)
739 : : {
740 : : /* no complaint for missing auxiliary file */
741 [ + - + - ]: 2062 : if (errno == ENOENT && version)
742 : : {
743 : 2062 : pfree(filename);
744 : 2062 : return;
745 : : }
746 : :
747 [ # # ]: 0 : ereport(ERROR,
748 : : (errcode_for_file_access(),
749 : : errmsg("could not open extension control file \"%s\": %m",
750 : : filename)));
751 : : }
752 : :
753 : : /*
754 : : * Parse the file content, using GUC's file parsing code. We need not
755 : : * check the return value since any errors will be thrown at ERROR level.
756 : : */
757 : 10348 : (void) ParseConfigFp(file, filename, CONF_FILE_START_DEPTH, ERROR,
758 : : &head, &tail);
759 : :
760 : 10348 : FreeFile(file);
761 : :
762 : : /*
763 : : * Convert the ConfigVariable list into ExtensionControlFile entries.
764 : : */
765 [ + + ]: 55244 : for (item = head; item != NULL; item = item->next)
766 : : {
767 [ + + ]: 44896 : if (strcmp(item->name, "directory") == 0)
768 : : {
769 [ - + ]: 8 : if (version)
770 [ # # ]: 0 : ereport(ERROR,
771 : : (errcode(ERRCODE_SYNTAX_ERROR),
772 : : errmsg("parameter \"%s\" cannot be set in a secondary extension control file",
773 : : item->name)));
774 : :
775 : 8 : control->directory = pstrdup(item->value);
776 : : }
777 [ + + ]: 44888 : else if (strcmp(item->name, "default_version") == 0)
778 : : {
779 [ - + ]: 10348 : if (version)
780 [ # # ]: 0 : ereport(ERROR,
781 : : (errcode(ERRCODE_SYNTAX_ERROR),
782 : : errmsg("parameter \"%s\" cannot be set in a secondary extension control file",
783 : : item->name)));
784 : :
785 : 10348 : control->default_version = pstrdup(item->value);
786 : : }
787 [ + + ]: 34540 : else if (strcmp(item->name, "module_pathname") == 0)
788 : : {
789 : 8499 : control->module_pathname = pstrdup(item->value);
790 : : }
791 [ + + ]: 26041 : else if (strcmp(item->name, "comment") == 0)
792 : : {
793 : 10348 : control->comment = pstrdup(item->value);
794 : : }
795 [ + + ]: 15693 : else if (strcmp(item->name, "schema") == 0)
796 : : {
797 : 1015 : control->schema = pstrdup(item->value);
798 : : }
799 [ + + ]: 14678 : else if (strcmp(item->name, "relocatable") == 0)
800 : : {
801 [ - + ]: 10174 : if (!parse_bool(item->value, &control->relocatable))
802 [ # # ]: 0 : ereport(ERROR,
803 : : (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
804 : : errmsg("parameter \"%s\" requires a Boolean value",
805 : : item->name)));
806 : : }
807 [ + + ]: 4504 : else if (strcmp(item->name, "superuser") == 0)
808 : : {
809 [ - + ]: 752 : if (!parse_bool(item->value, &control->superuser))
810 [ # # ]: 0 : ereport(ERROR,
811 : : (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
812 : : errmsg("parameter \"%s\" requires a Boolean value",
813 : : item->name)));
814 : : }
815 [ + + ]: 3752 : else if (strcmp(item->name, "trusted") == 0)
816 : : {
817 [ - + ]: 2206 : if (!parse_bool(item->value, &control->trusted))
818 [ # # ]: 0 : ereport(ERROR,
819 : : (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
820 : : errmsg("parameter \"%s\" requires a Boolean value",
821 : : item->name)));
822 : : }
823 [ - + ]: 1546 : else if (strcmp(item->name, "encoding") == 0)
824 : : {
825 : 0 : control->encoding = pg_valid_server_encoding(item->value);
826 [ # # ]: 0 : if (control->encoding < 0)
827 [ # # ]: 0 : ereport(ERROR,
828 : : (errcode(ERRCODE_UNDEFINED_OBJECT),
829 : : errmsg("\"%s\" is not a valid encoding name",
830 : : item->value)));
831 : : }
832 [ + + ]: 1546 : else if (strcmp(item->name, "requires") == 0)
833 : : {
834 : : /* Need a modifiable copy of string */
835 : 1458 : char *rawnames = pstrdup(item->value);
836 : :
837 : : /* Parse string into list of identifiers */
838 [ - + ]: 1458 : if (!SplitIdentifierString(rawnames, ',', &control->requires))
839 : : {
840 : : /* syntax error in name list */
841 [ # # ]: 0 : ereport(ERROR,
842 : : (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
843 : : errmsg("parameter \"%s\" must be a list of extension names",
844 : : item->name)));
845 : : }
846 : : }
847 [ + - ]: 88 : else if (strcmp(item->name, "no_relocate") == 0)
848 : : {
849 : : /* Need a modifiable copy of string */
850 : 88 : char *rawnames = pstrdup(item->value);
851 : :
852 : : /* Parse string into list of identifiers */
853 [ - + ]: 88 : if (!SplitIdentifierString(rawnames, ',', &control->no_relocate))
854 : : {
855 : : /* syntax error in name list */
856 [ # # ]: 0 : ereport(ERROR,
857 : : (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
858 : : errmsg("parameter \"%s\" must be a list of extension names",
859 : : item->name)));
860 : : }
861 : : }
862 : : else
863 [ # # ]: 0 : ereport(ERROR,
864 : : (errcode(ERRCODE_SYNTAX_ERROR),
865 : : errmsg("unrecognized parameter \"%s\" in file \"%s\"",
866 : : item->name, filename)));
867 : : }
868 : :
869 : 10348 : FreeConfigVariables(head);
870 : :
871 [ + + - + ]: 10348 : if (control->relocatable && control->schema != NULL)
872 [ # # ]: 0 : ereport(ERROR,
873 : : (errcode(ERRCODE_SYNTAX_ERROR),
874 : : errmsg("parameter \"schema\" cannot be specified when \"relocatable\" is true")));
875 : :
876 : 10348 : pfree(filename);
877 : : }
878 : :
879 : : /*
880 : : * Read the primary control file for the specified extension.
881 : : */
882 : : static ExtensionControlFile *
883 : 421 : read_extension_control_file(const char *extname)
884 : : {
885 : 421 : ExtensionControlFile *control = new_ExtensionControlFile(extname);
886 : :
887 : : /*
888 : : * Parse the primary control file.
889 : : */
890 : 421 : parse_extension_control_file(control, NULL);
891 : :
892 : 420 : return control;
893 : : }
894 : :
895 : : /*
896 : : * Read the auxiliary control file for the specified extension and version.
897 : : *
898 : : * Returns a new modified ExtensionControlFile struct; the original struct
899 : : * (reflecting just the primary control file) is not modified.
900 : : */
901 : : static ExtensionControlFile *
902 : 2062 : read_extension_aux_control_file(const ExtensionControlFile *pcontrol,
903 : : const char *version)
904 : : {
905 : : ExtensionControlFile *acontrol;
906 : :
907 : : /*
908 : : * Flat-copy the struct. Pointer fields share values with original.
909 : : */
910 : 2062 : acontrol = palloc_object(ExtensionControlFile);
911 : 2062 : memcpy(acontrol, pcontrol, sizeof(ExtensionControlFile));
912 : :
913 : : /*
914 : : * Parse the auxiliary control file, overwriting struct fields
915 : : */
916 : 2062 : parse_extension_control_file(acontrol, version);
917 : :
918 : 2062 : return acontrol;
919 : : }
920 : :
921 : : /*
922 : : * Read an SQL script file into a string, and convert to database encoding
923 : : */
924 : : static char *
925 : 697 : read_extension_script_file(const ExtensionControlFile *control,
926 : : const char *filename)
927 : : {
928 : : int src_encoding;
929 : : char *src_str;
930 : : char *dest_str;
931 : : int len;
932 : :
933 : 697 : src_str = read_whole_file(filename, &len);
934 : :
935 : : /* use database encoding if not given */
936 [ + - ]: 697 : if (control->encoding < 0)
937 : 697 : src_encoding = GetDatabaseEncoding();
938 : : else
939 : 0 : src_encoding = control->encoding;
940 : :
941 : : /* make sure that source string is valid in the expected encoding */
942 : 697 : (void) pg_verify_mbstr(src_encoding, src_str, len, false);
943 : :
944 : : /*
945 : : * Convert the encoding to the database encoding. read_whole_file
946 : : * null-terminated the string, so if no conversion happens the string is
947 : : * valid as is.
948 : : */
949 : 697 : dest_str = pg_any_to_server(src_str, len, src_encoding);
950 : :
951 : 697 : return dest_str;
952 : : }
953 : :
954 : : /*
955 : : * error context callback for failures in script-file execution
956 : : */
957 : : static void
958 : 146 : script_error_callback(void *arg)
959 : : {
960 : 146 : script_error_callback_arg *callback_arg = (script_error_callback_arg *) arg;
961 : 146 : const char *query = callback_arg->sql;
962 : 146 : int location = callback_arg->stmt_location;
963 : 146 : int len = callback_arg->stmt_len;
964 : : int syntaxerrposition;
965 : : const char *lastslash;
966 : :
967 : : /*
968 : : * If there is a syntax error position, convert to internal syntax error;
969 : : * otherwise report the current query as an item of context stack.
970 : : *
971 : : * Note: we'll provide no context except the filename if there's neither
972 : : * an error position nor any known current query. That shouldn't happen
973 : : * though: all errors reported during raw parsing should come with an
974 : : * error position.
975 : : */
976 : 146 : syntaxerrposition = geterrposition();
977 [ + + ]: 146 : if (syntaxerrposition > 0)
978 : : {
979 : : /*
980 : : * If we do not know the bounds of the current statement (as would
981 : : * happen for an error occurring during initial raw parsing), we have
982 : : * to use a heuristic to decide how much of the script to show. We'll
983 : : * also use the heuristic in the unlikely case that syntaxerrposition
984 : : * is outside what we think the statement bounds are.
985 : : */
986 [ - + - - ]: 1 : if (location < 0 || syntaxerrposition < location ||
987 [ # # # # ]: 0 : (len > 0 && syntaxerrposition > location + len))
988 : : {
989 : : /*
990 : : * Our heuristic is pretty simple: look for semicolon-newline
991 : : * sequences, and break at the last one strictly before
992 : : * syntaxerrposition and the first one strictly after. It's
993 : : * certainly possible to fool this with semicolon-newline embedded
994 : : * in a string literal, but it seems better to do this than to
995 : : * show the entire extension script.
996 : : *
997 : : * Notice we cope with Windows-style newlines (\r\n) regardless of
998 : : * platform. This is because there might be such newlines in
999 : : * script files on other platforms.
1000 : : */
1001 : 1 : int slen = strlen(query);
1002 : :
1003 : 1 : location = len = 0;
1004 [ + - ]: 379 : for (int loc = 0; loc < slen; loc++)
1005 : : {
1006 [ + + ]: 379 : if (query[loc] != ';')
1007 : 377 : continue;
1008 [ - + ]: 2 : if (query[loc + 1] == '\r')
1009 : 0 : loc++;
1010 [ + - ]: 2 : if (query[loc + 1] == '\n')
1011 : : {
1012 : 2 : int bkpt = loc + 2;
1013 : :
1014 [ + + ]: 2 : if (bkpt < syntaxerrposition)
1015 : 1 : location = bkpt;
1016 [ + - ]: 1 : else if (bkpt > syntaxerrposition)
1017 : : {
1018 : 1 : len = bkpt - location;
1019 : 1 : break; /* no need to keep searching */
1020 : : }
1021 : : }
1022 : : }
1023 : : }
1024 : :
1025 : : /* Trim leading/trailing whitespace, for consistency */
1026 : 1 : query = CleanQuerytext(query, &location, &len);
1027 : :
1028 : : /*
1029 : : * Adjust syntaxerrposition. It shouldn't be pointing into the
1030 : : * whitespace we just trimmed, but cope if it is.
1031 : : */
1032 : 1 : syntaxerrposition -= location;
1033 [ - + ]: 1 : if (syntaxerrposition < 0)
1034 : 0 : syntaxerrposition = 0;
1035 [ - + ]: 1 : else if (syntaxerrposition > len)
1036 : 0 : syntaxerrposition = len;
1037 : :
1038 : : /* And report. */
1039 : 1 : errposition(0);
1040 : 1 : internalerrposition(syntaxerrposition);
1041 : 1 : internalerrquery(pnstrdup(query, len));
1042 : : }
1043 [ + - ]: 145 : else if (location >= 0)
1044 : : {
1045 : : /*
1046 : : * Since no syntax cursor will be shown, it's okay and helpful to trim
1047 : : * the reported query string to just the current statement.
1048 : : */
1049 : 145 : query = CleanQuerytext(query, &location, &len);
1050 : 145 : errcontext("SQL statement \"%.*s\"", len, query);
1051 : : }
1052 : :
1053 : : /*
1054 : : * Trim the reported file name to remove the path. We know that
1055 : : * get_extension_script_filename() inserted a '/', regardless of whether
1056 : : * we're on Windows.
1057 : : */
1058 : 146 : lastslash = strrchr(callback_arg->filename, '/');
1059 [ + - ]: 146 : if (lastslash)
1060 : 146 : lastslash++;
1061 : : else
1062 : 0 : lastslash = callback_arg->filename; /* shouldn't happen, but cope */
1063 : :
1064 : : /*
1065 : : * If we have a location (which, as said above, we really always should)
1066 : : * then report a line number to aid in localizing problems in big scripts.
1067 : : */
1068 [ + - ]: 146 : if (location >= 0)
1069 : : {
1070 : 146 : int linenumber = 1;
1071 : :
1072 [ + - ]: 106344 : for (query = callback_arg->sql; *query; query++)
1073 : : {
1074 [ + + ]: 106344 : if (--location < 0)
1075 : 146 : break;
1076 [ + + ]: 106198 : if (*query == '\n')
1077 : 3906 : linenumber++;
1078 : : }
1079 : 146 : errcontext("extension script file \"%s\", near line %d",
1080 : : lastslash, linenumber);
1081 : : }
1082 : : else
1083 : 0 : errcontext("extension script file \"%s\"", lastslash);
1084 : 146 : }
1085 : :
1086 : : /*
1087 : : * Execute given SQL string.
1088 : : *
1089 : : * The filename the string came from is also provided, for error reporting.
1090 : : *
1091 : : * Note: it's tempting to just use SPI to execute the string, but that does
1092 : : * not work very well. The really serious problem is that SPI will parse,
1093 : : * analyze, and plan the whole string before executing any of it; of course
1094 : : * this fails if there are any plannable statements referring to objects
1095 : : * created earlier in the script. A lesser annoyance is that SPI insists
1096 : : * on printing the whole string as errcontext in case of any error, and that
1097 : : * could be very long.
1098 : : */
1099 : : static void
1100 : 688 : execute_sql_string(const char *sql, const char *filename)
1101 : : {
1102 : : script_error_callback_arg callback_arg;
1103 : : ErrorContextCallback scripterrcontext;
1104 : : List *raw_parsetree_list;
1105 : : DestReceiver *dest;
1106 : : ListCell *lc1;
1107 : :
1108 : : /*
1109 : : * Setup error traceback support for ereport().
1110 : : */
1111 : 688 : callback_arg.sql = sql;
1112 : 688 : callback_arg.filename = filename;
1113 : 688 : callback_arg.stmt_location = -1;
1114 : 688 : callback_arg.stmt_len = -1;
1115 : :
1116 : 688 : scripterrcontext.callback = script_error_callback;
1117 : 688 : scripterrcontext.arg = &callback_arg;
1118 : 688 : scripterrcontext.previous = error_context_stack;
1119 : 688 : error_context_stack = &scripterrcontext;
1120 : :
1121 : : /*
1122 : : * Parse the SQL string into a list of raw parse trees.
1123 : : */
1124 : 688 : raw_parsetree_list = pg_parse_query(sql);
1125 : :
1126 : : /* All output from SELECTs goes to the bit bucket */
1127 : 687 : dest = CreateDestReceiver(DestNone);
1128 : :
1129 : : /*
1130 : : * Do parse analysis, rule rewrite, planning, and execution for each raw
1131 : : * parsetree. We must fully execute each query before beginning parse
1132 : : * analysis on the next one, since there may be interdependencies.
1133 : : */
1134 [ + + + + : 7959 : foreach(lc1, raw_parsetree_list)
+ + ]
1135 : : {
1136 : 7284 : RawStmt *parsetree = lfirst_node(RawStmt, lc1);
1137 : : MemoryContext per_parsetree_context,
1138 : : oldcontext;
1139 : : List *stmt_list;
1140 : : ListCell *lc2;
1141 : :
1142 : : /* Report location of this query for error context callback */
1143 : 7284 : callback_arg.stmt_location = parsetree->stmt_location;
1144 : 7284 : callback_arg.stmt_len = parsetree->stmt_len;
1145 : :
1146 : : /*
1147 : : * We do the work for each parsetree in a short-lived context, to
1148 : : * limit the memory used when there are many commands in the string.
1149 : : */
1150 : : per_parsetree_context =
1151 : 7284 : AllocSetContextCreate(CurrentMemoryContext,
1152 : : "execute_sql_string per-statement context",
1153 : : ALLOCSET_DEFAULT_SIZES);
1154 : 7284 : oldcontext = MemoryContextSwitchTo(per_parsetree_context);
1155 : :
1156 : : /* Be sure parser can see any DDL done so far */
1157 : 7284 : CommandCounterIncrement();
1158 : :
1159 : 7284 : stmt_list = pg_analyze_and_rewrite_fixedparams(parsetree,
1160 : : sql,
1161 : : NULL,
1162 : : 0,
1163 : : NULL);
1164 : 7284 : stmt_list = pg_plan_queries(stmt_list, sql, CURSOR_OPT_PARALLEL_OK, NULL);
1165 : :
1166 [ + - + + : 14556 : foreach(lc2, stmt_list)
+ + ]
1167 : : {
1168 : 7284 : PlannedStmt *stmt = lfirst_node(PlannedStmt, lc2);
1169 : :
1170 : 7284 : CommandCounterIncrement();
1171 : :
1172 : 7284 : PushActiveSnapshot(GetTransactionSnapshot());
1173 : :
1174 [ + + ]: 7284 : if (stmt->utilityStmt == NULL)
1175 : : {
1176 : : QueryDesc *qdesc;
1177 : :
1178 : 8 : qdesc = CreateQueryDesc(stmt,
1179 : : sql,
1180 : : GetActiveSnapshot(), NULL,
1181 : : dest, NULL, NULL, 0);
1182 : :
1183 : 8 : ExecutorStart(qdesc, 0);
1184 : 8 : ExecutorRun(qdesc, ForwardScanDirection, 0);
1185 : 8 : ExecutorFinish(qdesc);
1186 : 8 : ExecutorEnd(qdesc);
1187 : :
1188 : 8 : FreeQueryDesc(qdesc);
1189 : : }
1190 : : else
1191 : : {
1192 [ - + ]: 7276 : if (IsA(stmt->utilityStmt, TransactionStmt))
1193 [ # # ]: 0 : ereport(ERROR,
1194 : : (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1195 : : errmsg("transaction control statements are not allowed within an extension script")));
1196 : :
1197 : 7276 : ProcessUtility(stmt,
1198 : : sql,
1199 : : false,
1200 : : PROCESS_UTILITY_QUERY,
1201 : : NULL,
1202 : : NULL,
1203 : : dest,
1204 : : NULL);
1205 : : }
1206 : :
1207 : 7272 : PopActiveSnapshot();
1208 : : }
1209 : :
1210 : : /* Clean up per-parsetree context. */
1211 : 7272 : MemoryContextSwitchTo(oldcontext);
1212 : 7272 : MemoryContextDelete(per_parsetree_context);
1213 : : }
1214 : :
1215 : 675 : error_context_stack = scripterrcontext.previous;
1216 : :
1217 : : /* Be sure to advance the command counter after the last script command */
1218 : 675 : CommandCounterIncrement();
1219 : 675 : }
1220 : :
1221 : : /*
1222 : : * Policy function: is the given extension trusted for installation by a
1223 : : * non-superuser?
1224 : : *
1225 : : * (Update the errhint logic below if you change this.)
1226 : : */
1227 : : static bool
1228 : 8 : extension_is_trusted(ExtensionControlFile *control)
1229 : : {
1230 : : AclResult aclresult;
1231 : :
1232 : : /* Never trust unless extension's control file says it's okay */
1233 [ + + ]: 8 : if (!control->trusted)
1234 : 2 : return false;
1235 : : /* Allow if user has CREATE privilege on current database */
1236 : 6 : aclresult = object_aclcheck(DatabaseRelationId, MyDatabaseId, GetUserId(), ACL_CREATE);
1237 [ + + ]: 6 : if (aclresult == ACLCHECK_OK)
1238 : 5 : return true;
1239 : 1 : return false;
1240 : : }
1241 : :
1242 : : #ifdef USE_ASSERT_CHECKING
1243 : : /* Like CheckRelationLockedByMe(), but for pg_namespace */
1244 : : static bool
1245 : : CheckNamespaceLockedByMe(Oid schemaOid, LOCKMODE lockmode, bool orstronger)
1246 : : {
1247 : : LOCKTAG tag;
1248 : :
1249 : : SET_LOCKTAG_OBJECT(tag, MyDatabaseId, NamespaceRelationId, schemaOid, 0);
1250 : :
1251 : : return LockHeldByMe(&tag, lockmode, orstronger);
1252 : : }
1253 : : #endif
1254 : :
1255 : : /*
1256 : : * Block operations that would put a temporary-table namespace (defined per
1257 : : * isAnyTempNamespace()) in search_path. Extension scripts assume they can
1258 : : * create a function and find it via search_path, but creating in a temp
1259 : : * namespace stifles that.
1260 : : *
1261 : : * Block operations that would otherwise put "$user" in search_path as though
1262 : : * that resolved to the schema having nspname='$user'. More generally, block
1263 : : * any name that is special to the search_path interpreter. Checking
1264 : : * "pg_"-prefixed special names is not obligatory, because such schemas won't
1265 : : * exist without allow_system_table_mods intervention.
1266 : : */
1267 : : static void
1268 : 726 : extension_search_path_element_check(const char *name)
1269 : : {
1270 [ + + ]: 726 : if (strncmp(name, "pg_temp_", 8) == 0 ||
1271 [ + - ]: 725 : strncmp(name, "pg_toast_temp_", 14) == 0 ||
1272 [ + - ]: 725 : strcmp(name, "pg_temp") == 0 ||
1273 [ + + ]: 725 : strcmp(name, "$user") == 0)
1274 [ + - ]: 3 : ereport(ERROR,
1275 : : (errcode(ERRCODE_RESERVED_NAME),
1276 : : errmsg("unacceptable extension schema name \"%s\"",
1277 : : name)));
1278 : 723 : }
1279 : :
1280 : : /*
1281 : : * Check that a name is safe to substitute into an extension script.
1282 : : *
1283 : : * We filter each substitution through quote_identifier(), but names
1284 : : * containing quote characters, comment delimiters, or substitution tokens
1285 : : * could still achieve SQL injection. To avoid a security snare for
1286 : : * extension authors, error on substitution for names containing these.
1287 : : * extname is the extension whose schema name is being substituted, or NULL
1288 : : * when substituting the owner name.
1289 : : */
1290 : : static void
1291 : 89 : check_substitution_name(const char *name, const char *extname)
1292 : : {
1293 : 89 : const char *quoting_relevant_chars = "\"$'\\";
1294 : :
1295 [ + + ]: 89 : if (strpbrk(name, quoting_relevant_chars) != NULL)
1296 : : {
1297 [ + - ]: 2 : if (extname != NULL)
1298 [ + - ]: 2 : ereport(ERROR,
1299 : : (errcode(ERRCODE_INVALID_TEXT_REPRESENTATION),
1300 : : errmsg("invalid character in extension \"%s\" schema: must not contain any of \"%s\"",
1301 : : extname, quoting_relevant_chars)));
1302 : : else
1303 [ # # ]: 0 : ereport(ERROR,
1304 : : (errcode(ERRCODE_INVALID_TEXT_REPRESENTATION),
1305 : : errmsg("invalid character in extension owner: must not contain any of \"%s\"",
1306 : : quoting_relevant_chars)));
1307 : : }
1308 : :
1309 [ + + ]: 87 : if (strpbrk(name, "\n\r") != NULL ||
1310 [ + + ]: 86 : strstr(name, "--") != NULL ||
1311 [ + + ]: 85 : strstr(name, "/*") != NULL ||
1312 [ + + ]: 84 : strstr(name, "*/") != NULL)
1313 : : {
1314 [ + - ]: 4 : if (extname != NULL)
1315 [ + - ]: 4 : ereport(ERROR,
1316 : : (errcode(ERRCODE_INVALID_TEXT_REPRESENTATION),
1317 : : errmsg("invalid string in extension \"%s\" schema: must not contain newline, carriage return, \"--\", \"/*\", or \"*/\"",
1318 : : extname)));
1319 : : else
1320 [ # # ]: 0 : ereport(ERROR,
1321 : : (errcode(ERRCODE_INVALID_TEXT_REPRESENTATION),
1322 : : errmsg("invalid string in extension owner: must not contain newline, carriage return, \"--\", \"/*\", or \"*/\"")));
1323 : : }
1324 : :
1325 [ + + ]: 83 : if (strstr(name, "@extowner@") != NULL ||
1326 [ + + ]: 82 : strstr(name, "@extschema") != NULL ||
1327 [ + + ]: 81 : strstr(name, "MODULE_PATHNAME") != NULL)
1328 : : {
1329 [ + - ]: 3 : if (extname != NULL)
1330 [ + - ]: 3 : ereport(ERROR,
1331 : : (errcode(ERRCODE_INVALID_TEXT_REPRESENTATION),
1332 : : errmsg("invalid string in extension \"%s\" schema: must not contain \"@extowner@\", \"@extschema\", or \"MODULE_PATHNAME\"",
1333 : : extname)));
1334 : : else
1335 [ # # ]: 0 : ereport(ERROR,
1336 : : (errcode(ERRCODE_INVALID_TEXT_REPRESENTATION),
1337 : : errmsg("invalid string in extension owner: must not contain \"@extowner@\", \"@extschema\", or \"MODULE_PATHNAME\"")));
1338 : : }
1339 : 80 : }
1340 : :
1341 : : /*
1342 : : * Execute the appropriate script file for installing or updating the extension
1343 : : *
1344 : : * If from_version isn't NULL, it's an update
1345 : : *
1346 : : * Note: requiredSchemas must be one-for-one with the control->requires list
1347 : : */
1348 : : static void
1349 : 703 : execute_extension_script(Oid extensionOid, ExtensionControlFile *control,
1350 : : const char *from_version,
1351 : : const char *version,
1352 : : List *requiredSchemas,
1353 : : Oid schemaOid,
1354 : : const char *schemaName)
1355 : : {
1356 : 703 : bool switch_to_superuser = false;
1357 : : char *filename;
1358 : 703 : Oid save_userid = 0;
1359 : 703 : int save_sec_context = 0;
1360 : : int save_nestlevel;
1361 : : StringInfoData pathbuf;
1362 : : ListCell *lc;
1363 : : ListCell *lc2;
1364 : :
1365 : : /*
1366 : : * Enforce superuser-ness if appropriate. We postpone these checks until
1367 : : * here so that the control flags are correctly associated with the right
1368 : : * script(s) if they happen to be set in secondary control files.
1369 : : */
1370 [ + + + + ]: 703 : if (control->superuser && !superuser())
1371 : : {
1372 [ + + ]: 8 : if (extension_is_trusted(control))
1373 : 5 : switch_to_superuser = true;
1374 [ + - ]: 3 : else if (from_version == NULL)
1375 [ + - + + ]: 3 : ereport(ERROR,
1376 : : (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
1377 : : errmsg("permission denied to create extension \"%s\"",
1378 : : control->name),
1379 : : control->trusted
1380 : : ? errhint("Must have CREATE privilege on current database to create this extension.")
1381 : : : errhint("Must be superuser to create this extension.")));
1382 : : else
1383 [ # # # # ]: 0 : ereport(ERROR,
1384 : : (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
1385 : : errmsg("permission denied to update extension \"%s\"",
1386 : : control->name),
1387 : : control->trusted
1388 : : ? errhint("Must have CREATE privilege on current database to update this extension.")
1389 : : : errhint("Must be superuser to update this extension.")));
1390 : : }
1391 : :
1392 : 700 : filename = get_extension_script_filename(control, from_version, version);
1393 : :
1394 [ + + ]: 700 : if (from_version == NULL)
1395 [ + + ]: 384 : elog(DEBUG1, "executing extension script for \"%s\" version '%s'", control->name, version);
1396 : : else
1397 [ + + ]: 316 : elog(DEBUG1, "executing extension script for \"%s\" update from version '%s' to '%s'", control->name, from_version, version);
1398 : :
1399 : : /*
1400 : : * If installing a trusted extension on behalf of a non-superuser, become
1401 : : * the bootstrap superuser. (This switch will be cleaned up automatically
1402 : : * if the transaction aborts, as will the GUC changes below.)
1403 : : */
1404 [ + + ]: 700 : if (switch_to_superuser)
1405 : : {
1406 : 5 : GetUserIdAndSecContext(&save_userid, &save_sec_context);
1407 : 5 : SetUserIdAndSecContext(BOOTSTRAP_SUPERUSERID,
1408 : : save_sec_context | SECURITY_LOCAL_USERID_CHANGE);
1409 : : }
1410 : :
1411 : : /*
1412 : : * Force client_min_messages and log_min_messages to be at least WARNING,
1413 : : * so that we won't spam the user with useless NOTICE messages from common
1414 : : * script actions like creating shell types.
1415 : : *
1416 : : * We use the equivalent of a function SET option to allow the setting to
1417 : : * persist for exactly the duration of the script execution. guc.c also
1418 : : * takes care of undoing the setting on error.
1419 : : *
1420 : : * log_min_messages can't be set by ordinary users, so for that one we
1421 : : * pretend to be superuser.
1422 : : */
1423 : 700 : save_nestlevel = NewGUCNestLevel();
1424 : :
1425 [ + + ]: 700 : if (client_min_messages < WARNING)
1426 : 686 : (void) set_config_option("client_min_messages", "warning",
1427 : : PGC_USERSET, PGC_S_SESSION,
1428 : : GUC_ACTION_SAVE, true, 0, false);
1429 [ + + ]: 700 : if (log_min_messages[MyBackendType] < WARNING)
1430 : 11 : (void) set_config_option_ext("log_min_messages", "warning",
1431 : : PGC_SUSET, PGC_S_SESSION,
1432 : : BOOTSTRAP_SUPERUSERID,
1433 : : GUC_ACTION_SAVE, true, 0, false);
1434 : :
1435 : : /*
1436 : : * Similarly disable check_function_bodies, to ensure that SQL functions
1437 : : * won't be parsed during creation.
1438 : : */
1439 [ + - ]: 700 : if (check_function_bodies)
1440 : 700 : (void) set_config_option("check_function_bodies", "off",
1441 : : PGC_USERSET, PGC_S_SESSION,
1442 : : GUC_ACTION_SAVE, true, 0, false);
1443 : :
1444 : : /*
1445 : : * Set up the search path to have the target schema first, making it be
1446 : : * the default creation target namespace. Then add the schemas of any
1447 : : * prerequisite extensions, unless they are in pg_catalog which would be
1448 : : * searched anyway. (Listing pg_catalog explicitly in a non-first
1449 : : * position would be bad for security.) Finally add pg_temp to ensure
1450 : : * that temp objects can't take precedence over others.
1451 : : *
1452 : : * For trusted extensions, this relies crucially on running inside the
1453 : : * userid switch to superuser. Otherwise, a schema permission check could
1454 : : * cause a schema to silently drop out of the search_path. For an object
1455 : : * the script intended to find in that schema, the script could then find
1456 : : * attacker-controlled substitutes later in this search_path.
1457 : : *
1458 : : * This is an exception to the usual <sect1 id="perm-functions"> standard,
1459 : : * "Remove from search_path any schemas that permit untrusted users to
1460 : : * create objects." These schemas may have any owner and any ACL. To
1461 : : * make that safe, assure a lock on each schema, and expect scripts to
1462 : : * follow <sect2 id="extend-extensions-security">. Without the lock,
1463 : : * concurrent ALTER SCHEMA extschema RENAME could cause commands in the
1464 : : * script to reach the wrong objects.
1465 : : */
1466 : : Assert(CheckNamespaceLockedByMe(schemaOid, AccessShareLock, false));
1467 : 700 : initStringInfo(&pathbuf);
1468 : 700 : extension_search_path_element_check(schemaName);
1469 : 697 : appendStringInfoString(&pathbuf, quote_identifier(schemaName));
1470 [ + + + + : 723 : foreach(lc, requiredSchemas)
+ + ]
1471 : : {
1472 : 26 : Oid reqschema = lfirst_oid(lc);
1473 : : char *reqname;
1474 : :
1475 : : Assert(CheckNamespaceLockedByMe(reqschema, AccessShareLock, false));
1476 : 26 : reqname = get_namespace_name(reqschema);
1477 : :
1478 : : /*
1479 : : * While it can't happen apart from catalog corruption, schema lookup
1480 : : * failure must be a hard failure. Suppose we just ignored missing
1481 : : * schemas. For an object the script intended to find in the schema,
1482 : : * the script could then find attacker-controlled substitutes later in
1483 : : * this search_path.
1484 : : */
1485 [ - + ]: 26 : if (!reqname)
1486 [ # # ]: 0 : elog(ERROR, "cache lookup failed for schema %u", reqschema);
1487 : :
1488 : 26 : extension_search_path_element_check(reqname);
1489 [ + + ]: 26 : if (strcmp(reqname, "pg_catalog") != 0)
1490 : 16 : appendStringInfo(&pathbuf, ", %s", quote_identifier(reqname));
1491 : : }
1492 : 697 : appendStringInfoString(&pathbuf, ", pg_temp");
1493 : :
1494 : 697 : (void) set_config_option("search_path", pathbuf.data,
1495 : : PGC_USERSET, PGC_S_SESSION,
1496 : : GUC_ACTION_SAVE, true, 0, false);
1497 : :
1498 : : /*
1499 : : * Set creating_extension and related variables so that
1500 : : * recordDependencyOnCurrentExtension and other functions do the right
1501 : : * things. On failure, ensure we reset these variables.
1502 : : */
1503 : 697 : creating_extension = true;
1504 : 697 : CurrentExtensionObject = extensionOid;
1505 [ + + ]: 697 : PG_TRY();
1506 : : {
1507 : 697 : char *c_sql = read_extension_script_file(control, filename);
1508 : : Datum t_sql;
1509 : :
1510 : : /* We use various functions that want to operate on text datums */
1511 : 697 : t_sql = CStringGetTextDatum(c_sql);
1512 : :
1513 : : /*
1514 : : * Reduce any lines beginning with "\echo" to empty. This allows
1515 : : * scripts to contain messages telling people not to run them via
1516 : : * psql, which has been found to be necessary due to old habits.
1517 : : */
1518 : 2788 : t_sql = DirectFunctionCall4Coll(textregexreplace,
1519 : : C_COLLATION_OID,
1520 : : t_sql,
1521 : 697 : CStringGetTextDatum("^\\\\echo.*$"),
1522 : 697 : CStringGetTextDatum(""),
1523 : 697 : CStringGetTextDatum("ng"));
1524 : :
1525 : : /*
1526 : : * If the script uses @extowner@, substitute the calling username.
1527 : : */
1528 [ + + ]: 697 : if (strstr(c_sql, "@extowner@"))
1529 : : {
1530 [ + + ]: 67 : Oid uid = switch_to_superuser ? save_userid : GetUserId();
1531 : 67 : const char *userName = GetUserNameFromId(uid, false);
1532 : 67 : const char *qUserName = quote_identifier(userName);
1533 : :
1534 : 201 : t_sql = DirectFunctionCall3Coll(replace_text,
1535 : : C_COLLATION_OID,
1536 : : t_sql,
1537 : 67 : CStringGetTextDatum("@extowner@"),
1538 : 67 : CStringGetTextDatum(qUserName));
1539 : 67 : check_substitution_name(userName, NULL);
1540 : : }
1541 : :
1542 : : /*
1543 : : * If it's not relocatable, substitute the target schema name for
1544 : : * occurrences of @extschema@.
1545 : : *
1546 : : * For a relocatable extension, we needn't do this. There cannot be
1547 : : * any need for @extschema@, else it wouldn't be relocatable.
1548 : : */
1549 [ + + ]: 697 : if (!control->relocatable)
1550 : : {
1551 : 105 : Datum old = t_sql;
1552 : 105 : const char *qSchemaName = quote_identifier(schemaName);
1553 : :
1554 : 315 : t_sql = DirectFunctionCall3Coll(replace_text,
1555 : : C_COLLATION_OID,
1556 : : t_sql,
1557 : 105 : CStringGetTextDatum("@extschema@"),
1558 : 105 : CStringGetTextDatum(qSchemaName));
1559 [ + + ]: 105 : if (t_sql != old)
1560 : 11 : check_substitution_name(schemaName, control->name);
1561 : : }
1562 : :
1563 : : /*
1564 : : * Likewise, substitute required extensions' schema names for
1565 : : * occurrences of @extschema:extension_name@.
1566 : : */
1567 : : Assert(list_length(control->requires) == list_length(requiredSchemas));
1568 [ + + + + : 714 : forboth(lc, control->requires, lc2, requiredSchemas)
+ + + + +
+ + - +
+ ]
1569 : : {
1570 : 26 : Datum old = t_sql;
1571 : 26 : char *reqextname = (char *) lfirst(lc);
1572 : 26 : Oid reqschema = lfirst_oid(lc2);
1573 : 26 : char *reqSchemaName = get_namespace_name(reqschema);
1574 : 26 : const char *qReqSchemaName = quote_identifier(reqSchemaName);
1575 : : char *repltoken;
1576 : :
1577 : 26 : repltoken = psprintf("@extschema:%s@", reqextname);
1578 : 78 : t_sql = DirectFunctionCall3Coll(replace_text,
1579 : : C_COLLATION_OID,
1580 : : t_sql,
1581 : 26 : CStringGetTextDatum(repltoken),
1582 : 26 : CStringGetTextDatum(qReqSchemaName));
1583 [ + + ]: 26 : if (t_sql != old)
1584 : 11 : check_substitution_name(reqSchemaName, reqextname);
1585 : : }
1586 : :
1587 : : /*
1588 : : * If module_pathname was set in the control file, substitute its
1589 : : * value for occurrences of MODULE_PATHNAME.
1590 : : */
1591 [ + + ]: 688 : if (control->module_pathname)
1592 : : {
1593 : 641 : t_sql = DirectFunctionCall3Coll(replace_text,
1594 : : C_COLLATION_OID,
1595 : : t_sql,
1596 : 641 : CStringGetTextDatum("MODULE_PATHNAME"),
1597 : 641 : CStringGetTextDatum(control->module_pathname));
1598 : : }
1599 : :
1600 : : /* And now back to C string */
1601 : 688 : c_sql = text_to_cstring(DatumGetTextPP(t_sql));
1602 : :
1603 : 688 : execute_sql_string(c_sql, filename);
1604 : : }
1605 : 22 : PG_FINALLY();
1606 : : {
1607 : 697 : creating_extension = false;
1608 : 697 : CurrentExtensionObject = InvalidOid;
1609 : : }
1610 [ + + ]: 697 : PG_END_TRY();
1611 : :
1612 : : /*
1613 : : * Restore the GUC variables we set above.
1614 : : */
1615 : 675 : AtEOXact_GUC(true, save_nestlevel);
1616 : :
1617 : : /*
1618 : : * Restore authentication state if needed.
1619 : : */
1620 [ + + ]: 675 : if (switch_to_superuser)
1621 : 5 : SetUserIdAndSecContext(save_userid, save_sec_context);
1622 : 675 : }
1623 : :
1624 : : /*
1625 : : * Find or create an ExtensionVersionInfo for the specified version name
1626 : : *
1627 : : * Currently, we just use a List of the ExtensionVersionInfo's. Searching
1628 : : * for them therefore uses about O(N^2) time when there are N versions of
1629 : : * the extension. We could change the data structure to a hash table if
1630 : : * this ever becomes a bottleneck.
1631 : : */
1632 : : static ExtensionVersionInfo *
1633 : 4124 : get_ext_ver_info(const char *versionname, List **evi_list)
1634 : : {
1635 : : ExtensionVersionInfo *evi;
1636 : : ListCell *lc;
1637 : :
1638 [ + + + + : 16420 : foreach(lc, *evi_list)
+ + ]
1639 : : {
1640 : 13952 : evi = (ExtensionVersionInfo *) lfirst(lc);
1641 [ + + ]: 13952 : if (strcmp(evi->name, versionname) == 0)
1642 : 1656 : return evi;
1643 : : }
1644 : :
1645 : 2468 : evi = palloc_object(ExtensionVersionInfo);
1646 : 2468 : evi->name = pstrdup(versionname);
1647 : 2468 : evi->reachable = NIL;
1648 : 2468 : evi->installable = false;
1649 : : /* initialize for later application of Dijkstra's algorithm */
1650 : 2468 : evi->distance_known = false;
1651 : 2468 : evi->distance = INT_MAX;
1652 : 2468 : evi->previous = NULL;
1653 : :
1654 : 2468 : *evi_list = lappend(*evi_list, evi);
1655 : :
1656 : 2468 : return evi;
1657 : : }
1658 : :
1659 : : /*
1660 : : * Locate the nearest unprocessed ExtensionVersionInfo
1661 : : *
1662 : : * This part of the algorithm is also about O(N^2). A priority queue would
1663 : : * make it much faster, but for now there's no need.
1664 : : */
1665 : : static ExtensionVersionInfo *
1666 : 4238 : get_nearest_unprocessed_vertex(List *evi_list)
1667 : : {
1668 : 4238 : ExtensionVersionInfo *evi = NULL;
1669 : : ListCell *lc;
1670 : :
1671 [ + - + + : 41745 : foreach(lc, evi_list)
+ + ]
1672 : : {
1673 : 37507 : ExtensionVersionInfo *evi2 = (ExtensionVersionInfo *) lfirst(lc);
1674 : :
1675 : : /* only vertices whose distance is still uncertain are candidates */
1676 [ + + ]: 37507 : if (evi2->distance_known)
1677 : 9676 : continue;
1678 : : /* remember the closest such vertex */
1679 [ + + ]: 27831 : if (evi == NULL ||
1680 [ + + ]: 23593 : evi->distance > evi2->distance)
1681 : 6914 : evi = evi2;
1682 : : }
1683 : :
1684 : 4238 : return evi;
1685 : : }
1686 : :
1687 : : /*
1688 : : * Obtain information about the set of update scripts available for the
1689 : : * specified extension. The result is a List of ExtensionVersionInfo
1690 : : * structs, each with a subsidiary list of the ExtensionVersionInfos for
1691 : : * the versions that can be reached in one step from that version.
1692 : : */
1693 : : static List *
1694 : 930 : get_ext_ver_list(ExtensionControlFile *control)
1695 : : {
1696 : 930 : List *evi_list = NIL;
1697 : 930 : int extnamelen = strlen(control->name);
1698 : : char *location;
1699 : : DIR *dir;
1700 : : struct dirent *de;
1701 : :
1702 : 930 : location = get_extension_script_directory(control);
1703 : 930 : dir = AllocateDir(location);
1704 [ + + ]: 343758 : while ((de = ReadDir(dir, location)) != NULL)
1705 : : {
1706 : : char *vername;
1707 : : char *vername2;
1708 : : ExtensionVersionInfo *evi;
1709 : : ExtensionVersionInfo *evi2;
1710 : :
1711 : : /* must be a .sql file ... */
1712 [ + + ]: 342828 : if (!is_extension_script_filename(de->d_name))
1713 : 110898 : continue;
1714 : :
1715 : : /* ... matching extension name followed by separator */
1716 [ + + ]: 231930 : if (strncmp(de->d_name, control->name, extnamelen) != 0 ||
1717 [ + + ]: 2554 : de->d_name[extnamelen] != '-' ||
1718 [ - + ]: 2468 : de->d_name[extnamelen + 1] != '-')
1719 : 229462 : continue;
1720 : :
1721 : : /* extract version name(s) from 'extname--something.sql' filename */
1722 : 2468 : vername = pstrdup(de->d_name + extnamelen + 2);
1723 : 2468 : *strrchr(vername, '.') = '\0';
1724 : 2468 : vername2 = strstr(vername, "--");
1725 [ + + ]: 2468 : if (!vername2)
1726 : : {
1727 : : /* It's an install, not update, script; record its version name */
1728 : 930 : evi = get_ext_ver_info(vername, &evi_list);
1729 : 930 : evi->installable = true;
1730 : 930 : continue;
1731 : : }
1732 : 1538 : *vername2 = '\0'; /* terminate first version */
1733 : 1538 : vername2 += 2; /* and point to second */
1734 : :
1735 : : /* if there's a third --, it's bogus, ignore it */
1736 [ - + ]: 1538 : if (strstr(vername2, "--"))
1737 : 0 : continue;
1738 : :
1739 : : /* Create ExtensionVersionInfos and link them together */
1740 : 1538 : evi = get_ext_ver_info(vername, &evi_list);
1741 : 1538 : evi2 = get_ext_ver_info(vername2, &evi_list);
1742 : 1538 : evi->reachable = lappend(evi->reachable, evi2);
1743 : : }
1744 : 930 : FreeDir(dir);
1745 : :
1746 : 930 : return evi_list;
1747 : : }
1748 : :
1749 : : /*
1750 : : * Given an initial and final version name, identify the sequence of update
1751 : : * scripts that have to be applied to perform that update.
1752 : : *
1753 : : * Result is a List of names of versions to transition through (the initial
1754 : : * version is *not* included).
1755 : : */
1756 : : static List *
1757 : 20 : identify_update_path(ExtensionControlFile *control,
1758 : : const char *oldVersion, const char *newVersion)
1759 : : {
1760 : : List *result;
1761 : : List *evi_list;
1762 : : ExtensionVersionInfo *evi_start;
1763 : : ExtensionVersionInfo *evi_target;
1764 : :
1765 : : /* Extract the version update graph from the script directory */
1766 : 20 : evi_list = get_ext_ver_list(control);
1767 : :
1768 : : /* Initialize start and end vertices */
1769 : 20 : evi_start = get_ext_ver_info(oldVersion, &evi_list);
1770 : 20 : evi_target = get_ext_ver_info(newVersion, &evi_list);
1771 : :
1772 : : /* Find shortest path */
1773 : 20 : result = find_update_path(evi_list, evi_start, evi_target, false, false);
1774 : :
1775 [ - + ]: 20 : if (result == NIL)
1776 [ # # ]: 0 : ereport(ERROR,
1777 : : (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
1778 : : errmsg("extension \"%s\" has no update path from version \"%s\" to version \"%s\"",
1779 : : control->name, oldVersion, newVersion)));
1780 : :
1781 : 20 : return result;
1782 : : }
1783 : :
1784 : : /*
1785 : : * Apply Dijkstra's algorithm to find the shortest path from evi_start to
1786 : : * evi_target.
1787 : : *
1788 : : * If reject_indirect is true, ignore paths that go through installable
1789 : : * versions. This saves work when the caller will consider starting from
1790 : : * all installable versions anyway.
1791 : : *
1792 : : * If reinitialize is false, assume the ExtensionVersionInfo list has not
1793 : : * been used for this before, and the initialization done by get_ext_ver_info
1794 : : * is still good. Otherwise, reinitialize all transient fields used here.
1795 : : *
1796 : : * Result is a List of names of versions to transition through (the initial
1797 : : * version is *not* included). Returns NIL if no such path.
1798 : : */
1799 : : static List *
1800 : 1029 : find_update_path(List *evi_list,
1801 : : ExtensionVersionInfo *evi_start,
1802 : : ExtensionVersionInfo *evi_target,
1803 : : bool reject_indirect,
1804 : : bool reinitialize)
1805 : : {
1806 : : List *result;
1807 : : ExtensionVersionInfo *evi;
1808 : : ListCell *lc;
1809 : :
1810 : : /* Caller error if start == target */
1811 : : Assert(evi_start != evi_target);
1812 : : /* Caller error if reject_indirect and target is installable */
1813 : : Assert(!(reject_indirect && evi_target->installable));
1814 : :
1815 [ + + ]: 1029 : if (reinitialize)
1816 : : {
1817 [ + - + + : 8409 : foreach(lc, evi_list)
+ + ]
1818 : : {
1819 : 7400 : evi = (ExtensionVersionInfo *) lfirst(lc);
1820 : 7400 : evi->distance_known = false;
1821 : 7400 : evi->distance = INT_MAX;
1822 : 7400 : evi->previous = NULL;
1823 : : }
1824 : : }
1825 : :
1826 : 1029 : evi_start->distance = 0;
1827 : :
1828 [ + - ]: 4238 : while ((evi = get_nearest_unprocessed_vertex(evi_list)) != NULL)
1829 : : {
1830 [ + + ]: 4238 : if (evi->distance == INT_MAX)
1831 : 413 : break; /* all remaining vertices are unreachable */
1832 : 3825 : evi->distance_known = true;
1833 [ + + ]: 3825 : if (evi == evi_target)
1834 : 616 : break; /* found shortest path to target */
1835 [ + + + + : 6013 : foreach(lc, evi->reachable)
+ + ]
1836 : : {
1837 : 2804 : ExtensionVersionInfo *evi2 = (ExtensionVersionInfo *) lfirst(lc);
1838 : : int newdist;
1839 : :
1840 : : /* if reject_indirect, treat installable versions as unreachable */
1841 [ + + - + ]: 2804 : if (reject_indirect && evi2->installable)
1842 : 0 : continue;
1843 : 2804 : newdist = evi->distance + 1;
1844 [ + - ]: 2804 : if (newdist < evi2->distance)
1845 : : {
1846 : 2804 : evi2->distance = newdist;
1847 : 2804 : evi2->previous = evi;
1848 : : }
1849 [ # # ]: 0 : else if (newdist == evi2->distance &&
1850 [ # # ]: 0 : evi2->previous != NULL &&
1851 [ # # ]: 0 : strcmp(evi->name, evi2->previous->name) < 0)
1852 : : {
1853 : : /*
1854 : : * Break ties in favor of the version name that comes first
1855 : : * according to strcmp(). This behavior is undocumented and
1856 : : * users shouldn't rely on it. We do it just to ensure that
1857 : : * if there is a tie, the update path that is chosen does not
1858 : : * depend on random factors like the order in which directory
1859 : : * entries get visited.
1860 : : */
1861 : 0 : evi2->previous = evi;
1862 : : }
1863 : : }
1864 : : }
1865 : :
1866 : : /* Return NIL if target is not reachable from start */
1867 [ + + ]: 1029 : if (!evi_target->distance_known)
1868 : 413 : return NIL;
1869 : :
1870 : : /* Build and return list of version names representing the update path */
1871 : 616 : result = NIL;
1872 [ + + ]: 2305 : for (evi = evi_target; evi != evi_start; evi = evi->previous)
1873 : 1689 : result = lcons(evi->name, result);
1874 : :
1875 : 616 : return result;
1876 : : }
1877 : :
1878 : : /*
1879 : : * Given a target version that is not directly installable, find the
1880 : : * best installation sequence starting from a directly-installable version.
1881 : : *
1882 : : * evi_list: previously-collected version update graph
1883 : : * evi_target: member of that list that we want to reach
1884 : : *
1885 : : * Returns the best starting-point version, or NULL if there is none.
1886 : : * On success, *best_path is set to the path from the start point.
1887 : : *
1888 : : * If there's more than one possible start point, prefer shorter update paths,
1889 : : * and break any ties arbitrarily on the basis of strcmp'ing the starting
1890 : : * versions' names.
1891 : : */
1892 : : static ExtensionVersionInfo *
1893 : 1009 : find_install_path(List *evi_list, ExtensionVersionInfo *evi_target,
1894 : : List **best_path)
1895 : : {
1896 : 1009 : ExtensionVersionInfo *evi_start = NULL;
1897 : : ListCell *lc;
1898 : :
1899 : 1009 : *best_path = NIL;
1900 : :
1901 : : /*
1902 : : * We don't expect to be called for an installable target, but if we are,
1903 : : * the answer is easy: just start from there, with an empty update path.
1904 : : */
1905 [ - + ]: 1009 : if (evi_target->installable)
1906 : 0 : return evi_target;
1907 : :
1908 : : /* Consider all installable versions as start points */
1909 [ + - + + : 8409 : foreach(lc, evi_list)
+ + ]
1910 : : {
1911 : 7400 : ExtensionVersionInfo *evi1 = (ExtensionVersionInfo *) lfirst(lc);
1912 : : List *path;
1913 : :
1914 [ + + ]: 7400 : if (!evi1->installable)
1915 : 6391 : continue;
1916 : :
1917 : : /*
1918 : : * Find shortest path from evi1 to evi_target; but no need to consider
1919 : : * paths going through other installable versions.
1920 : : */
1921 : 1009 : path = find_update_path(evi_list, evi1, evi_target, true, true);
1922 [ + + ]: 1009 : if (path == NIL)
1923 : 413 : continue;
1924 : :
1925 : : /* Remember best path */
1926 [ - + - - ]: 596 : if (evi_start == NULL ||
1927 [ # # ]: 0 : list_length(path) < list_length(*best_path) ||
1928 : 0 : (list_length(path) == list_length(*best_path) &&
1929 [ # # ]: 0 : strcmp(evi_start->name, evi1->name) < 0))
1930 : : {
1931 : 596 : evi_start = evi1;
1932 : 596 : *best_path = path;
1933 : : }
1934 : : }
1935 : :
1936 : 1009 : return evi_start;
1937 : : }
1938 : :
1939 : : /*
1940 : : * CREATE EXTENSION worker
1941 : : *
1942 : : * When CASCADE is specified, CreateExtensionInternal() recurses if required
1943 : : * extensions need to be installed. To sanely handle cyclic dependencies,
1944 : : * the "parents" list contains a list of names of extensions already being
1945 : : * installed, allowing us to error out if we recurse to one of those.
1946 : : */
1947 : : static ObjectAddress
1948 : 397 : CreateExtensionInternal(char *extensionName,
1949 : : char *schemaName,
1950 : : const char *versionName,
1951 : : bool cascade,
1952 : : List *parents,
1953 : : bool is_create)
1954 : : {
1955 : 397 : char *origSchemaName = schemaName;
1956 : 397 : Oid schemaOid = InvalidOid;
1957 : 397 : Oid extowner = GetUserId();
1958 : : ExtensionControlFile *pcontrol;
1959 : : ExtensionControlFile *control;
1960 : : char *filename;
1961 : : struct stat fst;
1962 : : List *updateVersions;
1963 : : List *requiredExtensions;
1964 : : List *requiredSchemas;
1965 : : Oid extensionOid;
1966 : : ObjectAddress address;
1967 : : ListCell *lc;
1968 : :
1969 : : /*
1970 : : * Read the primary control file. Note we assume that it does not contain
1971 : : * any non-ASCII data, so there is no need to worry about encoding at this
1972 : : * point.
1973 : : */
1974 : 397 : pcontrol = read_extension_control_file(extensionName);
1975 : :
1976 : : /*
1977 : : * Determine the version to install
1978 : : */
1979 [ + + ]: 396 : if (versionName == NULL)
1980 : : {
1981 [ + - ]: 390 : if (pcontrol->default_version)
1982 : 390 : versionName = pcontrol->default_version;
1983 : : else
1984 [ # # ]: 0 : ereport(ERROR,
1985 : : (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
1986 : : errmsg("version to install must be specified")));
1987 : : }
1988 : 396 : check_valid_version_name(versionName);
1989 : :
1990 : : /*
1991 : : * Figure out which script(s) we need to run to install the desired
1992 : : * version of the extension. If we do not have a script that directly
1993 : : * does what is needed, we try to find a sequence of update scripts that
1994 : : * will get us there.
1995 : : */
1996 : 396 : filename = get_extension_script_filename(pcontrol, NULL, versionName);
1997 [ + + ]: 396 : if (stat(filename, &fst) == 0)
1998 : : {
1999 : : /* Easy, no extra scripts */
2000 : 318 : updateVersions = NIL;
2001 : : }
2002 : : else
2003 : : {
2004 : : /* Look for best way to install this version */
2005 : : List *evi_list;
2006 : : ExtensionVersionInfo *evi_start;
2007 : : ExtensionVersionInfo *evi_target;
2008 : :
2009 : : /* Extract the version update graph from the script directory */
2010 : 78 : evi_list = get_ext_ver_list(pcontrol);
2011 : :
2012 : : /* Identify the target version */
2013 : 78 : evi_target = get_ext_ver_info(versionName, &evi_list);
2014 : :
2015 : : /* Identify best path to reach target */
2016 : 78 : evi_start = find_install_path(evi_list, evi_target,
2017 : : &updateVersions);
2018 : :
2019 : : /* Fail if no path ... */
2020 [ - + ]: 78 : if (evi_start == NULL)
2021 [ # # ]: 0 : ereport(ERROR,
2022 : : (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
2023 : : errmsg("extension \"%s\" has no installation script nor update path for version \"%s\"",
2024 : : pcontrol->name, versionName)));
2025 : :
2026 : : /* Otherwise, install best starting point and then upgrade */
2027 : 78 : versionName = evi_start->name;
2028 : : }
2029 : :
2030 : : /*
2031 : : * Fetch control parameters for installation target version
2032 : : */
2033 : 396 : control = read_extension_aux_control_file(pcontrol, versionName);
2034 : :
2035 : : /*
2036 : : * Determine the target schema to install the extension into
2037 : : */
2038 [ + + ]: 396 : if (schemaName)
2039 : : {
2040 : : ObjectAddress schemaAddress;
2041 : :
2042 : : /* If the user is giving us the schema name, it must exist already. */
2043 : 37 : schemaAddress = get_object_address(OBJECT_SCHEMA,
2044 : 37 : (Node *) makeString(schemaName),
2045 : : NULL, AccessShareLock, false);
2046 : 35 : schemaOid = schemaAddress.objectId;
2047 : : }
2048 : :
2049 [ + + ]: 394 : if (control->schema != NULL)
2050 : : {
2051 : : ObjectAddress schemaAddress;
2052 : :
2053 : : /*
2054 : : * The extension is not relocatable and the author gave us a schema
2055 : : * for it.
2056 : : *
2057 : : * Unless CASCADE parameter was given, it's an error to give a schema
2058 : : * different from control->schema if control->schema is specified.
2059 : : */
2060 [ + + + - ]: 86 : if (schemaName && strcmp(control->schema, schemaName) != 0 &&
2061 [ + + ]: 2 : !cascade)
2062 [ + - ]: 1 : ereport(ERROR,
2063 : : (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2064 : : errmsg("extension \"%s\" must be installed in schema \"%s\"",
2065 : : control->name,
2066 : : control->schema)));
2067 : :
2068 : : /* Always use the schema from control file for current extension. */
2069 : 85 : schemaName = control->schema;
2070 : :
2071 : : /* Find or create the schema in case it does not exist. */
2072 : 85 : schemaAddress = get_object_address(OBJECT_SCHEMA,
2073 : 85 : (Node *) makeString(schemaName),
2074 : : NULL, AccessShareLock, true);
2075 : 85 : schemaOid = schemaAddress.objectId;
2076 : :
2077 [ + + ]: 85 : if (!OidIsValid(schemaOid))
2078 : : {
2079 : 3 : ParseState *pstate = make_parsestate(NULL);
2080 : 3 : CreateSchemaStmt *csstmt = makeNode(CreateSchemaStmt);
2081 : :
2082 : 3 : pstate->p_sourcetext = "(generated CREATE SCHEMA command)";
2083 : :
2084 : 3 : csstmt->schemaname = schemaName;
2085 : 3 : csstmt->authrole = NULL; /* will be created by current user */
2086 : 3 : csstmt->schemaElts = NIL;
2087 : 3 : csstmt->if_not_exists = false;
2088 : :
2089 : 3 : CreateSchemaCommand(pstate, csstmt, -1, -1);
2090 : :
2091 : : /*
2092 : : * CreateSchemaCommand includes CommandCounterIncrement, so new
2093 : : * schema is now visible.
2094 : : */
2095 : : schemaAddress =
2096 : 3 : get_object_address(OBJECT_SCHEMA,
2097 : 3 : (Node *) makeString(schemaName),
2098 : : NULL, AccessShareLock, false);
2099 : 3 : schemaOid = schemaAddress.objectId;
2100 : : }
2101 : : }
2102 [ + + ]: 308 : else if (!OidIsValid(schemaOid))
2103 : : {
2104 : : /*
2105 : : * Neither user nor author of the extension specified schema; use the
2106 : : * current default creation namespace, which is the first explicit
2107 : : * entry in the search_path.
2108 : : */
2109 : 275 : List *search_path = fetch_search_path(false);
2110 : :
2111 [ - + ]: 275 : if (search_path == NIL) /* nothing valid in search_path? */
2112 [ # # ]: 0 : ereport(ERROR,
2113 : : (errcode(ERRCODE_UNDEFINED_SCHEMA),
2114 : : errmsg("no schema has been selected to create in")));
2115 : 275 : schemaOid = linitial_oid(search_path);
2116 : 275 : LockDatabaseObject(NamespaceRelationId, schemaOid, 0,
2117 : : AccessShareLock);
2118 : 275 : schemaName = get_namespace_name(schemaOid);
2119 [ - + ]: 275 : if (schemaName == NULL) /* recently-deleted namespace? */
2120 [ # # ]: 0 : ereport(ERROR,
2121 : : (errcode(ERRCODE_UNDEFINED_SCHEMA),
2122 : : errmsg("no schema has been selected to create in")));
2123 : :
2124 : 275 : list_free(search_path);
2125 : : }
2126 : :
2127 : : /*
2128 : : * We don't check creation rights on the target namespace here. If the
2129 : : * extension script actually creates any objects there, it will fail if
2130 : : * the user doesn't have such permissions. But there are cases such as
2131 : : * procedural languages where it's convenient to set schema = pg_catalog
2132 : : * yet we don't want to restrict the command to users with ACL_CREATE for
2133 : : * pg_catalog.
2134 : : */
2135 : :
2136 : : /*
2137 : : * Look up the prerequisite extensions, install them if necessary, and
2138 : : * build lists of their OIDs and the OIDs of their target schemas.
2139 : : */
2140 : 393 : requiredExtensions = NIL;
2141 : 393 : requiredSchemas = NIL;
2142 [ + + + + : 419 : foreach(lc, control->requires)
+ + ]
2143 : : {
2144 : 32 : char *curreq = (char *) lfirst(lc);
2145 : : Oid reqext;
2146 : : Oid reqschema;
2147 : :
2148 : 32 : reqext = get_required_extension(curreq,
2149 : : extensionName,
2150 : : origSchemaName,
2151 : : cascade,
2152 : : parents,
2153 : : is_create);
2154 : 26 : reqschema = get_extension_schema(reqext);
2155 : 26 : LockDatabaseObject(NamespaceRelationId, reqschema, 0,
2156 : : AccessShareLock);
2157 : 26 : requiredExtensions = lappend_oid(requiredExtensions, reqext);
2158 : 26 : requiredSchemas = lappend_oid(requiredSchemas, reqschema);
2159 : : }
2160 : :
2161 : : /*
2162 : : * Insert new tuple into pg_extension, and create dependency entries.
2163 : : */
2164 : 387 : address = InsertExtensionTuple(control->name, extowner,
2165 : 387 : schemaOid, control->relocatable,
2166 : : versionName,
2167 : : PointerGetDatum(NULL),
2168 : : PointerGetDatum(NULL),
2169 : : requiredExtensions);
2170 : 387 : extensionOid = address.objectId;
2171 : :
2172 : : /*
2173 : : * Apply any control-file comment on extension
2174 : : */
2175 [ + - ]: 387 : if (control->comment != NULL)
2176 : 387 : CreateComments(extensionOid, ExtensionRelationId, 0, control->comment);
2177 : :
2178 : : /*
2179 : : * Execute the installation script file
2180 : : */
2181 : 387 : execute_extension_script(extensionOid, control,
2182 : : NULL, versionName,
2183 : : requiredSchemas,
2184 : : schemaOid, schemaName);
2185 : :
2186 : : /*
2187 : : * If additional update scripts have to be executed, apply the updates as
2188 : : * though a series of ALTER EXTENSION UPDATE commands were given
2189 : : */
2190 : 362 : ApplyExtensionUpdates(extensionOid, pcontrol,
2191 : : versionName, updateVersions,
2192 : : origSchemaName, cascade, is_create);
2193 : :
2194 : : Assert(!isTempNamespace(schemaOid)); /* expect earlier failure */
2195 : :
2196 : 362 : return address;
2197 : : }
2198 : :
2199 : : /*
2200 : : * Get the OID of an extension listed in "requires", possibly creating it.
2201 : : */
2202 : : static Oid
2203 : 33 : get_required_extension(char *reqExtensionName,
2204 : : char *extensionName,
2205 : : char *origSchemaName,
2206 : : bool cascade,
2207 : : List *parents,
2208 : : bool is_create)
2209 : : {
2210 : : ObjectAddress address;
2211 : : Oid reqExtensionOid;
2212 : :
2213 : : /* Block concurrent ALTER EXTENSION UPDATE */
2214 : 33 : address = get_object_address(OBJECT_EXTENSION,
2215 : 33 : (Node *) makeString(reqExtensionName),
2216 : : NULL, ShareUpdateExclusiveLock, true);
2217 : 33 : reqExtensionOid = address.objectId;
2218 [ + + ]: 33 : if (!OidIsValid(reqExtensionOid))
2219 : : {
2220 [ + + ]: 22 : if (cascade)
2221 : : {
2222 : : /* Must install it. */
2223 : : ObjectAddress addr;
2224 : : List *cascade_parents;
2225 : : ListCell *lc;
2226 : :
2227 : : /* Check extension name validity before trying to cascade. */
2228 : 20 : check_valid_extension_name(reqExtensionName);
2229 : :
2230 : : /* Check for cyclic dependency between extensions. */
2231 [ + + + + : 22 : foreach(lc, parents)
+ + ]
2232 : : {
2233 : 3 : char *pname = (char *) lfirst(lc);
2234 : :
2235 [ + + ]: 3 : if (strcmp(pname, reqExtensionName) == 0)
2236 [ + - ]: 1 : ereport(ERROR,
2237 : : (errcode(ERRCODE_INVALID_RECURSION),
2238 : : errmsg("cyclic dependency detected between extensions \"%s\" and \"%s\"",
2239 : : reqExtensionName, extensionName)));
2240 : : }
2241 : :
2242 [ + - ]: 19 : ereport(NOTICE,
2243 : : (errmsg("installing required extension \"%s\"",
2244 : : reqExtensionName)));
2245 : :
2246 : : /* Add current extension to list of parents to pass down. */
2247 : 19 : cascade_parents = lappend(list_copy(parents), extensionName);
2248 : :
2249 : : /*
2250 : : * Create the required extension. We propagate the SCHEMA option
2251 : : * if any, and CASCADE, but no other options.
2252 : : */
2253 : 19 : addr = CreateExtensionInternal(reqExtensionName,
2254 : : origSchemaName,
2255 : : NULL,
2256 : : cascade,
2257 : : cascade_parents,
2258 : : is_create);
2259 : :
2260 : : /* Get its newly-assigned OID. */
2261 : 16 : reqExtensionOid = addr.objectId;
2262 : : }
2263 : : else
2264 [ + - + - ]: 2 : ereport(ERROR,
2265 : : (errcode(ERRCODE_UNDEFINED_OBJECT),
2266 : : errmsg("required extension \"%s\" is not installed",
2267 : : reqExtensionName),
2268 : : is_create ?
2269 : : errhint("Use CREATE EXTENSION ... CASCADE to install required extensions too.") : 0));
2270 : : }
2271 : :
2272 : 27 : return reqExtensionOid;
2273 : : }
2274 : :
2275 : : /*
2276 : : * CREATE EXTENSION
2277 : : */
2278 : : ObjectAddress
2279 : 381 : CreateExtension(ParseState *pstate, CreateExtensionStmt *stmt)
2280 : : {
2281 : 381 : DefElem *d_schema = NULL;
2282 : 381 : DefElem *d_new_version = NULL;
2283 : 381 : DefElem *d_cascade = NULL;
2284 : 381 : char *schemaName = NULL;
2285 : 381 : char *versionName = NULL;
2286 : 381 : bool cascade = false;
2287 : : ListCell *lc;
2288 : :
2289 : : /* Check extension name validity before any filesystem access */
2290 : 381 : check_valid_extension_name(stmt->extname);
2291 : :
2292 : : /*
2293 : : * Check for duplicate extension name. The unique index on
2294 : : * pg_extension.extname would catch this anyway, and serves as a backstop
2295 : : * in case of race conditions; but this is a friendlier error message, and
2296 : : * besides we need a check to support IF NOT EXISTS.
2297 : : */
2298 [ + + ]: 381 : if (get_extension_oid(stmt->extname, true) != InvalidOid)
2299 : : {
2300 [ + - ]: 3 : if (stmt->if_not_exists)
2301 : : {
2302 [ + - ]: 3 : ereport(NOTICE,
2303 : : (errcode(ERRCODE_DUPLICATE_OBJECT),
2304 : : errmsg("extension \"%s\" already exists, skipping",
2305 : : stmt->extname)));
2306 : 3 : return InvalidObjectAddress;
2307 : : }
2308 : : else
2309 [ # # ]: 0 : ereport(ERROR,
2310 : : (errcode(ERRCODE_DUPLICATE_OBJECT),
2311 : : errmsg("extension \"%s\" already exists",
2312 : : stmt->extname)));
2313 : : }
2314 : :
2315 : : /*
2316 : : * We use global variables to track the extension being created, so we can
2317 : : * create only one extension at the same time.
2318 : : */
2319 [ - + ]: 378 : if (creating_extension)
2320 [ # # ]: 0 : ereport(ERROR,
2321 : : (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2322 : : errmsg("nested CREATE EXTENSION is not supported")));
2323 : :
2324 : : /* Deconstruct the statement option list */
2325 [ + + + + : 436 : foreach(lc, stmt->options)
+ + ]
2326 : : {
2327 : 58 : DefElem *defel = (DefElem *) lfirst(lc);
2328 : :
2329 [ + + ]: 58 : if (strcmp(defel->defname, "schema") == 0)
2330 : : {
2331 [ - + ]: 32 : if (d_schema)
2332 : 0 : errorConflictingDefElem(defel, pstate);
2333 : 32 : d_schema = defel;
2334 : 32 : schemaName = defGetString(d_schema);
2335 : : }
2336 [ + + ]: 26 : else if (strcmp(defel->defname, "new_version") == 0)
2337 : : {
2338 [ - + ]: 6 : if (d_new_version)
2339 : 0 : errorConflictingDefElem(defel, pstate);
2340 : 6 : d_new_version = defel;
2341 : 6 : versionName = defGetString(d_new_version);
2342 : : }
2343 [ + - ]: 20 : else if (strcmp(defel->defname, "cascade") == 0)
2344 : : {
2345 [ - + ]: 20 : if (d_cascade)
2346 : 0 : errorConflictingDefElem(defel, pstate);
2347 : 20 : d_cascade = defel;
2348 : 20 : cascade = defGetBoolean(d_cascade);
2349 : : }
2350 : : else
2351 [ # # ]: 0 : elog(ERROR, "unrecognized option: %s", defel->defname);
2352 : : }
2353 : :
2354 : : /* Call CreateExtensionInternal to do the real work. */
2355 : 378 : return CreateExtensionInternal(stmt->extname,
2356 : : schemaName,
2357 : : versionName,
2358 : : cascade,
2359 : : NIL,
2360 : : true);
2361 : : }
2362 : :
2363 : : /*
2364 : : * InsertExtensionTuple
2365 : : *
2366 : : * Insert the new pg_extension row, and create extension's dependency entries.
2367 : : * Return the OID assigned to the new row.
2368 : : *
2369 : : * This is exported for the benefit of pg_upgrade, which has to create a
2370 : : * pg_extension entry (and the extension-level dependencies) without
2371 : : * actually running the extension's script.
2372 : : *
2373 : : * extConfig and extCondition should be arrays or PointerGetDatum(NULL).
2374 : : * We declare them as plain Datum to avoid needing array.h in extension.h.
2375 : : */
2376 : : ObjectAddress
2377 : 392 : InsertExtensionTuple(const char *extName, Oid extOwner,
2378 : : Oid schemaOid, bool relocatable, const char *extVersion,
2379 : : Datum extConfig, Datum extCondition,
2380 : : List *requiredExtensions)
2381 : : {
2382 : : Oid extensionOid;
2383 : : Relation rel;
2384 : : Datum values[Natts_pg_extension];
2385 : : bool nulls[Natts_pg_extension];
2386 : : HeapTuple tuple;
2387 : : ObjectAddress myself;
2388 : : ObjectAddress nsp;
2389 : : ObjectAddresses *refobjs;
2390 : : ListCell *lc;
2391 : :
2392 : : /*
2393 : : * Build and insert the pg_extension tuple
2394 : : */
2395 : 392 : rel = table_open(ExtensionRelationId, RowExclusiveLock);
2396 : :
2397 : 392 : memset(values, 0, sizeof(values));
2398 : 392 : memset(nulls, 0, sizeof(nulls));
2399 : :
2400 : 392 : extensionOid = GetNewOidWithIndex(rel, ExtensionOidIndexId,
2401 : : Anum_pg_extension_oid);
2402 : 392 : values[Anum_pg_extension_oid - 1] = ObjectIdGetDatum(extensionOid);
2403 : 392 : values[Anum_pg_extension_extname - 1] =
2404 : 392 : DirectFunctionCall1(namein, CStringGetDatum(extName));
2405 : 392 : values[Anum_pg_extension_extowner - 1] = ObjectIdGetDatum(extOwner);
2406 : 392 : values[Anum_pg_extension_extnamespace - 1] = ObjectIdGetDatum(schemaOid);
2407 : 392 : values[Anum_pg_extension_extrelocatable - 1] = BoolGetDatum(relocatable);
2408 : 392 : values[Anum_pg_extension_extversion - 1] = CStringGetTextDatum(extVersion);
2409 : :
2410 [ + - ]: 392 : if (extConfig == PointerGetDatum(NULL))
2411 : 392 : nulls[Anum_pg_extension_extconfig - 1] = true;
2412 : : else
2413 : 0 : values[Anum_pg_extension_extconfig - 1] = extConfig;
2414 : :
2415 [ + - ]: 392 : if (extCondition == PointerGetDatum(NULL))
2416 : 392 : nulls[Anum_pg_extension_extcondition - 1] = true;
2417 : : else
2418 : 0 : values[Anum_pg_extension_extcondition - 1] = extCondition;
2419 : :
2420 : 392 : tuple = heap_form_tuple(rel->rd_att, values, nulls);
2421 : :
2422 : 392 : CatalogTupleInsert(rel, tuple);
2423 : :
2424 : 392 : heap_freetuple(tuple);
2425 : 392 : table_close(rel, RowExclusiveLock);
2426 : :
2427 : : /*
2428 : : * Record dependencies on owner, schema, and prerequisite extensions
2429 : : */
2430 : 392 : recordDependencyOnOwner(ExtensionRelationId, extensionOid, extOwner);
2431 : :
2432 : 392 : refobjs = new_object_addresses();
2433 : :
2434 : 392 : ObjectAddressSet(myself, ExtensionRelationId, extensionOid);
2435 : :
2436 : 392 : ObjectAddressSet(nsp, NamespaceRelationId, schemaOid);
2437 : 392 : add_exact_object_address(&nsp, refobjs);
2438 : :
2439 [ + + + + : 417 : foreach(lc, requiredExtensions)
+ + ]
2440 : : {
2441 : 25 : Oid reqext = lfirst_oid(lc);
2442 : : ObjectAddress otherext;
2443 : :
2444 : 25 : ObjectAddressSet(otherext, ExtensionRelationId, reqext);
2445 : 25 : add_exact_object_address(&otherext, refobjs);
2446 : : }
2447 : :
2448 : : /* Record all of them (this includes duplicate elimination) */
2449 : 392 : record_object_address_dependencies(&myself, refobjs, DEPENDENCY_NORMAL);
2450 : 392 : free_object_addresses(refobjs);
2451 : :
2452 : : /* Post creation hook for new extension */
2453 [ - + ]: 392 : InvokeObjectPostCreateHook(ExtensionRelationId, extensionOid, 0);
2454 : :
2455 : 392 : return myself;
2456 : : }
2457 : :
2458 : : /*
2459 : : * Guts of extension deletion.
2460 : : *
2461 : : * All we need do here is remove the pg_extension tuple itself. Everything
2462 : : * else is taken care of by the dependency infrastructure.
2463 : : */
2464 : : void
2465 : 125 : RemoveExtensionById(Oid extId)
2466 : : {
2467 : : Relation rel;
2468 : : SysScanDesc scandesc;
2469 : : HeapTuple tuple;
2470 : : ScanKeyData entry[1];
2471 : :
2472 : : /*
2473 : : * Disallow deletion of any extension that's currently open for insertion;
2474 : : * else subsequent executions of recordDependencyOnCurrentExtension()
2475 : : * could create dangling pg_depend records that refer to a no-longer-valid
2476 : : * pg_extension OID. This is needed not so much because we think people
2477 : : * might write "DROP EXTENSION foo" in foo's own script files, as because
2478 : : * errors in dependency management in extension script files could give
2479 : : * rise to cases where an extension is dropped as a result of recursing
2480 : : * from some contained object. Because of that, we must test for the case
2481 : : * here, not at some higher level of the DROP EXTENSION command.
2482 : : */
2483 [ - + ]: 125 : if (extId == CurrentExtensionObject)
2484 [ # # ]: 0 : ereport(ERROR,
2485 : : (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
2486 : : errmsg("cannot drop extension \"%s\" because it is being modified",
2487 : : get_extension_name(extId))));
2488 : :
2489 : 125 : rel = table_open(ExtensionRelationId, RowExclusiveLock);
2490 : :
2491 : 125 : ScanKeyInit(&entry[0],
2492 : : Anum_pg_extension_oid,
2493 : : BTEqualStrategyNumber, F_OIDEQ,
2494 : : ObjectIdGetDatum(extId));
2495 : 125 : scandesc = systable_beginscan(rel, ExtensionOidIndexId, true,
2496 : : NULL, 1, entry);
2497 : :
2498 : 125 : tuple = systable_getnext(scandesc);
2499 : :
2500 : : /* We assume that there can be at most one matching tuple */
2501 [ + - ]: 125 : if (HeapTupleIsValid(tuple))
2502 : 125 : CatalogTupleDelete(rel, &tuple->t_self);
2503 : :
2504 : 125 : systable_endscan(scandesc);
2505 : :
2506 : 125 : table_close(rel, RowExclusiveLock);
2507 : 125 : }
2508 : :
2509 : : /*
2510 : : * This function lists the available extensions (one row per primary control
2511 : : * file in the control directory). We parse each control file and report the
2512 : : * interesting fields.
2513 : : *
2514 : : * The system view pg_available_extensions provides a user interface to this
2515 : : * SRF, adding information about whether the extensions are installed in the
2516 : : * current DB.
2517 : : */
2518 : : Datum
2519 : 77 : pg_available_extensions(PG_FUNCTION_ARGS)
2520 : : {
2521 : 77 : ReturnSetInfo *rsinfo = (ReturnSetInfo *) fcinfo->resultinfo;
2522 : : List *locations;
2523 : : DIR *dir;
2524 : : struct dirent *de;
2525 : 77 : List *found_ext = NIL;
2526 : :
2527 : : /* Build tuplestore to hold the result rows */
2528 : 77 : InitMaterializedSRF(fcinfo, 0);
2529 : :
2530 : 77 : locations = get_extension_control_directories();
2531 : :
2532 [ + - + + : 241 : foreach_ptr(ExtensionLocation, location, locations)
+ + ]
2533 : : {
2534 : 87 : dir = AllocateDir(location->loc);
2535 : :
2536 : : /*
2537 : : * If the control directory doesn't exist, we want to silently return
2538 : : * an empty set. Any other error will be reported by ReadDir.
2539 : : */
2540 [ - + - - ]: 87 : if (dir == NULL && errno == ENOENT)
2541 : : {
2542 : : /* do nothing */
2543 : : }
2544 : : else
2545 : : {
2546 [ + + ]: 28698 : while ((de = ReadDir(dir, location->loc)) != NULL)
2547 : : {
2548 : : ExtensionControlFile *control;
2549 : : char *extname;
2550 : : String *extname_str;
2551 : : Datum values[4];
2552 : : bool nulls[4];
2553 : :
2554 [ + + ]: 28611 : if (!is_extension_control_filename(de->d_name))
2555 : 19515 : continue;
2556 : :
2557 : : /* extract extension name from 'name.control' filename */
2558 : 9100 : extname = pstrdup(de->d_name);
2559 : 9100 : *strrchr(extname, '.') = '\0';
2560 : :
2561 : : /* ignore it if it's an auxiliary control file */
2562 [ - + ]: 9100 : if (strstr(extname, "--"))
2563 : 0 : continue;
2564 : :
2565 : : /*
2566 : : * Ignore already-found names. They are not reachable by the
2567 : : * path search, so don't show them.
2568 : : */
2569 : 9100 : extname_str = makeString(extname);
2570 [ + + ]: 9100 : if (list_member(found_ext, extname_str))
2571 : 4 : continue;
2572 : : else
2573 : 9096 : found_ext = lappend(found_ext, extname_str);
2574 : :
2575 : 9096 : control = new_ExtensionControlFile(extname);
2576 : 9096 : control->control_dir = pstrdup(location->loc);
2577 : 9096 : parse_extension_control_file(control, NULL);
2578 : :
2579 : 9096 : memset(values, 0, sizeof(values));
2580 : 9096 : memset(nulls, 0, sizeof(nulls));
2581 : :
2582 : : /* name */
2583 : 9096 : values[0] = DirectFunctionCall1(namein,
2584 : : CStringGetDatum(control->name));
2585 : : /* default_version */
2586 [ - + ]: 9096 : if (control->default_version == NULL)
2587 : 0 : nulls[1] = true;
2588 : : else
2589 : 9096 : values[1] = CStringGetTextDatum(control->default_version);
2590 : :
2591 : : /* location */
2592 : 9096 : values[2] = CStringGetTextDatum(get_extension_location(location));
2593 : :
2594 : : /* comment */
2595 [ - + ]: 9096 : if (control->comment == NULL)
2596 : 0 : nulls[3] = true;
2597 : : else
2598 : 9096 : values[3] = CStringGetTextDatum(control->comment);
2599 : :
2600 : 9096 : tuplestore_putvalues(rsinfo->setResult, rsinfo->setDesc,
2601 : : values, nulls);
2602 : : }
2603 : :
2604 : 87 : FreeDir(dir);
2605 : : }
2606 : : }
2607 : :
2608 : 77 : return (Datum) 0;
2609 : : }
2610 : :
2611 : : /*
2612 : : * This function lists the available extension versions (one row per
2613 : : * extension installation script). For each version, we parse the related
2614 : : * control file(s) and report the interesting fields.
2615 : : *
2616 : : * The system view pg_available_extension_versions provides a user interface
2617 : : * to this SRF, adding information about which versions are installed in the
2618 : : * current DB.
2619 : : */
2620 : : Datum
2621 : 7 : pg_available_extension_versions(PG_FUNCTION_ARGS)
2622 : : {
2623 : 7 : ReturnSetInfo *rsinfo = (ReturnSetInfo *) fcinfo->resultinfo;
2624 : : List *locations;
2625 : : DIR *dir;
2626 : : struct dirent *de;
2627 : 7 : List *found_ext = NIL;
2628 : :
2629 : : /* Build tuplestore to hold the result rows */
2630 : 7 : InitMaterializedSRF(fcinfo, 0);
2631 : :
2632 : 7 : locations = get_extension_control_directories();
2633 : :
2634 [ + - + + : 27 : foreach_ptr(ExtensionLocation, location, locations)
+ + ]
2635 : : {
2636 : 13 : dir = AllocateDir(location->loc);
2637 : :
2638 : : /*
2639 : : * If the control directory doesn't exist, we want to silently return
2640 : : * an empty set. Any other error will be reported by ReadDir.
2641 : : */
2642 [ - + - - ]: 13 : if (dir == NULL && errno == ENOENT)
2643 : : {
2644 : : /* do nothing */
2645 : : }
2646 : : else
2647 : : {
2648 [ + + ]: 2637 : while ((de = ReadDir(dir, location->loc)) != NULL)
2649 : : {
2650 : : ExtensionControlFile *control;
2651 : : char *extname;
2652 : : String *extname_str;
2653 : :
2654 [ + + ]: 2624 : if (!is_extension_control_filename(de->d_name))
2655 : 1789 : continue;
2656 : :
2657 : : /* extract extension name from 'name.control' filename */
2658 : 835 : extname = pstrdup(de->d_name);
2659 : 835 : *strrchr(extname, '.') = '\0';
2660 : :
2661 : : /* ignore it if it's an auxiliary control file */
2662 [ - + ]: 835 : if (strstr(extname, "--"))
2663 : 0 : continue;
2664 : :
2665 : : /*
2666 : : * Ignore already-found names. They are not reachable by the
2667 : : * path search, so don't show them.
2668 : : */
2669 : 835 : extname_str = makeString(extname);
2670 [ + + ]: 835 : if (list_member(found_ext, extname_str))
2671 : 3 : continue;
2672 : : else
2673 : 832 : found_ext = lappend(found_ext, extname_str);
2674 : :
2675 : : /* read the control file */
2676 : 832 : control = new_ExtensionControlFile(extname);
2677 : 832 : control->control_dir = pstrdup(location->loc);
2678 : 832 : parse_extension_control_file(control, NULL);
2679 : :
2680 : : /* scan extension's script directory for install scripts */
2681 : 832 : get_available_versions_for_extension(control, rsinfo->setResult,
2682 : : rsinfo->setDesc,
2683 : : location);
2684 : : }
2685 : :
2686 : 13 : FreeDir(dir);
2687 : : }
2688 : : }
2689 : :
2690 : 7 : return (Datum) 0;
2691 : : }
2692 : :
2693 : : /*
2694 : : * Inner loop for pg_available_extension_versions:
2695 : : * read versions of one extension, add rows to tupstore
2696 : : */
2697 : : static void
2698 : 832 : get_available_versions_for_extension(ExtensionControlFile *pcontrol,
2699 : : Tuplestorestate *tupstore,
2700 : : TupleDesc tupdesc,
2701 : : ExtensionLocation *location)
2702 : : {
2703 : : List *evi_list;
2704 : : ListCell *lc;
2705 : :
2706 : : /* Extract the version update graph from the script directory */
2707 : 832 : evi_list = get_ext_ver_list(pcontrol);
2708 : :
2709 : : /* For each installable version ... */
2710 [ + - + + : 2595 : foreach(lc, evi_list)
+ + ]
2711 : : {
2712 : 1763 : ExtensionVersionInfo *evi = (ExtensionVersionInfo *) lfirst(lc);
2713 : : ExtensionControlFile *control;
2714 : : Datum values[9];
2715 : : bool nulls[9];
2716 : : ListCell *lc2;
2717 : :
2718 [ + + ]: 1763 : if (!evi->installable)
2719 : 931 : continue;
2720 : :
2721 : : /*
2722 : : * Fetch parameters for specific version (pcontrol is not changed)
2723 : : */
2724 : 832 : control = read_extension_aux_control_file(pcontrol, evi->name);
2725 : :
2726 : 832 : memset(values, 0, sizeof(values));
2727 : 832 : memset(nulls, 0, sizeof(nulls));
2728 : :
2729 : : /* name */
2730 : 832 : values[0] = DirectFunctionCall1(namein,
2731 : : CStringGetDatum(control->name));
2732 : : /* version */
2733 : 832 : values[1] = CStringGetTextDatum(evi->name);
2734 : : /* superuser */
2735 : 832 : values[2] = BoolGetDatum(control->superuser);
2736 : : /* trusted */
2737 : 832 : values[3] = BoolGetDatum(control->trusted);
2738 : : /* relocatable */
2739 : 832 : values[4] = BoolGetDatum(control->relocatable);
2740 : : /* schema */
2741 [ + + ]: 832 : if (control->schema == NULL)
2742 : 755 : nulls[5] = true;
2743 : : else
2744 : 77 : values[5] = DirectFunctionCall1(namein,
2745 : : CStringGetDatum(control->schema));
2746 : : /* requires */
2747 [ + + ]: 832 : if (control->requires == NIL)
2748 : 713 : nulls[6] = true;
2749 : : else
2750 : 119 : values[6] = convert_requires_to_datum(control->requires);
2751 : :
2752 : : /* location */
2753 : 832 : values[7] = CStringGetTextDatum(get_extension_location(location));
2754 : :
2755 : : /* comment */
2756 [ - + ]: 832 : if (control->comment == NULL)
2757 : 0 : nulls[8] = true;
2758 : : else
2759 : 832 : values[8] = CStringGetTextDatum(control->comment);
2760 : :
2761 : 832 : tuplestore_putvalues(tupstore, tupdesc, values, nulls);
2762 : :
2763 : : /*
2764 : : * Find all non-directly-installable versions that would be installed
2765 : : * starting from this version, and report them, inheriting the
2766 : : * parameters that aren't changed in updates from this version.
2767 : : */
2768 [ + - + + : 2595 : foreach(lc2, evi_list)
+ + ]
2769 : : {
2770 : 1763 : ExtensionVersionInfo *evi2 = (ExtensionVersionInfo *) lfirst(lc2);
2771 : : List *best_path;
2772 : :
2773 [ + + ]: 1763 : if (evi2->installable)
2774 : 832 : continue;
2775 [ + + ]: 931 : if (find_install_path(evi_list, evi2, &best_path) == evi)
2776 : : {
2777 : : /*
2778 : : * Fetch parameters for this version (pcontrol is not changed)
2779 : : */
2780 : 518 : control = read_extension_aux_control_file(pcontrol, evi2->name);
2781 : :
2782 : : /* name stays the same */
2783 : : /* version */
2784 : 518 : values[1] = CStringGetTextDatum(evi2->name);
2785 : : /* superuser */
2786 : 518 : values[2] = BoolGetDatum(control->superuser);
2787 : : /* trusted */
2788 : 518 : values[3] = BoolGetDatum(control->trusted);
2789 : : /* relocatable */
2790 : 518 : values[4] = BoolGetDatum(control->relocatable);
2791 : : /* schema stays the same */
2792 : : /* requires */
2793 [ + + ]: 518 : if (control->requires == NIL)
2794 : 511 : nulls[6] = true;
2795 : : else
2796 : : {
2797 : 7 : values[6] = convert_requires_to_datum(control->requires);
2798 : 7 : nulls[6] = false;
2799 : : }
2800 : : /* comment and location stay the same */
2801 : :
2802 : 518 : tuplestore_putvalues(tupstore, tupdesc, values, nulls);
2803 : : }
2804 : : }
2805 : : }
2806 : 832 : }
2807 : :
2808 : : /*
2809 : : * Test whether the given extension exists (not whether it's installed)
2810 : : *
2811 : : * This checks for the existence of a matching control file in the extension
2812 : : * directory. That's not a bulletproof check, since the file might be
2813 : : * invalid, but this is only used for hints so it doesn't have to be 100%
2814 : : * right.
2815 : : */
2816 : : bool
2817 : 0 : extension_file_exists(const char *extensionName)
2818 : : {
2819 : 0 : bool result = false;
2820 : : List *locations;
2821 : : DIR *dir;
2822 : : struct dirent *de;
2823 : :
2824 : 0 : locations = get_extension_control_directories();
2825 : :
2826 [ # # # # : 0 : foreach_ptr(ExtensionLocation, location, locations)
# # ]
2827 : : {
2828 : 0 : dir = AllocateDir(location->loc);
2829 : :
2830 : : /*
2831 : : * If the control directory doesn't exist, we want to silently return
2832 : : * false. Any other error will be reported by ReadDir.
2833 : : */
2834 [ # # # # ]: 0 : if (dir == NULL && errno == ENOENT)
2835 : : {
2836 : : /* do nothing */
2837 : : }
2838 : : else
2839 : : {
2840 [ # # ]: 0 : while ((de = ReadDir(dir, location->loc)) != NULL)
2841 : : {
2842 : : char *extname;
2843 : :
2844 [ # # ]: 0 : if (!is_extension_control_filename(de->d_name))
2845 : 0 : continue;
2846 : :
2847 : : /* extract extension name from 'name.control' filename */
2848 : 0 : extname = pstrdup(de->d_name);
2849 : 0 : *strrchr(extname, '.') = '\0';
2850 : :
2851 : : /* ignore it if it's an auxiliary control file */
2852 [ # # ]: 0 : if (strstr(extname, "--"))
2853 : 0 : continue;
2854 : :
2855 : : /* done if it matches request */
2856 [ # # ]: 0 : if (strcmp(extname, extensionName) == 0)
2857 : : {
2858 : 0 : result = true;
2859 : 0 : break;
2860 : : }
2861 : : }
2862 : :
2863 : 0 : FreeDir(dir);
2864 : : }
2865 [ # # ]: 0 : if (result)
2866 : 0 : break;
2867 : : }
2868 : :
2869 : 0 : return result;
2870 : : }
2871 : :
2872 : : /*
2873 : : * Convert a list of extension names to a name[] Datum
2874 : : */
2875 : : static Datum
2876 : 126 : convert_requires_to_datum(List *requires)
2877 : : {
2878 : : Datum *datums;
2879 : : int ndatums;
2880 : : ArrayType *a;
2881 : : ListCell *lc;
2882 : :
2883 : 126 : ndatums = list_length(requires);
2884 : 126 : datums = palloc_array(Datum, ndatums);
2885 : 126 : ndatums = 0;
2886 [ + - + + : 301 : foreach(lc, requires)
+ + ]
2887 : : {
2888 : 175 : char *curreq = (char *) lfirst(lc);
2889 : :
2890 : 175 : datums[ndatums++] =
2891 : 175 : DirectFunctionCall1(namein, CStringGetDatum(curreq));
2892 : : }
2893 : 126 : a = construct_array_builtin(datums, ndatums, NAMEOID);
2894 : 126 : return PointerGetDatum(a);
2895 : : }
2896 : :
2897 : : /*
2898 : : * This function reports the version update paths that exist for the
2899 : : * specified extension.
2900 : : */
2901 : : Datum
2902 : 0 : pg_extension_update_paths(PG_FUNCTION_ARGS)
2903 : : {
2904 : 0 : Name extname = PG_GETARG_NAME(0);
2905 : 0 : ReturnSetInfo *rsinfo = (ReturnSetInfo *) fcinfo->resultinfo;
2906 : : List *evi_list;
2907 : : ExtensionControlFile *control;
2908 : : ListCell *lc1;
2909 : :
2910 : : /* Check extension name validity before any filesystem access */
2911 : 0 : check_valid_extension_name(NameStr(*extname));
2912 : :
2913 : : /* Build tuplestore to hold the result rows */
2914 : 0 : InitMaterializedSRF(fcinfo, 0);
2915 : :
2916 : : /* Read the extension's control file */
2917 : 0 : control = read_extension_control_file(NameStr(*extname));
2918 : :
2919 : : /* Extract the version update graph from the script directory */
2920 : 0 : evi_list = get_ext_ver_list(control);
2921 : :
2922 : : /* Iterate over all pairs of versions */
2923 [ # # # # : 0 : foreach(lc1, evi_list)
# # ]
2924 : : {
2925 : 0 : ExtensionVersionInfo *evi1 = (ExtensionVersionInfo *) lfirst(lc1);
2926 : : ListCell *lc2;
2927 : :
2928 [ # # # # : 0 : foreach(lc2, evi_list)
# # ]
2929 : : {
2930 : 0 : ExtensionVersionInfo *evi2 = (ExtensionVersionInfo *) lfirst(lc2);
2931 : : List *path;
2932 : : Datum values[3];
2933 : : bool nulls[3];
2934 : :
2935 [ # # ]: 0 : if (evi1 == evi2)
2936 : 0 : continue;
2937 : :
2938 : : /* Find shortest path from evi1 to evi2 */
2939 : 0 : path = find_update_path(evi_list, evi1, evi2, false, true);
2940 : :
2941 : : /* Emit result row */
2942 : 0 : memset(values, 0, sizeof(values));
2943 : 0 : memset(nulls, 0, sizeof(nulls));
2944 : :
2945 : : /* source */
2946 : 0 : values[0] = CStringGetTextDatum(evi1->name);
2947 : : /* target */
2948 : 0 : values[1] = CStringGetTextDatum(evi2->name);
2949 : : /* path */
2950 [ # # ]: 0 : if (path == NIL)
2951 : 0 : nulls[2] = true;
2952 : : else
2953 : : {
2954 : : StringInfoData pathbuf;
2955 : : ListCell *lcv;
2956 : :
2957 : 0 : initStringInfo(&pathbuf);
2958 : : /* The path doesn't include start vertex, but show it */
2959 : 0 : appendStringInfoString(&pathbuf, evi1->name);
2960 [ # # # # : 0 : foreach(lcv, path)
# # ]
2961 : : {
2962 : 0 : char *versionName = (char *) lfirst(lcv);
2963 : :
2964 : 0 : appendStringInfoString(&pathbuf, "--");
2965 : 0 : appendStringInfoString(&pathbuf, versionName);
2966 : : }
2967 : 0 : values[2] = CStringGetTextDatum(pathbuf.data);
2968 : 0 : pfree(pathbuf.data);
2969 : : }
2970 : :
2971 : 0 : tuplestore_putvalues(rsinfo->setResult, rsinfo->setDesc,
2972 : : values, nulls);
2973 : : }
2974 : : }
2975 : :
2976 : 0 : return (Datum) 0;
2977 : : }
2978 : :
2979 : : /*
2980 : : * pg_extension_config_dump
2981 : : *
2982 : : * Record information about a configuration table that belongs to an
2983 : : * extension being created, but whose contents should be dumped in whole
2984 : : * or in part during pg_dump.
2985 : : */
2986 : : Datum
2987 : 6 : pg_extension_config_dump(PG_FUNCTION_ARGS)
2988 : : {
2989 : 6 : Oid tableoid = PG_GETARG_OID(0);
2990 : 6 : text *wherecond = PG_GETARG_TEXT_PP(1);
2991 : : char *tablename;
2992 : : Relation extRel;
2993 : : ScanKeyData key[1];
2994 : : SysScanDesc extScan;
2995 : : HeapTuple extTup;
2996 : : Datum arrayDatum;
2997 : : Datum elementDatum;
2998 : : int arrayLength;
2999 : : int arrayIndex;
3000 : : bool isnull;
3001 : : Datum repl_val[Natts_pg_extension];
3002 : : bool repl_null[Natts_pg_extension];
3003 : : bool repl_repl[Natts_pg_extension];
3004 : : ArrayType *a;
3005 : :
3006 : : /*
3007 : : * We only allow this to be called from an extension's SQL script. We
3008 : : * shouldn't need any permissions check beyond that. No concurrent
3009 : : * session can mutate the extension: ALTER EXTENSION UPDATE locks the
3010 : : * extension; during CREATE EXTENSION, it is not yet committed.
3011 : : */
3012 [ - + ]: 6 : if (!creating_extension)
3013 [ # # ]: 0 : ereport(ERROR,
3014 : : (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
3015 : : errmsg("%s can only be called from an SQL script executed by CREATE EXTENSION",
3016 : : "pg_extension_config_dump()")));
3017 : :
3018 : : /*
3019 : : * Check that the table exists and is a member of the extension being
3020 : : * created. This ensures that we don't need to register an additional
3021 : : * dependency to protect the extconfig entry.
3022 : : */
3023 : 6 : tablename = get_rel_name(tableoid);
3024 [ - + ]: 6 : if (tablename == NULL)
3025 [ # # ]: 0 : ereport(ERROR,
3026 : : (errcode(ERRCODE_UNDEFINED_TABLE),
3027 : : errmsg("OID %u does not refer to a table", tableoid)));
3028 [ - + ]: 6 : if (getExtensionOfObject(RelationRelationId, tableoid) !=
3029 : : CurrentExtensionObject)
3030 [ # # ]: 0 : ereport(ERROR,
3031 : : (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
3032 : : errmsg("table \"%s\" is not a member of the extension being created",
3033 : : tablename)));
3034 : :
3035 : : /*
3036 : : * Add the table OID and WHERE condition to the extension's extconfig and
3037 : : * extcondition arrays.
3038 : : *
3039 : : * If the table is already in extconfig, treat this as an update of the
3040 : : * WHERE condition.
3041 : : */
3042 : :
3043 : : /* Find the pg_extension tuple */
3044 : 6 : extRel = table_open(ExtensionRelationId, RowExclusiveLock);
3045 : :
3046 : 6 : ScanKeyInit(&key[0],
3047 : : Anum_pg_extension_oid,
3048 : : BTEqualStrategyNumber, F_OIDEQ,
3049 : : ObjectIdGetDatum(CurrentExtensionObject));
3050 : :
3051 : 6 : extScan = systable_beginscan(extRel, ExtensionOidIndexId, true,
3052 : : NULL, 1, key);
3053 : :
3054 : 6 : extTup = systable_getnext(extScan);
3055 : :
3056 [ - + ]: 6 : if (!HeapTupleIsValid(extTup)) /* should not happen */
3057 [ # # ]: 0 : elog(ERROR, "could not find tuple for extension %u",
3058 : : CurrentExtensionObject);
3059 : :
3060 : 6 : memset(repl_val, 0, sizeof(repl_val));
3061 : 6 : memset(repl_null, false, sizeof(repl_null));
3062 : 6 : memset(repl_repl, false, sizeof(repl_repl));
3063 : :
3064 : : /* Build or modify the extconfig value */
3065 : 6 : elementDatum = ObjectIdGetDatum(tableoid);
3066 : :
3067 : 6 : arrayDatum = heap_getattr(extTup, Anum_pg_extension_extconfig,
3068 : : RelationGetDescr(extRel), &isnull);
3069 [ + + ]: 6 : if (isnull)
3070 : : {
3071 : : /* Previously empty extconfig, so build 1-element array */
3072 : 3 : arrayLength = 0;
3073 : 3 : arrayIndex = 1;
3074 : :
3075 : 3 : a = construct_array_builtin(&elementDatum, 1, OIDOID);
3076 : : }
3077 : : else
3078 : : {
3079 : : /* Modify or extend existing extconfig array */
3080 : : Oid *arrayData;
3081 : : int i;
3082 : :
3083 : 3 : a = DatumGetArrayTypeP(arrayDatum);
3084 : :
3085 : 3 : arrayLength = ARR_DIMS(a)[0];
3086 [ + - ]: 3 : if (ARR_NDIM(a) != 1 ||
3087 [ + - + - ]: 3 : ARR_LBOUND(a)[0] != 1 ||
3088 : 3 : arrayLength < 0 ||
3089 [ + - ]: 3 : ARR_HASNULL(a) ||
3090 [ - + ]: 3 : ARR_ELEMTYPE(a) != OIDOID)
3091 [ # # ]: 0 : elog(ERROR, "extconfig is not a 1-D Oid array");
3092 [ - + ]: 3 : arrayData = (Oid *) ARR_DATA_PTR(a);
3093 : :
3094 : 3 : arrayIndex = arrayLength + 1; /* set up to add after end */
3095 : :
3096 [ + + ]: 6 : for (i = 0; i < arrayLength; i++)
3097 : : {
3098 [ - + ]: 3 : if (arrayData[i] == tableoid)
3099 : : {
3100 : 0 : arrayIndex = i + 1; /* replace this element instead */
3101 : 0 : break;
3102 : : }
3103 : : }
3104 : :
3105 : 3 : a = array_set(a, 1, &arrayIndex,
3106 : : elementDatum,
3107 : : false,
3108 : : -1 /* varlena array */ ,
3109 : : sizeof(Oid) /* OID's typlen */ ,
3110 : : true /* OID's typbyval */ ,
3111 : : TYPALIGN_INT /* OID's typalign */ );
3112 : : }
3113 : 6 : repl_val[Anum_pg_extension_extconfig - 1] = PointerGetDatum(a);
3114 : 6 : repl_repl[Anum_pg_extension_extconfig - 1] = true;
3115 : :
3116 : : /* Build or modify the extcondition value */
3117 : 6 : elementDatum = PointerGetDatum(wherecond);
3118 : :
3119 : 6 : arrayDatum = heap_getattr(extTup, Anum_pg_extension_extcondition,
3120 : : RelationGetDescr(extRel), &isnull);
3121 [ + + ]: 6 : if (isnull)
3122 : : {
3123 [ - + ]: 3 : if (arrayLength != 0)
3124 [ # # ]: 0 : elog(ERROR, "extconfig and extcondition arrays do not match");
3125 : :
3126 : 3 : a = construct_array_builtin(&elementDatum, 1, TEXTOID);
3127 : : }
3128 : : else
3129 : : {
3130 : 3 : a = DatumGetArrayTypeP(arrayDatum);
3131 : :
3132 [ + - ]: 3 : if (ARR_NDIM(a) != 1 ||
3133 [ + - ]: 3 : ARR_LBOUND(a)[0] != 1 ||
3134 [ + - ]: 3 : ARR_HASNULL(a) ||
3135 [ - + ]: 3 : ARR_ELEMTYPE(a) != TEXTOID)
3136 [ # # ]: 0 : elog(ERROR, "extcondition is not a 1-D text array");
3137 [ - + ]: 3 : if (ARR_DIMS(a)[0] != arrayLength)
3138 [ # # ]: 0 : elog(ERROR, "extconfig and extcondition arrays do not match");
3139 : :
3140 : : /* Add or replace at same index as in extconfig */
3141 : 3 : a = array_set(a, 1, &arrayIndex,
3142 : : elementDatum,
3143 : : false,
3144 : : -1 /* varlena array */ ,
3145 : : -1 /* TEXT's typlen */ ,
3146 : : false /* TEXT's typbyval */ ,
3147 : : TYPALIGN_INT /* TEXT's typalign */ );
3148 : : }
3149 : 6 : repl_val[Anum_pg_extension_extcondition - 1] = PointerGetDatum(a);
3150 : 6 : repl_repl[Anum_pg_extension_extcondition - 1] = true;
3151 : :
3152 : 6 : extTup = heap_modify_tuple(extTup, RelationGetDescr(extRel),
3153 : : repl_val, repl_null, repl_repl);
3154 : :
3155 : 6 : CatalogTupleUpdate(extRel, &extTup->t_self, extTup);
3156 : :
3157 : 6 : systable_endscan(extScan);
3158 : :
3159 : 6 : table_close(extRel, RowExclusiveLock);
3160 : :
3161 : 6 : PG_RETURN_VOID();
3162 : : }
3163 : :
3164 : : /*
3165 : : * pg_get_loaded_modules
3166 : : *
3167 : : * SQL-callable function to get per-loaded-module information. Modules
3168 : : * (shared libraries) aren't necessarily one-to-one with extensions, but
3169 : : * they're sufficiently closely related to make this file a good home.
3170 : : */
3171 : : Datum
3172 : 0 : pg_get_loaded_modules(PG_FUNCTION_ARGS)
3173 : : {
3174 : 0 : ReturnSetInfo *rsinfo = (ReturnSetInfo *) fcinfo->resultinfo;
3175 : : DynamicFileList *file_scanner;
3176 : :
3177 : : /* Build tuplestore to hold the result rows */
3178 : 0 : InitMaterializedSRF(fcinfo, 0);
3179 : :
3180 [ # # ]: 0 : for (file_scanner = get_first_loaded_module(); file_scanner != NULL;
3181 : 0 : file_scanner = get_next_loaded_module(file_scanner))
3182 : : {
3183 : : const char *library_path,
3184 : : *module_name,
3185 : : *module_version;
3186 : : const char *sep;
3187 : 0 : Datum values[3] = {0};
3188 : 0 : bool nulls[3] = {0};
3189 : :
3190 : 0 : get_loaded_module_details(file_scanner,
3191 : : &library_path,
3192 : : &module_name,
3193 : : &module_version);
3194 : :
3195 [ # # ]: 0 : if (module_name == NULL)
3196 : 0 : nulls[0] = true;
3197 : : else
3198 : 0 : values[0] = CStringGetTextDatum(module_name);
3199 [ # # ]: 0 : if (module_version == NULL)
3200 : 0 : nulls[1] = true;
3201 : : else
3202 : 0 : values[1] = CStringGetTextDatum(module_version);
3203 : :
3204 : : /* For security reasons, we don't show the directory path */
3205 : 0 : sep = last_dir_separator(library_path);
3206 [ # # ]: 0 : if (sep)
3207 : 0 : library_path = sep + 1;
3208 : 0 : values[2] = CStringGetTextDatum(library_path);
3209 : :
3210 : 0 : tuplestore_putvalues(rsinfo->setResult, rsinfo->setDesc,
3211 : : values, nulls);
3212 : : }
3213 : :
3214 : 0 : return (Datum) 0;
3215 : : }
3216 : :
3217 : : /*
3218 : : * extension_config_remove
3219 : : *
3220 : : * Remove the specified table OID from extension's extconfig, if present.
3221 : : * This is not currently exposed as a function, but it could be;
3222 : : * for now, we just invoke it from ALTER EXTENSION DROP.
3223 : : */
3224 : : static void
3225 : 35 : extension_config_remove(Oid extensionoid, Oid tableoid)
3226 : : {
3227 : : Relation extRel;
3228 : : ScanKeyData key[1];
3229 : : SysScanDesc extScan;
3230 : : HeapTuple extTup;
3231 : : Datum arrayDatum;
3232 : : int arrayLength;
3233 : : int arrayIndex;
3234 : : bool isnull;
3235 : : Datum repl_val[Natts_pg_extension];
3236 : : bool repl_null[Natts_pg_extension];
3237 : : bool repl_repl[Natts_pg_extension];
3238 : : ArrayType *a;
3239 : :
3240 : : /* Find the pg_extension tuple */
3241 : 35 : extRel = table_open(ExtensionRelationId, RowExclusiveLock);
3242 : :
3243 : 35 : ScanKeyInit(&key[0],
3244 : : Anum_pg_extension_oid,
3245 : : BTEqualStrategyNumber, F_OIDEQ,
3246 : : ObjectIdGetDatum(extensionoid));
3247 : :
3248 : 35 : extScan = systable_beginscan(extRel, ExtensionOidIndexId, true,
3249 : : NULL, 1, key);
3250 : :
3251 : 35 : extTup = systable_getnext(extScan);
3252 : :
3253 [ - + ]: 35 : if (!HeapTupleIsValid(extTup)) /* should not happen */
3254 [ # # ]: 0 : elog(ERROR, "could not find tuple for extension %u",
3255 : : extensionoid);
3256 : :
3257 : : /* Search extconfig for the tableoid */
3258 : 35 : arrayDatum = heap_getattr(extTup, Anum_pg_extension_extconfig,
3259 : : RelationGetDescr(extRel), &isnull);
3260 [ + + ]: 35 : if (isnull)
3261 : : {
3262 : : /* nothing to do */
3263 : 31 : a = NULL;
3264 : 31 : arrayLength = 0;
3265 : 31 : arrayIndex = -1;
3266 : : }
3267 : : else
3268 : : {
3269 : : Oid *arrayData;
3270 : : int i;
3271 : :
3272 : 4 : a = DatumGetArrayTypeP(arrayDatum);
3273 : :
3274 : 4 : arrayLength = ARR_DIMS(a)[0];
3275 [ + - ]: 4 : if (ARR_NDIM(a) != 1 ||
3276 [ + - + - ]: 4 : ARR_LBOUND(a)[0] != 1 ||
3277 : 4 : arrayLength < 0 ||
3278 [ + - ]: 4 : ARR_HASNULL(a) ||
3279 [ - + ]: 4 : ARR_ELEMTYPE(a) != OIDOID)
3280 [ # # ]: 0 : elog(ERROR, "extconfig is not a 1-D Oid array");
3281 [ - + ]: 4 : arrayData = (Oid *) ARR_DATA_PTR(a);
3282 : :
3283 : 4 : arrayIndex = -1; /* flag for no deletion needed */
3284 : :
3285 [ + + ]: 12 : for (i = 0; i < arrayLength; i++)
3286 : : {
3287 [ - + ]: 8 : if (arrayData[i] == tableoid)
3288 : : {
3289 : 0 : arrayIndex = i; /* index to remove */
3290 : 0 : break;
3291 : : }
3292 : : }
3293 : : }
3294 : :
3295 : : /* If tableoid is not in extconfig, nothing to do */
3296 [ + - ]: 35 : if (arrayIndex < 0)
3297 : : {
3298 : 35 : systable_endscan(extScan);
3299 : 35 : table_close(extRel, RowExclusiveLock);
3300 : 35 : return;
3301 : : }
3302 : :
3303 : : /* Modify or delete the extconfig value */
3304 : 0 : memset(repl_val, 0, sizeof(repl_val));
3305 : 0 : memset(repl_null, false, sizeof(repl_null));
3306 : 0 : memset(repl_repl, false, sizeof(repl_repl));
3307 : :
3308 [ # # ]: 0 : if (arrayLength <= 1)
3309 : : {
3310 : : /* removing only element, just set array to null */
3311 : 0 : repl_null[Anum_pg_extension_extconfig - 1] = true;
3312 : : }
3313 : : else
3314 : : {
3315 : : /* squeeze out the target element */
3316 : : Datum *dvalues;
3317 : : int nelems;
3318 : : int i;
3319 : :
3320 : : /* We already checked there are no nulls */
3321 : 0 : deconstruct_array_builtin(a, OIDOID, &dvalues, NULL, &nelems);
3322 : :
3323 [ # # ]: 0 : for (i = arrayIndex; i < arrayLength - 1; i++)
3324 : 0 : dvalues[i] = dvalues[i + 1];
3325 : :
3326 : 0 : a = construct_array_builtin(dvalues, arrayLength - 1, OIDOID);
3327 : :
3328 : 0 : repl_val[Anum_pg_extension_extconfig - 1] = PointerGetDatum(a);
3329 : : }
3330 : 0 : repl_repl[Anum_pg_extension_extconfig - 1] = true;
3331 : :
3332 : : /* Modify or delete the extcondition value */
3333 : 0 : arrayDatum = heap_getattr(extTup, Anum_pg_extension_extcondition,
3334 : : RelationGetDescr(extRel), &isnull);
3335 [ # # ]: 0 : if (isnull)
3336 : : {
3337 [ # # ]: 0 : elog(ERROR, "extconfig and extcondition arrays do not match");
3338 : : }
3339 : : else
3340 : : {
3341 : 0 : a = DatumGetArrayTypeP(arrayDatum);
3342 : :
3343 [ # # ]: 0 : if (ARR_NDIM(a) != 1 ||
3344 [ # # ]: 0 : ARR_LBOUND(a)[0] != 1 ||
3345 [ # # ]: 0 : ARR_HASNULL(a) ||
3346 [ # # ]: 0 : ARR_ELEMTYPE(a) != TEXTOID)
3347 [ # # ]: 0 : elog(ERROR, "extcondition is not a 1-D text array");
3348 [ # # ]: 0 : if (ARR_DIMS(a)[0] != arrayLength)
3349 [ # # ]: 0 : elog(ERROR, "extconfig and extcondition arrays do not match");
3350 : : }
3351 : :
3352 [ # # ]: 0 : if (arrayLength <= 1)
3353 : : {
3354 : : /* removing only element, just set array to null */
3355 : 0 : repl_null[Anum_pg_extension_extcondition - 1] = true;
3356 : : }
3357 : : else
3358 : : {
3359 : : /* squeeze out the target element */
3360 : : Datum *dvalues;
3361 : : int nelems;
3362 : : int i;
3363 : :
3364 : : /* We already checked there are no nulls */
3365 : 0 : deconstruct_array_builtin(a, TEXTOID, &dvalues, NULL, &nelems);
3366 : :
3367 [ # # ]: 0 : for (i = arrayIndex; i < arrayLength - 1; i++)
3368 : 0 : dvalues[i] = dvalues[i + 1];
3369 : :
3370 : 0 : a = construct_array_builtin(dvalues, arrayLength - 1, TEXTOID);
3371 : :
3372 : 0 : repl_val[Anum_pg_extension_extcondition - 1] = PointerGetDatum(a);
3373 : : }
3374 : 0 : repl_repl[Anum_pg_extension_extcondition - 1] = true;
3375 : :
3376 : 0 : extTup = heap_modify_tuple(extTup, RelationGetDescr(extRel),
3377 : : repl_val, repl_null, repl_repl);
3378 : :
3379 : 0 : CatalogTupleUpdate(extRel, &extTup->t_self, extTup);
3380 : :
3381 : 0 : systable_endscan(extScan);
3382 : :
3383 : 0 : table_close(extRel, RowExclusiveLock);
3384 : : }
3385 : :
3386 : : /*
3387 : : * Execute ALTER EXTENSION SET SCHEMA
3388 : : */
3389 : : ObjectAddress
3390 : 6 : AlterExtensionNamespace(const char *extensionName, const char *newschema, Oid *oldschema)
3391 : : {
3392 : : ObjectAddress extAddr;
3393 : : Oid extensionOid;
3394 : : Oid nspOid;
3395 : : Oid oldNspOid;
3396 : : AclResult aclresult;
3397 : : Relation extRel;
3398 : : ScanKeyData key[2];
3399 : : SysScanDesc extScan;
3400 : : HeapTuple extTup;
3401 : : Form_pg_extension extForm;
3402 : : Relation depRel;
3403 : : SysScanDesc depScan;
3404 : : HeapTuple depTup;
3405 : : ObjectAddresses *objsMoved;
3406 : :
3407 : 6 : extAddr = get_object_address(OBJECT_EXTENSION,
3408 : 6 : (Node *) makeString(pstrdup(extensionName)),
3409 : : NULL, ShareUpdateExclusiveLock, false);
3410 : 6 : extensionOid = extAddr.objectId;
3411 : :
3412 : 6 : nspOid = LookupCreationNamespace(newschema);
3413 : :
3414 : : /*
3415 : : * Permission check: must own extension. Note that we don't bother to
3416 : : * check ownership of the individual member objects ...
3417 : : */
3418 [ - + ]: 6 : if (!object_ownercheck(ExtensionRelationId, extensionOid, GetUserId()))
3419 : 0 : aclcheck_error(ACLCHECK_NOT_OWNER, OBJECT_EXTENSION,
3420 : : extensionName);
3421 : :
3422 : : /* Permission check: must have creation rights in target namespace */
3423 : 6 : aclresult = object_aclcheck(NamespaceRelationId, nspOid, GetUserId(), ACL_CREATE);
3424 [ - + ]: 6 : if (aclresult != ACLCHECK_OK)
3425 : 0 : aclcheck_error(aclresult, OBJECT_SCHEMA, newschema);
3426 : :
3427 : : /*
3428 : : * If the schema is currently a member of the extension, disallow moving
3429 : : * the extension into the schema. That would create a dependency loop.
3430 : : */
3431 [ - + ]: 6 : if (getExtensionOfObject(NamespaceRelationId, nspOid) == extensionOid)
3432 [ # # ]: 0 : ereport(ERROR,
3433 : : (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
3434 : : errmsg("cannot move extension \"%s\" into schema \"%s\" "
3435 : : "because the extension contains the schema",
3436 : : extensionName, newschema)));
3437 : :
3438 : : /* Locate the pg_extension tuple */
3439 : 6 : extRel = table_open(ExtensionRelationId, RowExclusiveLock);
3440 : :
3441 : 6 : ScanKeyInit(&key[0],
3442 : : Anum_pg_extension_oid,
3443 : : BTEqualStrategyNumber, F_OIDEQ,
3444 : : ObjectIdGetDatum(extensionOid));
3445 : :
3446 : 6 : extScan = systable_beginscan(extRel, ExtensionOidIndexId, true,
3447 : : NULL, 1, key);
3448 : :
3449 : 6 : extTup = systable_getnext(extScan);
3450 : :
3451 [ - + ]: 6 : if (!HeapTupleIsValid(extTup)) /* should not happen */
3452 [ # # ]: 0 : elog(ERROR, "could not find tuple for extension %u",
3453 : : extensionOid);
3454 : :
3455 : : /* Copy tuple so we can modify it below */
3456 : 6 : extTup = heap_copytuple(extTup);
3457 : 6 : extForm = (Form_pg_extension) GETSTRUCT(extTup);
3458 : :
3459 : 6 : systable_endscan(extScan);
3460 : :
3461 : : /*
3462 : : * If the extension is already in the target schema, just silently do
3463 : : * nothing.
3464 : : */
3465 [ - + ]: 6 : if (extForm->extnamespace == nspOid)
3466 : : {
3467 : 0 : table_close(extRel, RowExclusiveLock);
3468 : 0 : return InvalidObjectAddress;
3469 : : }
3470 : :
3471 : : /* Check extension is supposed to be relocatable */
3472 [ - + ]: 6 : if (!extForm->extrelocatable)
3473 [ # # ]: 0 : ereport(ERROR,
3474 : : (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
3475 : : errmsg("extension \"%s\" does not support SET SCHEMA",
3476 : : NameStr(extForm->extname))));
3477 : :
3478 : 6 : objsMoved = new_object_addresses();
3479 : :
3480 : : /* store the OID of the namespace to-be-changed */
3481 : 6 : oldNspOid = extForm->extnamespace;
3482 : :
3483 : : /*
3484 : : * Scan pg_depend to find objects that depend directly on the extension,
3485 : : * and alter each one's schema.
3486 : : */
3487 : 6 : depRel = table_open(DependRelationId, AccessShareLock);
3488 : :
3489 : 6 : ScanKeyInit(&key[0],
3490 : : Anum_pg_depend_refclassid,
3491 : : BTEqualStrategyNumber, F_OIDEQ,
3492 : : ObjectIdGetDatum(ExtensionRelationId));
3493 : 6 : ScanKeyInit(&key[1],
3494 : : Anum_pg_depend_refobjid,
3495 : : BTEqualStrategyNumber, F_OIDEQ,
3496 : : ObjectIdGetDatum(extensionOid));
3497 : :
3498 : 6 : depScan = systable_beginscan(depRel, DependReferenceIndexId, true,
3499 : : NULL, 2, key);
3500 : :
3501 [ + + ]: 29 : while (HeapTupleIsValid(depTup = systable_getnext(depScan)))
3502 : : {
3503 : 25 : Form_pg_depend pg_depend = (Form_pg_depend) GETSTRUCT(depTup);
3504 : : ObjectAddress dep;
3505 : : Oid dep_oldNspOid;
3506 : :
3507 : : /*
3508 : : * If a dependent extension has a no_relocate request for this
3509 : : * extension, disallow SET SCHEMA. (XXX it's a bit ugly to do this in
3510 : : * the same loop that's actually executing the renames: we may detect
3511 : : * the error condition only after having expended a fair amount of
3512 : : * work. However, the alternative is to do two scans of pg_depend,
3513 : : * which seems like optimizing for failure cases. The rename work
3514 : : * will all roll back cleanly enough if we do fail here.)
3515 : : */
3516 [ + + ]: 25 : if (pg_depend->deptype == DEPENDENCY_NORMAL &&
3517 [ + - ]: 4 : pg_depend->classid == ExtensionRelationId)
3518 : : {
3519 : 4 : char *depextname = get_extension_name(pg_depend->objid);
3520 : : ExtensionControlFile *dcontrol;
3521 : : ListCell *lc;
3522 : :
3523 : 4 : dcontrol = read_extension_control_file(depextname);
3524 [ + + + + : 5 : foreach(lc, dcontrol->no_relocate)
+ + ]
3525 : : {
3526 : 2 : char *nrextname = (char *) lfirst(lc);
3527 : :
3528 [ + + ]: 2 : if (strcmp(nrextname, NameStr(extForm->extname)) == 0)
3529 : : {
3530 [ + - ]: 1 : ereport(ERROR,
3531 : : (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
3532 : : errmsg("cannot SET SCHEMA of extension \"%s\" because other extensions prevent it",
3533 : : NameStr(extForm->extname)),
3534 : : errdetail("Extension \"%s\" requests no relocation of extension \"%s\".",
3535 : : depextname,
3536 : : NameStr(extForm->extname))));
3537 : : }
3538 : : }
3539 : : }
3540 : :
3541 : : /*
3542 : : * Otherwise, ignore non-membership dependencies. (Currently, the
3543 : : * only other case we could see here is a normal dependency from
3544 : : * another extension.)
3545 : : */
3546 [ + + ]: 24 : if (pg_depend->deptype != DEPENDENCY_EXTENSION)
3547 : 3 : continue;
3548 : :
3549 : 21 : dep.classId = pg_depend->classid;
3550 : 21 : dep.objectId = pg_depend->objid;
3551 : 21 : dep.objectSubId = pg_depend->objsubid;
3552 : :
3553 [ - + ]: 21 : if (dep.objectSubId != 0) /* should not happen */
3554 [ # # ]: 0 : elog(ERROR, "extension should not have a sub-object dependency");
3555 : :
3556 : : /* Relocate the object */
3557 : 21 : dep_oldNspOid = AlterObjectNamespace_oid(dep.classId,
3558 : : dep.objectId,
3559 : : nspOid,
3560 : : objsMoved);
3561 : :
3562 : : /*
3563 : : * If not all the objects had the same old namespace (ignoring any
3564 : : * that are not in namespaces or are dependent types), complain.
3565 : : */
3566 [ + + + + ]: 21 : if (dep_oldNspOid != InvalidOid && dep_oldNspOid != oldNspOid)
3567 [ + - ]: 1 : ereport(ERROR,
3568 : : (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
3569 : : errmsg("extension \"%s\" does not support SET SCHEMA",
3570 : : NameStr(extForm->extname)),
3571 : : errdetail("%s is not in the extension's schema \"%s\".",
3572 : : getObjectDescription(&dep, false),
3573 : : get_namespace_name(oldNspOid))));
3574 : : }
3575 : :
3576 : : /* report old schema, if caller wants it */
3577 [ + - ]: 4 : if (oldschema)
3578 : 4 : *oldschema = oldNspOid;
3579 : :
3580 : 4 : systable_endscan(depScan);
3581 : :
3582 : 4 : relation_close(depRel, AccessShareLock);
3583 : :
3584 : : /* Now adjust pg_extension.extnamespace */
3585 : 4 : extForm->extnamespace = nspOid;
3586 : :
3587 : 4 : CatalogTupleUpdate(extRel, &extTup->t_self, extTup);
3588 : :
3589 : 4 : table_close(extRel, RowExclusiveLock);
3590 : :
3591 : : /* update dependency to point to the new schema */
3592 [ - + ]: 4 : if (changeDependencyFor(ExtensionRelationId, extensionOid,
3593 : : NamespaceRelationId, oldNspOid, nspOid) != 1)
3594 [ # # ]: 0 : elog(ERROR, "could not change schema dependency for extension %s",
3595 : : NameStr(extForm->extname));
3596 : :
3597 [ - + ]: 4 : InvokeObjectPostAlterHook(ExtensionRelationId, extensionOid, 0);
3598 : :
3599 : 4 : return extAddr;
3600 : : }
3601 : :
3602 : : /*
3603 : : * Execute ALTER EXTENSION UPDATE
3604 : : */
3605 : : ObjectAddress
3606 : 20 : ExecAlterExtensionStmt(ParseState *pstate, AlterExtensionStmt *stmt)
3607 : : {
3608 : : ObjectAddress address;
3609 : 20 : DefElem *d_new_version = NULL;
3610 : : char *versionName;
3611 : : char *oldVersionName;
3612 : : ExtensionControlFile *control;
3613 : : Oid extensionOid;
3614 : : Relation extRel;
3615 : : ScanKeyData key[1];
3616 : : SysScanDesc extScan;
3617 : : HeapTuple extTup;
3618 : : List *updateVersions;
3619 : : Datum datum;
3620 : : bool isnull;
3621 : : ListCell *lc;
3622 : :
3623 : : /*
3624 : : * We use global variables to track the extension being created, so we can
3625 : : * create/update only one extension at the same time.
3626 : : */
3627 [ - + ]: 20 : if (creating_extension)
3628 [ # # ]: 0 : ereport(ERROR,
3629 : : (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
3630 : : errmsg("nested ALTER EXTENSION is not supported")));
3631 : :
3632 : : /*----------
3633 : : * Lock the extension --- it must already exist in pg_extension. Exclude
3634 : : * other ALTER EXTENSION UPDATE backends; the alternative is not useful
3635 : : * beyond constructing attacks and would allow this sequence of events:
3636 : : *
3637 : : * - I choose script files based on the latest committed extversion.
3638 : : * - Concurrent ALTER EXTENSION UPDATE commits.
3639 : : * - I enter ApplyExtensionUpdates() and run script files not appropriate
3640 : : * for the latest committed extversion.
3641 : : */
3642 : 20 : address = get_object_address(OBJECT_EXTENSION,
3643 : 20 : (Node *) makeString(stmt->extname),
3644 : : NULL, ShareUpdateExclusiveLock, false);
3645 : 20 : extensionOid = address.objectId;
3646 : :
3647 : 20 : extRel = table_open(ExtensionRelationId, AccessShareLock);
3648 : :
3649 : 20 : ScanKeyInit(&key[0],
3650 : : Anum_pg_extension_oid,
3651 : : BTEqualStrategyNumber, F_OIDEQ,
3652 : : ObjectIdGetDatum(extensionOid));
3653 : :
3654 : 20 : extScan = systable_beginscan(extRel, ExtensionOidIndexId, true,
3655 : : NULL, 1, key);
3656 : :
3657 : 20 : extTup = systable_getnext(extScan);
3658 : :
3659 [ - + ]: 20 : if (!HeapTupleIsValid(extTup)) /* should not happen */
3660 [ # # ]: 0 : elog(ERROR, "could not find tuple for extension %u", extensionOid);
3661 : :
3662 : : /*
3663 : : * Determine the existing version we are updating from
3664 : : */
3665 : 20 : datum = heap_getattr(extTup, Anum_pg_extension_extversion,
3666 : : RelationGetDescr(extRel), &isnull);
3667 [ - + ]: 20 : if (isnull)
3668 [ # # ]: 0 : elog(ERROR, "extversion is null");
3669 : 20 : oldVersionName = text_to_cstring(DatumGetTextPP(datum));
3670 : :
3671 : 20 : systable_endscan(extScan);
3672 : :
3673 : 20 : table_close(extRel, AccessShareLock);
3674 : :
3675 : : /* Permission check: must own extension */
3676 [ - + ]: 20 : if (!object_ownercheck(ExtensionRelationId, extensionOid, GetUserId()))
3677 : 0 : aclcheck_error(ACLCHECK_NOT_OWNER, OBJECT_EXTENSION,
3678 : 0 : stmt->extname);
3679 : :
3680 : : /*
3681 : : * Read the primary control file. Note we assume that it does not contain
3682 : : * any non-ASCII data, so there is no need to worry about encoding at this
3683 : : * point.
3684 : : */
3685 : 20 : control = read_extension_control_file(stmt->extname);
3686 : :
3687 : : /*
3688 : : * Read the statement option list
3689 : : */
3690 [ + - + + : 40 : foreach(lc, stmt->options)
+ + ]
3691 : : {
3692 : 20 : DefElem *defel = (DefElem *) lfirst(lc);
3693 : :
3694 [ + - ]: 20 : if (strcmp(defel->defname, "new_version") == 0)
3695 : : {
3696 [ - + ]: 20 : if (d_new_version)
3697 : 0 : errorConflictingDefElem(defel, pstate);
3698 : 20 : d_new_version = defel;
3699 : : }
3700 : : else
3701 [ # # ]: 0 : elog(ERROR, "unrecognized option: %s", defel->defname);
3702 : : }
3703 : :
3704 : : /*
3705 : : * Determine the version to update to
3706 : : */
3707 [ + - + - ]: 20 : if (d_new_version && d_new_version->arg)
3708 : 20 : versionName = strVal(d_new_version->arg);
3709 [ # # ]: 0 : else if (control->default_version)
3710 : 0 : versionName = control->default_version;
3711 : : else
3712 : : {
3713 [ # # ]: 0 : ereport(ERROR,
3714 : : (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
3715 : : errmsg("version to install must be specified")));
3716 : : versionName = NULL; /* keep compiler quiet */
3717 : : }
3718 : 20 : check_valid_version_name(versionName);
3719 : :
3720 : : /*
3721 : : * If we're already at that version, just say so
3722 : : */
3723 [ - + ]: 20 : if (strcmp(oldVersionName, versionName) == 0)
3724 : : {
3725 [ # # ]: 0 : ereport(NOTICE,
3726 : : (errmsg("version \"%s\" of extension \"%s\" is already installed",
3727 : : versionName, stmt->extname)));
3728 : 0 : return InvalidObjectAddress;
3729 : : }
3730 : :
3731 : : /*
3732 : : * Identify the series of update script files we need to execute
3733 : : */
3734 : 20 : updateVersions = identify_update_path(control,
3735 : : oldVersionName,
3736 : : versionName);
3737 : :
3738 : : /*
3739 : : * Update the pg_extension row and execute the update scripts, one at a
3740 : : * time
3741 : : */
3742 : 20 : ApplyExtensionUpdates(extensionOid, control,
3743 : : oldVersionName, updateVersions,
3744 : : NULL, false, false);
3745 : :
3746 : 17 : return address;
3747 : : }
3748 : :
3749 : : /*
3750 : : * Apply a series of update scripts as though individual ALTER EXTENSION
3751 : : * UPDATE commands had been given, including altering the pg_extension row
3752 : : * and dependencies each time.
3753 : : *
3754 : : * This might be more work than necessary, but it ensures that old update
3755 : : * scripts don't break if newer versions have different control parameters.
3756 : : */
3757 : : static void
3758 : 382 : ApplyExtensionUpdates(Oid extensionOid,
3759 : : ExtensionControlFile *pcontrol,
3760 : : const char *initialVersion,
3761 : : List *updateVersions,
3762 : : char *origSchemaName,
3763 : : bool cascade,
3764 : : bool is_create)
3765 : : {
3766 : 382 : const char *oldVersionName = initialVersion;
3767 : : ListCell *lcv;
3768 : :
3769 [ + + + + : 695 : foreach(lcv, updateVersions)
+ + ]
3770 : : {
3771 : 316 : char *versionName = (char *) lfirst(lcv);
3772 : : ExtensionControlFile *control;
3773 : : char *schemaName;
3774 : : Oid schemaOid;
3775 : : List *requiredExtensions;
3776 : : List *requiredSchemas;
3777 : : Relation extRel;
3778 : : ScanKeyData key[1];
3779 : : SysScanDesc extScan;
3780 : : HeapTuple extTup;
3781 : : Form_pg_extension extForm;
3782 : : Datum values[Natts_pg_extension];
3783 : : bool nulls[Natts_pg_extension];
3784 : : bool repl[Natts_pg_extension];
3785 : : ObjectAddress myself;
3786 : : ListCell *lc;
3787 : :
3788 : : /*
3789 : : * Fetch parameters for specific version (pcontrol is not changed)
3790 : : */
3791 : 316 : control = read_extension_aux_control_file(pcontrol, versionName);
3792 : :
3793 : : /* Find the pg_extension tuple */
3794 : 316 : extRel = table_open(ExtensionRelationId, RowExclusiveLock);
3795 : :
3796 : 316 : ScanKeyInit(&key[0],
3797 : : Anum_pg_extension_oid,
3798 : : BTEqualStrategyNumber, F_OIDEQ,
3799 : : ObjectIdGetDatum(extensionOid));
3800 : :
3801 : 316 : extScan = systable_beginscan(extRel, ExtensionOidIndexId, true,
3802 : : NULL, 1, key);
3803 : :
3804 : 316 : extTup = systable_getnext(extScan);
3805 : :
3806 [ - + ]: 316 : if (!HeapTupleIsValid(extTup)) /* should not happen */
3807 [ # # ]: 0 : elog(ERROR, "could not find tuple for extension %u",
3808 : : extensionOid);
3809 : :
3810 : 316 : extForm = (Form_pg_extension) GETSTRUCT(extTup);
3811 : :
3812 : : /*
3813 : : * Determine the target schema (set by original install)
3814 : : */
3815 : 316 : schemaOid = extForm->extnamespace;
3816 : 316 : LockDatabaseObject(NamespaceRelationId, schemaOid, 0,
3817 : : AccessShareLock);
3818 : 316 : schemaName = get_namespace_name(schemaOid);
3819 [ - + ]: 316 : if (!schemaName)
3820 [ # # ]: 0 : elog(ERROR, "cache lookup failed for schema %u", schemaOid);
3821 : :
3822 : : /*
3823 : : * Modify extrelocatable and extversion in the pg_extension tuple
3824 : : */
3825 : 316 : memset(values, 0, sizeof(values));
3826 : 316 : memset(nulls, 0, sizeof(nulls));
3827 : 316 : memset(repl, 0, sizeof(repl));
3828 : :
3829 : 316 : values[Anum_pg_extension_extrelocatable - 1] =
3830 : 316 : BoolGetDatum(control->relocatable);
3831 : 316 : repl[Anum_pg_extension_extrelocatable - 1] = true;
3832 : 316 : values[Anum_pg_extension_extversion - 1] =
3833 : 316 : CStringGetTextDatum(versionName);
3834 : 316 : repl[Anum_pg_extension_extversion - 1] = true;
3835 : :
3836 : 316 : extTup = heap_modify_tuple(extTup, RelationGetDescr(extRel),
3837 : : values, nulls, repl);
3838 : :
3839 : 316 : CatalogTupleUpdate(extRel, &extTup->t_self, extTup);
3840 : :
3841 : 316 : systable_endscan(extScan);
3842 : :
3843 : 316 : table_close(extRel, RowExclusiveLock);
3844 : :
3845 : : /*
3846 : : * Look up the prerequisite extensions for this version, install them
3847 : : * if necessary, and build lists of their OIDs and the OIDs of their
3848 : : * target schemas.
3849 : : */
3850 : 316 : requiredExtensions = NIL;
3851 : 316 : requiredSchemas = NIL;
3852 [ + + + + : 317 : foreach(lc, control->requires)
+ + ]
3853 : : {
3854 : 1 : char *curreq = (char *) lfirst(lc);
3855 : : Oid reqext;
3856 : : Oid reqschema;
3857 : :
3858 : 1 : reqext = get_required_extension(curreq,
3859 : : control->name,
3860 : : origSchemaName,
3861 : : cascade,
3862 : : NIL,
3863 : : is_create);
3864 : 1 : reqschema = get_extension_schema(reqext);
3865 : 1 : LockDatabaseObject(NamespaceRelationId, reqschema, 0,
3866 : : AccessShareLock);
3867 : 1 : requiredExtensions = lappend_oid(requiredExtensions, reqext);
3868 : 1 : requiredSchemas = lappend_oid(requiredSchemas, reqschema);
3869 : : }
3870 : :
3871 : : /*
3872 : : * Remove and recreate dependencies on prerequisite extensions
3873 : : */
3874 : 316 : deleteDependencyRecordsForClass(ExtensionRelationId, extensionOid,
3875 : : ExtensionRelationId,
3876 : : DEPENDENCY_NORMAL);
3877 : :
3878 : 316 : myself.classId = ExtensionRelationId;
3879 : 316 : myself.objectId = extensionOid;
3880 : 316 : myself.objectSubId = 0;
3881 : :
3882 [ + + + + : 317 : foreach(lc, requiredExtensions)
+ + ]
3883 : : {
3884 : 1 : Oid reqext = lfirst_oid(lc);
3885 : : ObjectAddress otherext;
3886 : :
3887 : 1 : otherext.classId = ExtensionRelationId;
3888 : 1 : otherext.objectId = reqext;
3889 : 1 : otherext.objectSubId = 0;
3890 : :
3891 : 1 : recordDependencyOn(&myself, &otherext, DEPENDENCY_NORMAL);
3892 : : }
3893 : :
3894 [ - + ]: 316 : InvokeObjectPostAlterHook(ExtensionRelationId, extensionOid, 0);
3895 : :
3896 : : /*
3897 : : * Finally, execute the update script file
3898 : : */
3899 : 316 : execute_extension_script(extensionOid, control,
3900 : : oldVersionName, versionName,
3901 : : requiredSchemas,
3902 : : schemaOid, schemaName);
3903 : :
3904 : : /*
3905 : : * Update prior-version name and loop around. Since
3906 : : * execute_sql_string did a final CommandCounterIncrement, we can
3907 : : * update the pg_extension row again.
3908 : : */
3909 : 313 : oldVersionName = versionName;
3910 : : }
3911 : 379 : }
3912 : :
3913 : : /*
3914 : : * Execute ALTER EXTENSION ADD/DROP
3915 : : *
3916 : : * Return value is the address of the altered extension.
3917 : : *
3918 : : * objAddr is an output argument which, if not NULL, is set to the address of
3919 : : * the added/dropped object.
3920 : : */
3921 : : ObjectAddress
3922 : 147 : ExecAlterExtensionContentsStmt(AlterExtensionContentsStmt *stmt,
3923 : : ObjectAddress *objAddr)
3924 : : {
3925 : : ObjectAddress extension;
3926 : : ObjectAddress object;
3927 : : Relation relation;
3928 : :
3929 [ + + ]: 147 : switch (stmt->objtype)
3930 : : {
3931 : 1 : case OBJECT_DATABASE:
3932 : : case OBJECT_EXTENSION:
3933 : : case OBJECT_INDEX:
3934 : : case OBJECT_PUBLICATION:
3935 : : case OBJECT_ROLE:
3936 : : case OBJECT_STATISTIC_EXT:
3937 : : case OBJECT_SUBSCRIPTION:
3938 : : case OBJECT_TABLESPACE:
3939 [ + - ]: 1 : ereport(ERROR,
3940 : : (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
3941 : : errmsg("cannot add an object of this type to an extension")));
3942 : : break;
3943 : 146 : default:
3944 : : /* OK */
3945 : 146 : break;
3946 : : }
3947 : :
3948 : : /*
3949 : : * Exclude other mutations of the same extension. The dependency loop
3950 : : * check below assumes no concurrent ALTER EXTENSION SET SCHEMA.
3951 : : */
3952 : 146 : extension = get_object_address(OBJECT_EXTENSION,
3953 : 146 : (Node *) makeString(stmt->extname),
3954 : : &relation, ShareUpdateExclusiveLock, false);
3955 : :
3956 : : /* Permission check: must own extension */
3957 [ - + ]: 146 : if (!object_ownercheck(ExtensionRelationId, extension.objectId, GetUserId()))
3958 : 0 : aclcheck_error(ACLCHECK_NOT_OWNER, OBJECT_EXTENSION,
3959 : 0 : stmt->extname);
3960 : :
3961 : : /*
3962 : : * Translate the parser representation that identifies the object into an
3963 : : * ObjectAddress. get_object_address() will throw an error if the object
3964 : : * does not exist, and will also acquire a lock on the object to guard
3965 : : * against concurrent DROP and ALTER EXTENSION ADD/DROP operations.
3966 : : */
3967 : 146 : object = get_object_address(stmt->objtype, stmt->object,
3968 : : &relation, ShareUpdateExclusiveLock, false);
3969 : :
3970 : : Assert(object.objectSubId == 0);
3971 [ + - ]: 146 : if (objAddr)
3972 : 146 : *objAddr = object;
3973 : :
3974 : : /* Permission check: must own target object, too */
3975 : 146 : check_object_ownership(GetUserId(), stmt->objtype, object,
3976 : : stmt->object, relation);
3977 : :
3978 : : /* Do the update, recursing to any dependent objects */
3979 : 146 : ExecAlterExtensionContentsRecurse(stmt, extension, object);
3980 : :
3981 : : /* Finish up */
3982 [ - + ]: 146 : InvokeObjectPostAlterHook(ExtensionRelationId, extension.objectId, 0);
3983 : :
3984 : : /*
3985 : : * If get_object_address() opened the relation for us, we close it to keep
3986 : : * the reference count correct - but we retain any locks acquired by
3987 : : * get_object_address() until commit time, to guard against concurrent
3988 : : * activity.
3989 : : */
3990 [ + + ]: 146 : if (relation != NULL)
3991 : 43 : relation_close(relation, NoLock);
3992 : :
3993 : 146 : return extension;
3994 : : }
3995 : :
3996 : : /*
3997 : : * ExecAlterExtensionContentsRecurse
3998 : : * Subroutine for ExecAlterExtensionContentsStmt
3999 : : *
4000 : : * Do the bare alteration of object's membership in extension,
4001 : : * without permission checks. Recurse to dependent objects, if any.
4002 : : */
4003 : : static void
4004 : 238 : ExecAlterExtensionContentsRecurse(AlterExtensionContentsStmt *stmt,
4005 : : ObjectAddress extension,
4006 : : ObjectAddress object)
4007 : : {
4008 : : Oid oldExtension;
4009 : :
4010 : : /*
4011 : : * Check existing extension membership.
4012 : : */
4013 : 238 : oldExtension = getExtensionOfObject(object.classId, object.objectId);
4014 : :
4015 [ + + ]: 238 : if (stmt->action > 0)
4016 : : {
4017 : : /*
4018 : : * ADD, so complain if object is already attached to some extension.
4019 : : */
4020 [ - + ]: 55 : if (OidIsValid(oldExtension))
4021 [ # # ]: 0 : ereport(ERROR,
4022 : : (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
4023 : : errmsg("%s is already a member of extension \"%s\"",
4024 : : getObjectDescription(&object, false),
4025 : : get_extension_name(oldExtension))));
4026 : :
4027 : : /*
4028 : : * Prevent a schema from being added to an extension if the schema
4029 : : * contains the extension. That would create a dependency loop.
4030 : : */
4031 [ + + - + ]: 56 : if (object.classId == NamespaceRelationId &&
4032 : 1 : object.objectId == get_extension_schema(extension.objectId))
4033 [ # # ]: 0 : ereport(ERROR,
4034 : : (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
4035 : : errmsg("cannot add schema \"%s\" to extension \"%s\" "
4036 : : "because the schema contains the extension",
4037 : : get_namespace_name(object.objectId),
4038 : : stmt->extname)));
4039 : :
4040 : : /*
4041 : : * OK, add the dependency.
4042 : : */
4043 : 55 : recordDependencyOn(&object, &extension, DEPENDENCY_EXTENSION);
4044 : :
4045 : : /*
4046 : : * Also record the initial ACL on the object, if any.
4047 : : *
4048 : : * Note that this will handle the object's ACLs, as well as any ACLs
4049 : : * on object subIds. (In other words, when the object is a table,
4050 : : * this will record the table's ACL and the ACLs for the columns on
4051 : : * the table, if any).
4052 : : */
4053 : 55 : recordExtObjInitPriv(object.objectId, object.classId);
4054 : : }
4055 : : else
4056 : : {
4057 : : /*
4058 : : * DROP, so complain if it's not a member.
4059 : : */
4060 [ - + ]: 183 : if (oldExtension != extension.objectId)
4061 [ # # ]: 0 : ereport(ERROR,
4062 : : (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
4063 : : errmsg("%s is not a member of extension \"%s\"",
4064 : : getObjectDescription(&object, false),
4065 : : stmt->extname)));
4066 : :
4067 : : /*
4068 : : * OK, drop the dependency.
4069 : : */
4070 [ - + ]: 183 : if (deleteDependencyRecordsForClass(object.classId, object.objectId,
4071 : : ExtensionRelationId,
4072 : : DEPENDENCY_EXTENSION) != 1)
4073 [ # # ]: 0 : elog(ERROR, "unexpected number of extension dependency records");
4074 : :
4075 : : /*
4076 : : * If it's a relation, it might have an entry in the extension's
4077 : : * extconfig array, which we must remove.
4078 : : */
4079 [ + + ]: 183 : if (object.classId == RelationRelationId)
4080 : 35 : extension_config_remove(extension.objectId, object.objectId);
4081 : :
4082 : : /*
4083 : : * Remove all the initial ACLs, if any.
4084 : : *
4085 : : * Note that this will remove the object's ACLs, as well as any ACLs
4086 : : * on object subIds. (In other words, when the object is a table,
4087 : : * this will remove the table's ACL and the ACLs for the columns on
4088 : : * the table, if any).
4089 : : */
4090 : 183 : removeExtObjInitPriv(object.objectId, object.classId);
4091 : : }
4092 : :
4093 : : /*
4094 : : * Recurse to any dependent objects; currently, this includes the array
4095 : : * type of a base type, the multirange type associated with a range type,
4096 : : * and the rowtype of a table.
4097 : : */
4098 [ + + ]: 238 : if (object.classId == TypeRelationId)
4099 : : {
4100 : : ObjectAddress depobject;
4101 : :
4102 : 96 : depobject.classId = TypeRelationId;
4103 : 96 : depobject.objectSubId = 0;
4104 : :
4105 : : /* If it has an array type, update that too */
4106 : 96 : depobject.objectId = get_array_type(object.objectId);
4107 [ + + ]: 96 : if (OidIsValid(depobject.objectId))
4108 : 48 : ExecAlterExtensionContentsRecurse(stmt, extension, depobject);
4109 : :
4110 : : /* If it is a range type, update the associated multirange too */
4111 [ + + ]: 96 : if (type_is_range(object.objectId))
4112 : : {
4113 : 2 : depobject.objectId = get_range_multirange(object.objectId);
4114 [ - + ]: 2 : if (!OidIsValid(depobject.objectId))
4115 [ # # ]: 0 : ereport(ERROR,
4116 : : (errcode(ERRCODE_UNDEFINED_OBJECT),
4117 : : errmsg("could not find multirange type for data type %s",
4118 : : format_type_be(object.objectId))));
4119 : 2 : ExecAlterExtensionContentsRecurse(stmt, extension, depobject);
4120 : : }
4121 : : }
4122 [ + + ]: 238 : if (object.classId == RelationRelationId)
4123 : : {
4124 : : ObjectAddress depobject;
4125 : :
4126 : 43 : depobject.classId = TypeRelationId;
4127 : 43 : depobject.objectSubId = 0;
4128 : :
4129 : : /* It might not have a rowtype, but if it does, update that */
4130 : 43 : depobject.objectId = get_rel_type_id(object.objectId);
4131 [ + + ]: 43 : if (OidIsValid(depobject.objectId))
4132 : 42 : ExecAlterExtensionContentsRecurse(stmt, extension, depobject);
4133 : : }
4134 : 238 : }
4135 : :
4136 : : /*
4137 : : * Read the whole of file into memory.
4138 : : *
4139 : : * The file contents are returned as a single palloc'd chunk. For convenience
4140 : : * of the callers, an extra \0 byte is added to the end. That is not counted
4141 : : * in the length returned into *length.
4142 : : */
4143 : : static char *
4144 : 697 : read_whole_file(const char *filename, int *length)
4145 : : {
4146 : : char *buf;
4147 : : FILE *file;
4148 : : size_t bytes_to_read;
4149 : : struct stat fst;
4150 : :
4151 [ - + ]: 697 : if (stat(filename, &fst) < 0)
4152 [ # # ]: 0 : ereport(ERROR,
4153 : : (errcode_for_file_access(),
4154 : : errmsg("could not stat file \"%s\": %m", filename)));
4155 : :
4156 [ - + ]: 697 : if (fst.st_size > (MaxAllocSize - 1))
4157 [ # # ]: 0 : ereport(ERROR,
4158 : : (errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED),
4159 : : errmsg("file \"%s\" is too large", filename)));
4160 : 697 : bytes_to_read = (size_t) fst.st_size;
4161 : :
4162 [ - + ]: 697 : if ((file = AllocateFile(filename, PG_BINARY_R)) == NULL)
4163 [ # # ]: 0 : ereport(ERROR,
4164 : : (errcode_for_file_access(),
4165 : : errmsg("could not open file \"%s\" for reading: %m",
4166 : : filename)));
4167 : :
4168 : 697 : buf = (char *) palloc(bytes_to_read + 1);
4169 : :
4170 : 697 : bytes_to_read = fread(buf, 1, bytes_to_read, file);
4171 : :
4172 [ - + ]: 697 : if (ferror(file))
4173 [ # # ]: 0 : ereport(ERROR,
4174 : : (errcode_for_file_access(),
4175 : : errmsg("could not read file \"%s\": %m", filename)));
4176 : :
4177 : 697 : FreeFile(file);
4178 : :
4179 : 697 : buf[bytes_to_read] = '\0';
4180 : :
4181 : : /*
4182 : : * On Windows, manually convert Windows-style newlines (\r\n) to the Unix
4183 : : * convention of \n only. This avoids gotchas due to script files
4184 : : * possibly getting converted when being transferred between platforms.
4185 : : * Ideally we'd do this by using text mode to read the file, but that also
4186 : : * causes control-Z to be treated as end-of-file. Historically we've
4187 : : * allowed control-Z in script files, so breaking that seems unwise.
4188 : : */
4189 : : #ifdef WIN32
4190 : : {
4191 : : char *s,
4192 : : *d;
4193 : :
4194 : : for (s = d = buf; *s; s++)
4195 : : {
4196 : : if (!(*s == '\r' && s[1] == '\n'))
4197 : : *d++ = *s;
4198 : : }
4199 : : *d = '\0';
4200 : : bytes_to_read = d - buf;
4201 : : }
4202 : : #endif
4203 : :
4204 : 697 : *length = bytes_to_read;
4205 : 697 : return buf;
4206 : : }
4207 : :
4208 : : static ExtensionControlFile *
4209 : 10349 : new_ExtensionControlFile(const char *extname)
4210 : : {
4211 : : /*
4212 : : * Set up default values. Pointer fields are initially null.
4213 : : */
4214 : 10349 : ExtensionControlFile *control = palloc0_object(ExtensionControlFile);
4215 : :
4216 : 10349 : control->name = pstrdup(extname);
4217 : 10349 : control->relocatable = false;
4218 : 10349 : control->superuser = true;
4219 : 10349 : control->trusted = false;
4220 : 10349 : control->encoding = -1;
4221 : :
4222 : 10349 : return control;
4223 : : }
4224 : :
4225 : : /*
4226 : : * Search for the basename in the list of paths.
4227 : : *
4228 : : * Similar to find_in_path but for simplicity does not support custom error
4229 : : * messages and expects that paths already have all macros replaced.
4230 : : */
4231 : : char *
4232 : 421 : find_in_paths(const char *basename, List *paths)
4233 : : {
4234 : : ListCell *cell;
4235 : :
4236 [ + - + + : 427 : foreach(cell, paths)
+ + ]
4237 : : {
4238 : 426 : ExtensionLocation *location = lfirst(cell);
4239 : 426 : char *path = location->loc;
4240 : : char *full;
4241 : :
4242 : : Assert(path != NULL);
4243 : :
4244 : 426 : path = pstrdup(path);
4245 : 426 : canonicalize_path(path);
4246 : :
4247 : : /* only absolute paths */
4248 [ - + ]: 426 : if (!is_absolute_path(path))
4249 [ # # ]: 0 : ereport(ERROR,
4250 : : errcode(ERRCODE_INVALID_NAME),
4251 : : errmsg("component in parameter \"%s\" is not an absolute path", "extension_control_path"));
4252 : :
4253 : 426 : full = psprintf("%s/%s", path, basename);
4254 : :
4255 [ + + ]: 426 : if (pg_file_exists(full))
4256 : 420 : return full;
4257 : :
4258 : 6 : pfree(path);
4259 : 6 : pfree(full);
4260 : : }
4261 : :
4262 : 1 : return NULL;
4263 : : }
|