Debian Codegraph @

src/backend/commands/extension.c

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