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