PostgreSQL Source Code  git master
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-2022, 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/sysattr.h"
36 #include "access/table.h"
37 #include "access/xact.h"
38 #include "catalog/catalog.h"
39 #include "catalog/dependency.h"
40 #include "catalog/indexing.h"
41 #include "catalog/namespace.h"
42 #include "catalog/objectaccess.h"
43 #include "catalog/pg_authid.h"
44 #include "catalog/pg_collation.h"
45 #include "catalog/pg_depend.h"
46 #include "catalog/pg_extension.h"
47 #include "catalog/pg_namespace.h"
48 #include "catalog/pg_type.h"
49 #include "commands/alter.h"
50 #include "commands/comment.h"
51 #include "commands/defrem.h"
52 #include "commands/extension.h"
53 #include "commands/schemacmds.h"
54 #include "funcapi.h"
55 #include "mb/pg_wchar.h"
56 #include "miscadmin.h"
57 #include "nodes/makefuncs.h"
58 #include "storage/fd.h"
59 #include "tcop/utility.h"
60 #include "utils/acl.h"
61 #include "utils/builtins.h"
62 #include "utils/fmgroids.h"
63 #include "utils/lsyscache.h"
64 #include "utils/memutils.h"
65 #include "utils/rel.h"
66 #include "utils/snapmgr.h"
67 #include "utils/varlena.h"
68 
69 
70 /* Globally visible state variables */
71 bool creating_extension = false;
73 
74 /*
75  * Internal data structure to hold the results of parsing a control file
76  */
77 typedef struct ExtensionControlFile
78 {
79  char *name; /* name of the extension */
80  char *directory; /* directory for script files */
81  char *default_version; /* default install target version, if any */
82  char *module_pathname; /* string to substitute for
83  * MODULE_PATHNAME */
84  char *comment; /* comment, if any */
85  char *schema; /* target schema (allowed if !relocatable) */
86  bool relocatable; /* is ALTER EXTENSION SET SCHEMA supported? */
87  bool superuser; /* must be superuser to install? */
88  bool trusted; /* allow becoming superuser on the fly? */
89  int encoding; /* encoding of the script file, or -1 */
90  List *requires; /* names of prerequisite extensions */
92 
93 /*
94  * Internal data structure for update path information
95  */
96 typedef struct ExtensionVersionInfo
97 {
98  char *name; /* name of the starting version */
99  List *reachable; /* List of ExtensionVersionInfo's */
100  bool installable; /* does this version have an install script? */
101  /* working state for Dijkstra's algorithm: */
102  bool distance_known; /* is distance from start known yet? */
103  int distance; /* current worst-case distance estimate */
104  struct ExtensionVersionInfo *previous; /* current best predecessor */
106 
107 /* Local functions */
108 static List *find_update_path(List *evi_list,
109  ExtensionVersionInfo *evi_start,
110  ExtensionVersionInfo *evi_target,
111  bool reject_indirect,
112  bool reinitialize);
113 static Oid get_required_extension(char *reqExtensionName,
114  char *extensionName,
115  char *origSchemaName,
116  bool cascade,
117  List *parents,
118  bool is_create);
120  Tuplestorestate *tupstore,
121  TupleDesc tupdesc);
122 static Datum convert_requires_to_datum(List *requires);
123 static void ApplyExtensionUpdates(Oid extensionOid,
124  ExtensionControlFile *pcontrol,
125  const char *initialVersion,
126  List *updateVersions,
127  char *origSchemaName,
128  bool cascade,
129  bool is_create);
130 static char *read_whole_file(const char *filename, int *length);
131 
132 
133 /*
134  * get_extension_oid - given an extension name, look up the OID
135  *
136  * If missing_ok is false, throw an error if extension name not found. If
137  * true, just return InvalidOid.
138  */
139 Oid
140 get_extension_oid(const char *extname, bool missing_ok)
141 {
142  Oid result;
143  Relation rel;
144  SysScanDesc scandesc;
145  HeapTuple tuple;
146  ScanKeyData entry[1];
147 
148  rel = table_open(ExtensionRelationId, AccessShareLock);
149 
150  ScanKeyInit(&entry[0],
151  Anum_pg_extension_extname,
152  BTEqualStrategyNumber, F_NAMEEQ,
153  CStringGetDatum(extname));
154 
155  scandesc = systable_beginscan(rel, ExtensionNameIndexId, true,
156  NULL, 1, entry);
157 
158  tuple = systable_getnext(scandesc);
159 
160  /* We assume that there can be at most one matching tuple */
161  if (HeapTupleIsValid(tuple))
162  result = ((Form_pg_extension) GETSTRUCT(tuple))->oid;
163  else
164  result = InvalidOid;
165 
166  systable_endscan(scandesc);
167 
169 
170  if (!OidIsValid(result) && !missing_ok)
171  ereport(ERROR,
172  (errcode(ERRCODE_UNDEFINED_OBJECT),
173  errmsg("extension \"%s\" does not exist",
174  extname)));
175 
176  return result;
177 }
178 
179 /*
180  * get_extension_name - given an extension OID, look up the name
181  *
182  * Returns a palloc'd string, or NULL if no such extension.
183  */
184 char *
186 {
187  char *result;
188  Relation rel;
189  SysScanDesc scandesc;
190  HeapTuple tuple;
191  ScanKeyData entry[1];
192 
193  rel = table_open(ExtensionRelationId, AccessShareLock);
194 
195  ScanKeyInit(&entry[0],
196  Anum_pg_extension_oid,
197  BTEqualStrategyNumber, F_OIDEQ,
198  ObjectIdGetDatum(ext_oid));
199 
200  scandesc = systable_beginscan(rel, ExtensionOidIndexId, true,
201  NULL, 1, entry);
202 
203  tuple = systable_getnext(scandesc);
204 
205  /* We assume that there can be at most one matching tuple */
206  if (HeapTupleIsValid(tuple))
207  result = pstrdup(NameStr(((Form_pg_extension) GETSTRUCT(tuple))->extname));
208  else
209  result = NULL;
210 
211  systable_endscan(scandesc);
212 
214 
215  return result;
216 }
217 
218 /*
219  * get_extension_schema - given an extension OID, fetch its extnamespace
220  *
221  * Returns InvalidOid if no such extension.
222  */
223 static Oid
225 {
226  Oid result;
227  Relation rel;
228  SysScanDesc scandesc;
229  HeapTuple tuple;
230  ScanKeyData entry[1];
231 
232  rel = table_open(ExtensionRelationId, AccessShareLock);
233 
234  ScanKeyInit(&entry[0],
235  Anum_pg_extension_oid,
236  BTEqualStrategyNumber, F_OIDEQ,
237  ObjectIdGetDatum(ext_oid));
238 
239  scandesc = systable_beginscan(rel, ExtensionOidIndexId, true,
240  NULL, 1, entry);
241 
242  tuple = systable_getnext(scandesc);
243 
244  /* We assume that there can be at most one matching tuple */
245  if (HeapTupleIsValid(tuple))
246  result = ((Form_pg_extension) GETSTRUCT(tuple))->extnamespace;
247  else
248  result = InvalidOid;
249 
250  systable_endscan(scandesc);
251 
253 
254  return result;
255 }
256 
257 /*
258  * Utility functions to check validity of extension and version names
259  */
260 static void
261 check_valid_extension_name(const char *extensionname)
262 {
263  int namelen = strlen(extensionname);
264 
265  /*
266  * Disallow empty names (the parser rejects empty identifiers anyway, but
267  * let's check).
268  */
269  if (namelen == 0)
270  ereport(ERROR,
271  (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
272  errmsg("invalid extension name: \"%s\"", extensionname),
273  errdetail("Extension names must not be empty.")));
274 
275  /*
276  * No double dashes, since that would make script filenames ambiguous.
277  */
278  if (strstr(extensionname, "--"))
279  ereport(ERROR,
280  (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
281  errmsg("invalid extension name: \"%s\"", extensionname),
282  errdetail("Extension names must not contain \"--\".")));
283 
284  /*
285  * No leading or trailing dash either. (We could probably allow this, but
286  * it would require much care in filename parsing and would make filenames
287  * visually if not formally ambiguous. Since there's no real-world use
288  * case, let's just forbid it.)
289  */
290  if (extensionname[0] == '-' || extensionname[namelen - 1] == '-')
291  ereport(ERROR,
292  (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
293  errmsg("invalid extension name: \"%s\"", extensionname),
294  errdetail("Extension names must not begin or end with \"-\".")));
295 
296  /*
297  * No directory separators either (this is sufficient to prevent ".."
298  * style attacks).
299  */
300  if (first_dir_separator(extensionname) != NULL)
301  ereport(ERROR,
302  (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
303  errmsg("invalid extension name: \"%s\"", extensionname),
304  errdetail("Extension names must not contain directory separator characters.")));
305 }
306 
307 static void
308 check_valid_version_name(const char *versionname)
309 {
310  int namelen = strlen(versionname);
311 
312  /*
313  * Disallow empty names (we could possibly allow this, but there seems
314  * little point).
315  */
316  if (namelen == 0)
317  ereport(ERROR,
318  (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
319  errmsg("invalid extension version name: \"%s\"", versionname),
320  errdetail("Version names must not be empty.")));
321 
322  /*
323  * No double dashes, since that would make script filenames ambiguous.
324  */
325  if (strstr(versionname, "--"))
326  ereport(ERROR,
327  (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
328  errmsg("invalid extension version name: \"%s\"", versionname),
329  errdetail("Version names must not contain \"--\".")));
330 
331  /*
332  * No leading or trailing dash either.
333  */
334  if (versionname[0] == '-' || versionname[namelen - 1] == '-')
335  ereport(ERROR,
336  (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
337  errmsg("invalid extension version name: \"%s\"", versionname),
338  errdetail("Version names must not begin or end with \"-\".")));
339 
340  /*
341  * No directory separators either (this is sufficient to prevent ".."
342  * style attacks).
343  */
344  if (first_dir_separator(versionname) != NULL)
345  ereport(ERROR,
346  (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
347  errmsg("invalid extension version name: \"%s\"", versionname),
348  errdetail("Version names must not contain directory separator characters.")));
349 }
350 
351 /*
352  * Utility functions to handle extension-related path names
353  */
354 static bool
356 {
357  const char *extension = strrchr(filename, '.');
358 
359  return (extension != NULL) && (strcmp(extension, ".control") == 0);
360 }
361 
362 static bool
364 {
365  const char *extension = strrchr(filename, '.');
366 
367  return (extension != NULL) && (strcmp(extension, ".sql") == 0);
368 }
369 
370 static char *
372 {
373  char sharepath[MAXPGPATH];
374  char *result;
375 
376  get_share_path(my_exec_path, sharepath);
377  result = (char *) palloc(MAXPGPATH);
378  snprintf(result, MAXPGPATH, "%s/extension", sharepath);
379 
380  return result;
381 }
382 
383 static char *
384 get_extension_control_filename(const char *extname)
385 {
386  char sharepath[MAXPGPATH];
387  char *result;
388 
389  get_share_path(my_exec_path, sharepath);
390  result = (char *) palloc(MAXPGPATH);
391  snprintf(result, MAXPGPATH, "%s/extension/%s.control",
392  sharepath, extname);
393 
394  return result;
395 }
396 
397 static char *
399 {
400  char sharepath[MAXPGPATH];
401  char *result;
402 
403  /*
404  * The directory parameter can be omitted, absolute, or relative to the
405  * installation's share directory.
406  */
407  if (!control->directory)
409 
410  if (is_absolute_path(control->directory))
411  return pstrdup(control->directory);
412 
413  get_share_path(my_exec_path, sharepath);
414  result = (char *) palloc(MAXPGPATH);
415  snprintf(result, MAXPGPATH, "%s/%s", sharepath, control->directory);
416 
417  return result;
418 }
419 
420 static char *
422  const char *version)
423 {
424  char *result;
425  char *scriptdir;
426 
427  scriptdir = get_extension_script_directory(control);
428 
429  result = (char *) palloc(MAXPGPATH);
430  snprintf(result, MAXPGPATH, "%s/%s--%s.control",
431  scriptdir, control->name, version);
432 
433  pfree(scriptdir);
434 
435  return result;
436 }
437 
438 static char *
440  const char *from_version, const char *version)
441 {
442  char *result;
443  char *scriptdir;
444 
445  scriptdir = get_extension_script_directory(control);
446 
447  result = (char *) palloc(MAXPGPATH);
448  if (from_version)
449  snprintf(result, MAXPGPATH, "%s/%s--%s--%s.sql",
450  scriptdir, control->name, from_version, version);
451  else
452  snprintf(result, MAXPGPATH, "%s/%s--%s.sql",
453  scriptdir, control->name, version);
454 
455  pfree(scriptdir);
456 
457  return result;
458 }
459 
460 
461 /*
462  * Parse contents of primary or auxiliary control file, and fill in
463  * fields of *control. We parse primary file if version == NULL,
464  * else the optional auxiliary file for that version.
465  *
466  * Control files are supposed to be very short, half a dozen lines,
467  * so we don't worry about memory allocation risks here. Also we don't
468  * worry about what encoding it's in; all values are expected to be ASCII.
469  */
470 static void
472  const char *version)
473 {
474  char *filename;
475  FILE *file;
476  ConfigVariable *item,
477  *head = NULL,
478  *tail = NULL;
479 
480  /*
481  * Locate the file to read. Auxiliary files are optional.
482  */
483  if (version)
484  filename = get_extension_aux_control_filename(control, version);
485  else
487 
488  if ((file = AllocateFile(filename, "r")) == NULL)
489  {
490  if (errno == ENOENT)
491  {
492  /* no complaint for missing auxiliary file */
493  if (version)
494  {
495  pfree(filename);
496  return;
497  }
498 
499  /* missing control file indicates extension is not installed */
500  ereport(ERROR,
501  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
502  errmsg("extension \"%s\" is not available", control->name),
503  errdetail("Could not open extension control file \"%s\": %m.",
504  filename),
505  errhint("The extension must first be installed on the system where PostgreSQL is running.")));
506  }
507  ereport(ERROR,
509  errmsg("could not open extension control file \"%s\": %m",
510  filename)));
511  }
512 
513  /*
514  * Parse the file content, using GUC's file parsing code. We need not
515  * check the return value since any errors will be thrown at ERROR level.
516  */
517  (void) ParseConfigFp(file, filename, 0, ERROR, &head, &tail);
518 
519  FreeFile(file);
520 
521  /*
522  * Convert the ConfigVariable list into ExtensionControlFile entries.
523  */
524  for (item = head; item != NULL; item = item->next)
525  {
526  if (strcmp(item->name, "directory") == 0)
527  {
528  if (version)
529  ereport(ERROR,
530  (errcode(ERRCODE_SYNTAX_ERROR),
531  errmsg("parameter \"%s\" cannot be set in a secondary extension control file",
532  item->name)));
533 
534  control->directory = pstrdup(item->value);
535  }
536  else if (strcmp(item->name, "default_version") == 0)
537  {
538  if (version)
539  ereport(ERROR,
540  (errcode(ERRCODE_SYNTAX_ERROR),
541  errmsg("parameter \"%s\" cannot be set in a secondary extension control file",
542  item->name)));
543 
544  control->default_version = pstrdup(item->value);
545  }
546  else if (strcmp(item->name, "module_pathname") == 0)
547  {
548  control->module_pathname = pstrdup(item->value);
549  }
550  else if (strcmp(item->name, "comment") == 0)
551  {
552  control->comment = pstrdup(item->value);
553  }
554  else if (strcmp(item->name, "schema") == 0)
555  {
556  control->schema = pstrdup(item->value);
557  }
558  else if (strcmp(item->name, "relocatable") == 0)
559  {
560  if (!parse_bool(item->value, &control->relocatable))
561  ereport(ERROR,
562  (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
563  errmsg("parameter \"%s\" requires a Boolean value",
564  item->name)));
565  }
566  else if (strcmp(item->name, "superuser") == 0)
567  {
568  if (!parse_bool(item->value, &control->superuser))
569  ereport(ERROR,
570  (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
571  errmsg("parameter \"%s\" requires a Boolean value",
572  item->name)));
573  }
574  else if (strcmp(item->name, "trusted") == 0)
575  {
576  if (!parse_bool(item->value, &control->trusted))
577  ereport(ERROR,
578  (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
579  errmsg("parameter \"%s\" requires a Boolean value",
580  item->name)));
581  }
582  else if (strcmp(item->name, "encoding") == 0)
583  {
584  control->encoding = pg_valid_server_encoding(item->value);
585  if (control->encoding < 0)
586  ereport(ERROR,
587  (errcode(ERRCODE_UNDEFINED_OBJECT),
588  errmsg("\"%s\" is not a valid encoding name",
589  item->value)));
590  }
591  else if (strcmp(item->name, "requires") == 0)
592  {
593  /* Need a modifiable copy of string */
594  char *rawnames = pstrdup(item->value);
595 
596  /* Parse string into list of identifiers */
597  if (!SplitIdentifierString(rawnames, ',', &control->requires))
598  {
599  /* syntax error in name list */
600  ereport(ERROR,
601  (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
602  errmsg("parameter \"%s\" must be a list of extension names",
603  item->name)));
604  }
605  }
606  else
607  ereport(ERROR,
608  (errcode(ERRCODE_SYNTAX_ERROR),
609  errmsg("unrecognized parameter \"%s\" in file \"%s\"",
610  item->name, filename)));
611  }
612 
613  FreeConfigVariables(head);
614 
615  if (control->relocatable && control->schema != NULL)
616  ereport(ERROR,
617  (errcode(ERRCODE_SYNTAX_ERROR),
618  errmsg("parameter \"schema\" cannot be specified when \"relocatable\" is true")));
619 
620  pfree(filename);
621 }
622 
623 /*
624  * Read the primary control file for the specified extension.
625  */
626 static ExtensionControlFile *
627 read_extension_control_file(const char *extname)
628 {
629  ExtensionControlFile *control;
630 
631  /*
632  * Set up default values. Pointer fields are initially null.
633  */
634  control = (ExtensionControlFile *) palloc0(sizeof(ExtensionControlFile));
635  control->name = pstrdup(extname);
636  control->relocatable = false;
637  control->superuser = true;
638  control->trusted = false;
639  control->encoding = -1;
640 
641  /*
642  * Parse the primary control file.
643  */
644  parse_extension_control_file(control, NULL);
645 
646  return control;
647 }
648 
649 /*
650  * Read the auxiliary control file for the specified extension and version.
651  *
652  * Returns a new modified ExtensionControlFile struct; the original struct
653  * (reflecting just the primary control file) is not modified.
654  */
655 static ExtensionControlFile *
657  const char *version)
658 {
659  ExtensionControlFile *acontrol;
660 
661  /*
662  * Flat-copy the struct. Pointer fields share values with original.
663  */
664  acontrol = (ExtensionControlFile *) palloc(sizeof(ExtensionControlFile));
665  memcpy(acontrol, pcontrol, sizeof(ExtensionControlFile));
666 
667  /*
668  * Parse the auxiliary control file, overwriting struct fields
669  */
670  parse_extension_control_file(acontrol, version);
671 
672  return acontrol;
673 }
674 
675 /*
676  * Read an SQL script file into a string, and convert to database encoding
677  */
678 static char *
680  const char *filename)
681 {
682  int src_encoding;
683  char *src_str;
684  char *dest_str;
685  int len;
686 
687  src_str = read_whole_file(filename, &len);
688 
689  /* use database encoding if not given */
690  if (control->encoding < 0)
691  src_encoding = GetDatabaseEncoding();
692  else
693  src_encoding = control->encoding;
694 
695  /* make sure that source string is valid in the expected encoding */
696  (void) pg_verify_mbstr(src_encoding, src_str, len, false);
697 
698  /*
699  * Convert the encoding to the database encoding. read_whole_file
700  * null-terminated the string, so if no conversion happens the string is
701  * valid as is.
702  */
703  dest_str = pg_any_to_server(src_str, len, src_encoding);
704 
705  return dest_str;
706 }
707 
708 /*
709  * Execute given SQL string.
710  *
711  * Note: it's tempting to just use SPI to execute the string, but that does
712  * not work very well. The really serious problem is that SPI will parse,
713  * analyze, and plan the whole string before executing any of it; of course
714  * this fails if there are any plannable statements referring to objects
715  * created earlier in the script. A lesser annoyance is that SPI insists
716  * on printing the whole string as errcontext in case of any error, and that
717  * could be very long.
718  */
719 static void
720 execute_sql_string(const char *sql)
721 {
722  List *raw_parsetree_list;
724  ListCell *lc1;
725 
726  /*
727  * Parse the SQL string into a list of raw parse trees.
728  */
729  raw_parsetree_list = pg_parse_query(sql);
730 
731  /* All output from SELECTs goes to the bit bucket */
733 
734  /*
735  * Do parse analysis, rule rewrite, planning, and execution for each raw
736  * parsetree. We must fully execute each query before beginning parse
737  * analysis on the next one, since there may be interdependencies.
738  */
739  foreach(lc1, raw_parsetree_list)
740  {
741  RawStmt *parsetree = lfirst_node(RawStmt, lc1);
742  MemoryContext per_parsetree_context,
743  oldcontext;
744  List *stmt_list;
745  ListCell *lc2;
746 
747  /*
748  * We do the work for each parsetree in a short-lived context, to
749  * limit the memory used when there are many commands in the string.
750  */
751  per_parsetree_context =
753  "execute_sql_string per-statement context",
755  oldcontext = MemoryContextSwitchTo(per_parsetree_context);
756 
757  /* Be sure parser can see any DDL done so far */
759 
760  stmt_list = pg_analyze_and_rewrite_fixedparams(parsetree,
761  sql,
762  NULL,
763  0,
764  NULL);
765  stmt_list = pg_plan_queries(stmt_list, sql, CURSOR_OPT_PARALLEL_OK, NULL);
766 
767  foreach(lc2, stmt_list)
768  {
769  PlannedStmt *stmt = lfirst_node(PlannedStmt, lc2);
770 
772 
774 
775  if (stmt->utilityStmt == NULL)
776  {
777  QueryDesc *qdesc;
778 
779  qdesc = CreateQueryDesc(stmt,
780  sql,
781  GetActiveSnapshot(), NULL,
782  dest, NULL, NULL, 0);
783 
784  ExecutorStart(qdesc, 0);
785  ExecutorRun(qdesc, ForwardScanDirection, 0, true);
786  ExecutorFinish(qdesc);
787  ExecutorEnd(qdesc);
788 
789  FreeQueryDesc(qdesc);
790  }
791  else
792  {
793  if (IsA(stmt->utilityStmt, TransactionStmt))
794  ereport(ERROR,
795  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
796  errmsg("transaction control statements are not allowed within an extension script")));
797 
798  ProcessUtility(stmt,
799  sql,
800  false,
802  NULL,
803  NULL,
804  dest,
805  NULL);
806  }
807 
809  }
810 
811  /* Clean up per-parsetree context. */
812  MemoryContextSwitchTo(oldcontext);
813  MemoryContextDelete(per_parsetree_context);
814  }
815 
816  /* Be sure to advance the command counter after the last script command */
818 }
819 
820 /*
821  * Policy function: is the given extension trusted for installation by a
822  * non-superuser?
823  *
824  * (Update the errhint logic below if you change this.)
825  */
826 static bool
828 {
829  AclResult aclresult;
830 
831  /* Never trust unless extension's control file says it's okay */
832  if (!control->trusted)
833  return false;
834  /* Allow if user has CREATE privilege on current database */
836  if (aclresult == ACLCHECK_OK)
837  return true;
838  return false;
839 }
840 
841 /*
842  * Execute the appropriate script file for installing or updating the extension
843  *
844  * If from_version isn't NULL, it's an update
845  */
846 static void
848  const char *from_version,
849  const char *version,
850  List *requiredSchemas,
851  const char *schemaName, Oid schemaOid)
852 {
853  bool switch_to_superuser = false;
854  char *filename;
855  Oid save_userid = 0;
856  int save_sec_context = 0;
857  int save_nestlevel;
858  StringInfoData pathbuf;
859  ListCell *lc;
860 
861  /*
862  * Enforce superuser-ness if appropriate. We postpone these checks until
863  * here so that the control flags are correctly associated with the right
864  * script(s) if they happen to be set in secondary control files.
865  */
866  if (control->superuser && !superuser())
867  {
868  if (extension_is_trusted(control))
869  switch_to_superuser = true;
870  else if (from_version == NULL)
871  ereport(ERROR,
872  (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
873  errmsg("permission denied to create extension \"%s\"",
874  control->name),
875  control->trusted
876  ? errhint("Must have CREATE privilege on current database to create this extension.")
877  : errhint("Must be superuser to create this extension.")));
878  else
879  ereport(ERROR,
880  (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
881  errmsg("permission denied to update extension \"%s\"",
882  control->name),
883  control->trusted
884  ? errhint("Must have CREATE privilege on current database to update this extension.")
885  : errhint("Must be superuser to update this extension.")));
886  }
887 
888  filename = get_extension_script_filename(control, from_version, version);
889 
890  if (from_version == NULL)
891  elog(DEBUG1, "executing extension script for \"%s\" version '%s'", control->name, version);
892  else
893  elog(DEBUG1, "executing extension script for \"%s\" update from version '%s' to '%s'", control->name, from_version, version);
894 
895  /*
896  * If installing a trusted extension on behalf of a non-superuser, become
897  * the bootstrap superuser. (This switch will be cleaned up automatically
898  * if the transaction aborts, as will the GUC changes below.)
899  */
900  if (switch_to_superuser)
901  {
902  GetUserIdAndSecContext(&save_userid, &save_sec_context);
903  SetUserIdAndSecContext(BOOTSTRAP_SUPERUSERID,
904  save_sec_context | SECURITY_LOCAL_USERID_CHANGE);
905  }
906 
907  /*
908  * Force client_min_messages and log_min_messages to be at least WARNING,
909  * so that we won't spam the user with useless NOTICE messages from common
910  * script actions like creating shell types.
911  *
912  * We use the equivalent of a function SET option to allow the setting to
913  * persist for exactly the duration of the script execution. guc.c also
914  * takes care of undoing the setting on error.
915  */
916  save_nestlevel = NewGUCNestLevel();
917 
919  (void) set_config_option("client_min_messages", "warning",
921  GUC_ACTION_SAVE, true, 0, false);
923  (void) set_config_option("log_min_messages", "warning",
925  GUC_ACTION_SAVE, true, 0, false);
926 
927  /*
928  * Similarly disable check_function_bodies, to ensure that SQL functions
929  * won't be parsed during creation.
930  */
932  (void) set_config_option("check_function_bodies", "off",
934  GUC_ACTION_SAVE, true, 0, false);
935 
936  /*
937  * Set up the search path to have the target schema first, making it be
938  * the default creation target namespace. Then add the schemas of any
939  * prerequisite extensions, unless they are in pg_catalog which would be
940  * searched anyway. (Listing pg_catalog explicitly in a non-first
941  * position would be bad for security.) Finally add pg_temp to ensure
942  * that temp objects can't take precedence over others.
943  *
944  * Note: it might look tempting to use PushOverrideSearchPath for this,
945  * but we cannot do that. We have to actually set the search_path GUC in
946  * case the extension script examines or changes it. In any case, the
947  * GUC_ACTION_SAVE method is just as convenient.
948  */
949  initStringInfo(&pathbuf);
950  appendStringInfoString(&pathbuf, quote_identifier(schemaName));
951  foreach(lc, requiredSchemas)
952  {
953  Oid reqschema = lfirst_oid(lc);
954  char *reqname = get_namespace_name(reqschema);
955 
956  if (reqname && strcmp(reqname, "pg_catalog") != 0)
957  appendStringInfo(&pathbuf, ", %s", quote_identifier(reqname));
958  }
959  appendStringInfoString(&pathbuf, ", pg_temp");
960 
961  (void) set_config_option("search_path", pathbuf.data,
963  GUC_ACTION_SAVE, true, 0, false);
964 
965  /*
966  * Set creating_extension and related variables so that
967  * recordDependencyOnCurrentExtension and other functions do the right
968  * things. On failure, ensure we reset these variables.
969  */
970  creating_extension = true;
971  CurrentExtensionObject = extensionOid;
972  PG_TRY();
973  {
974  char *c_sql = read_extension_script_file(control, filename);
975  Datum t_sql;
976 
977  /* We use various functions that want to operate on text datums */
978  t_sql = CStringGetTextDatum(c_sql);
979 
980  /*
981  * Reduce any lines beginning with "\echo" to empty. This allows
982  * scripts to contain messages telling people not to run them via
983  * psql, which has been found to be necessary due to old habits.
984  */
986  C_COLLATION_OID,
987  t_sql,
988  CStringGetTextDatum("^\\\\echo.*$"),
990  CStringGetTextDatum("ng"));
991 
992  /*
993  * If the script uses @extowner@, substitute the calling username.
994  */
995  if (strstr(c_sql, "@extowner@"))
996  {
997  Oid uid = switch_to_superuser ? save_userid : GetUserId();
998  const char *userName = GetUserNameFromId(uid, false);
999  const char *qUserName = quote_identifier(userName);
1000 
1002  C_COLLATION_OID,
1003  t_sql,
1004  CStringGetTextDatum("@extowner@"),
1005  CStringGetTextDatum(qUserName));
1006  }
1007 
1008  /*
1009  * If it's not relocatable, substitute the target schema name for
1010  * occurrences of @extschema@.
1011  *
1012  * For a relocatable extension, we needn't do this. There cannot be
1013  * any need for @extschema@, else it wouldn't be relocatable.
1014  */
1015  if (!control->relocatable)
1016  {
1017  const char *qSchemaName = quote_identifier(schemaName);
1018 
1020  C_COLLATION_OID,
1021  t_sql,
1022  CStringGetTextDatum("@extschema@"),
1023  CStringGetTextDatum(qSchemaName));
1024  }
1025 
1026  /*
1027  * If module_pathname was set in the control file, substitute its
1028  * value for occurrences of MODULE_PATHNAME.
1029  */
1030  if (control->module_pathname)
1031  {
1033  C_COLLATION_OID,
1034  t_sql,
1035  CStringGetTextDatum("MODULE_PATHNAME"),
1037  }
1038 
1039  /* And now back to C string */
1040  c_sql = text_to_cstring(DatumGetTextPP(t_sql));
1041 
1042  execute_sql_string(c_sql);
1043  }
1044  PG_FINALLY();
1045  {
1046  creating_extension = false;
1048  }
1049  PG_END_TRY();
1050 
1051  /*
1052  * Restore the GUC variables we set above.
1053  */
1054  AtEOXact_GUC(true, save_nestlevel);
1055 
1056  /*
1057  * Restore authentication state if needed.
1058  */
1059  if (switch_to_superuser)
1060  SetUserIdAndSecContext(save_userid, save_sec_context);
1061 }
1062 
1063 /*
1064  * Find or create an ExtensionVersionInfo for the specified version name
1065  *
1066  * Currently, we just use a List of the ExtensionVersionInfo's. Searching
1067  * for them therefore uses about O(N^2) time when there are N versions of
1068  * the extension. We could change the data structure to a hash table if
1069  * this ever becomes a bottleneck.
1070  */
1071 static ExtensionVersionInfo *
1072 get_ext_ver_info(const char *versionname, List **evi_list)
1073 {
1074  ExtensionVersionInfo *evi;
1075  ListCell *lc;
1076 
1077  foreach(lc, *evi_list)
1078  {
1079  evi = (ExtensionVersionInfo *) lfirst(lc);
1080  if (strcmp(evi->name, versionname) == 0)
1081  return evi;
1082  }
1083 
1085  evi->name = pstrdup(versionname);
1086  evi->reachable = NIL;
1087  evi->installable = false;
1088  /* initialize for later application of Dijkstra's algorithm */
1089  evi->distance_known = false;
1090  evi->distance = INT_MAX;
1091  evi->previous = NULL;
1092 
1093  *evi_list = lappend(*evi_list, evi);
1094 
1095  return evi;
1096 }
1097 
1098 /*
1099  * Locate the nearest unprocessed ExtensionVersionInfo
1100  *
1101  * This part of the algorithm is also about O(N^2). A priority queue would
1102  * make it much faster, but for now there's no need.
1103  */
1104 static ExtensionVersionInfo *
1106 {
1107  ExtensionVersionInfo *evi = NULL;
1108  ListCell *lc;
1109 
1110  foreach(lc, evi_list)
1111  {
1113 
1114  /* only vertices whose distance is still uncertain are candidates */
1115  if (evi2->distance_known)
1116  continue;
1117  /* remember the closest such vertex */
1118  if (evi == NULL ||
1119  evi->distance > evi2->distance)
1120  evi = evi2;
1121  }
1122 
1123  return evi;
1124 }
1125 
1126 /*
1127  * Obtain information about the set of update scripts available for the
1128  * specified extension. The result is a List of ExtensionVersionInfo
1129  * structs, each with a subsidiary list of the ExtensionVersionInfos for
1130  * the versions that can be reached in one step from that version.
1131  */
1132 static List *
1134 {
1135  List *evi_list = NIL;
1136  int extnamelen = strlen(control->name);
1137  char *location;
1138  DIR *dir;
1139  struct dirent *de;
1140 
1141  location = get_extension_script_directory(control);
1142  dir = AllocateDir(location);
1143  while ((de = ReadDir(dir, location)) != NULL)
1144  {
1145  char *vername;
1146  char *vername2;
1147  ExtensionVersionInfo *evi;
1148  ExtensionVersionInfo *evi2;
1149 
1150  /* must be a .sql file ... */
1152  continue;
1153 
1154  /* ... matching extension name followed by separator */
1155  if (strncmp(de->d_name, control->name, extnamelen) != 0 ||
1156  de->d_name[extnamelen] != '-' ||
1157  de->d_name[extnamelen + 1] != '-')
1158  continue;
1159 
1160  /* extract version name(s) from 'extname--something.sql' filename */
1161  vername = pstrdup(de->d_name + extnamelen + 2);
1162  *strrchr(vername, '.') = '\0';
1163  vername2 = strstr(vername, "--");
1164  if (!vername2)
1165  {
1166  /* It's an install, not update, script; record its version name */
1167  evi = get_ext_ver_info(vername, &evi_list);
1168  evi->installable = true;
1169  continue;
1170  }
1171  *vername2 = '\0'; /* terminate first version */
1172  vername2 += 2; /* and point to second */
1173 
1174  /* if there's a third --, it's bogus, ignore it */
1175  if (strstr(vername2, "--"))
1176  continue;
1177 
1178  /* Create ExtensionVersionInfos and link them together */
1179  evi = get_ext_ver_info(vername, &evi_list);
1180  evi2 = get_ext_ver_info(vername2, &evi_list);
1181  evi->reachable = lappend(evi->reachable, evi2);
1182  }
1183  FreeDir(dir);
1184 
1185  return evi_list;
1186 }
1187 
1188 /*
1189  * Given an initial and final version name, identify the sequence of update
1190  * scripts that have to be applied to perform that update.
1191  *
1192  * Result is a List of names of versions to transition through (the initial
1193  * version is *not* included).
1194  */
1195 static List *
1197  const char *oldVersion, const char *newVersion)
1198 {
1199  List *result;
1200  List *evi_list;
1201  ExtensionVersionInfo *evi_start;
1202  ExtensionVersionInfo *evi_target;
1203 
1204  /* Extract the version update graph from the script directory */
1205  evi_list = get_ext_ver_list(control);
1206 
1207  /* Initialize start and end vertices */
1208  evi_start = get_ext_ver_info(oldVersion, &evi_list);
1209  evi_target = get_ext_ver_info(newVersion, &evi_list);
1210 
1211  /* Find shortest path */
1212  result = find_update_path(evi_list, evi_start, evi_target, false, false);
1213 
1214  if (result == NIL)
1215  ereport(ERROR,
1216  (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
1217  errmsg("extension \"%s\" has no update path from version \"%s\" to version \"%s\"",
1218  control->name, oldVersion, newVersion)));
1219 
1220  return result;
1221 }
1222 
1223 /*
1224  * Apply Dijkstra's algorithm to find the shortest path from evi_start to
1225  * evi_target.
1226  *
1227  * If reject_indirect is true, ignore paths that go through installable
1228  * versions. This saves work when the caller will consider starting from
1229  * all installable versions anyway.
1230  *
1231  * If reinitialize is false, assume the ExtensionVersionInfo list has not
1232  * been used for this before, and the initialization done by get_ext_ver_info
1233  * is still good. Otherwise, reinitialize all transient fields used here.
1234  *
1235  * Result is a List of names of versions to transition through (the initial
1236  * version is *not* included). Returns NIL if no such path.
1237  */
1238 static List *
1240  ExtensionVersionInfo *evi_start,
1241  ExtensionVersionInfo *evi_target,
1242  bool reject_indirect,
1243  bool reinitialize)
1244 {
1245  List *result;
1246  ExtensionVersionInfo *evi;
1247  ListCell *lc;
1248 
1249  /* Caller error if start == target */
1250  Assert(evi_start != evi_target);
1251  /* Caller error if reject_indirect and target is installable */
1252  Assert(!(reject_indirect && evi_target->installable));
1253 
1254  if (reinitialize)
1255  {
1256  foreach(lc, evi_list)
1257  {
1258  evi = (ExtensionVersionInfo *) lfirst(lc);
1259  evi->distance_known = false;
1260  evi->distance = INT_MAX;
1261  evi->previous = NULL;
1262  }
1263  }
1264 
1265  evi_start->distance = 0;
1266 
1267  while ((evi = get_nearest_unprocessed_vertex(evi_list)) != NULL)
1268  {
1269  if (evi->distance == INT_MAX)
1270  break; /* all remaining vertices are unreachable */
1271  evi->distance_known = true;
1272  if (evi == evi_target)
1273  break; /* found shortest path to target */
1274  foreach(lc, evi->reachable)
1275  {
1277  int newdist;
1278 
1279  /* if reject_indirect, treat installable versions as unreachable */
1280  if (reject_indirect && evi2->installable)
1281  continue;
1282  newdist = evi->distance + 1;
1283  if (newdist < evi2->distance)
1284  {
1285  evi2->distance = newdist;
1286  evi2->previous = evi;
1287  }
1288  else if (newdist == evi2->distance &&
1289  evi2->previous != NULL &&
1290  strcmp(evi->name, evi2->previous->name) < 0)
1291  {
1292  /*
1293  * Break ties in favor of the version name that comes first
1294  * according to strcmp(). This behavior is undocumented and
1295  * users shouldn't rely on it. We do it just to ensure that
1296  * if there is a tie, the update path that is chosen does not
1297  * depend on random factors like the order in which directory
1298  * entries get visited.
1299  */
1300  evi2->previous = evi;
1301  }
1302  }
1303  }
1304 
1305  /* Return NIL if target is not reachable from start */
1306  if (!evi_target->distance_known)
1307  return NIL;
1308 
1309  /* Build and return list of version names representing the update path */
1310  result = NIL;
1311  for (evi = evi_target; evi != evi_start; evi = evi->previous)
1312  result = lcons(evi->name, result);
1313 
1314  return result;
1315 }
1316 
1317 /*
1318  * Given a target version that is not directly installable, find the
1319  * best installation sequence starting from a directly-installable version.
1320  *
1321  * evi_list: previously-collected version update graph
1322  * evi_target: member of that list that we want to reach
1323  *
1324  * Returns the best starting-point version, or NULL if there is none.
1325  * On success, *best_path is set to the path from the start point.
1326  *
1327  * If there's more than one possible start point, prefer shorter update paths,
1328  * and break any ties arbitrarily on the basis of strcmp'ing the starting
1329  * versions' names.
1330  */
1331 static ExtensionVersionInfo *
1333  List **best_path)
1334 {
1335  ExtensionVersionInfo *evi_start = NULL;
1336  ListCell *lc;
1337 
1338  *best_path = NIL;
1339 
1340  /*
1341  * We don't expect to be called for an installable target, but if we are,
1342  * the answer is easy: just start from there, with an empty update path.
1343  */
1344  if (evi_target->installable)
1345  return evi_target;
1346 
1347  /* Consider all installable versions as start points */
1348  foreach(lc, evi_list)
1349  {
1351  List *path;
1352 
1353  if (!evi1->installable)
1354  continue;
1355 
1356  /*
1357  * Find shortest path from evi1 to evi_target; but no need to consider
1358  * paths going through other installable versions.
1359  */
1360  path = find_update_path(evi_list, evi1, evi_target, true, true);
1361  if (path == NIL)
1362  continue;
1363 
1364  /* Remember best path */
1365  if (evi_start == NULL ||
1366  list_length(path) < list_length(*best_path) ||
1367  (list_length(path) == list_length(*best_path) &&
1368  strcmp(evi_start->name, evi1->name) < 0))
1369  {
1370  evi_start = evi1;
1371  *best_path = path;
1372  }
1373  }
1374 
1375  return evi_start;
1376 }
1377 
1378 /*
1379  * CREATE EXTENSION worker
1380  *
1381  * When CASCADE is specified, CreateExtensionInternal() recurses if required
1382  * extensions need to be installed. To sanely handle cyclic dependencies,
1383  * the "parents" list contains a list of names of extensions already being
1384  * installed, allowing us to error out if we recurse to one of those.
1385  */
1386 static ObjectAddress
1387 CreateExtensionInternal(char *extensionName,
1388  char *schemaName,
1389  const char *versionName,
1390  bool cascade,
1391  List *parents,
1392  bool is_create)
1393 {
1394  char *origSchemaName = schemaName;
1395  Oid schemaOid = InvalidOid;
1396  Oid extowner = GetUserId();
1397  ExtensionControlFile *pcontrol;
1398  ExtensionControlFile *control;
1399  char *filename;
1400  struct stat fst;
1401  List *updateVersions;
1402  List *requiredExtensions;
1403  List *requiredSchemas;
1404  Oid extensionOid;
1405  ObjectAddress address;
1406  ListCell *lc;
1407 
1408  /*
1409  * Read the primary control file. Note we assume that it does not contain
1410  * any non-ASCII data, so there is no need to worry about encoding at this
1411  * point.
1412  */
1413  pcontrol = read_extension_control_file(extensionName);
1414 
1415  /*
1416  * Determine the version to install
1417  */
1418  if (versionName == NULL)
1419  {
1420  if (pcontrol->default_version)
1421  versionName = pcontrol->default_version;
1422  else
1423  ereport(ERROR,
1424  (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
1425  errmsg("version to install must be specified")));
1426  }
1427  check_valid_version_name(versionName);
1428 
1429  /*
1430  * Figure out which script(s) we need to run to install the desired
1431  * version of the extension. If we do not have a script that directly
1432  * does what is needed, we try to find a sequence of update scripts that
1433  * will get us there.
1434  */
1435  filename = get_extension_script_filename(pcontrol, NULL, versionName);
1436  if (stat(filename, &fst) == 0)
1437  {
1438  /* Easy, no extra scripts */
1439  updateVersions = NIL;
1440  }
1441  else
1442  {
1443  /* Look for best way to install this version */
1444  List *evi_list;
1445  ExtensionVersionInfo *evi_start;
1446  ExtensionVersionInfo *evi_target;
1447 
1448  /* Extract the version update graph from the script directory */
1449  evi_list = get_ext_ver_list(pcontrol);
1450 
1451  /* Identify the target version */
1452  evi_target = get_ext_ver_info(versionName, &evi_list);
1453 
1454  /* Identify best path to reach target */
1455  evi_start = find_install_path(evi_list, evi_target,
1456  &updateVersions);
1457 
1458  /* Fail if no path ... */
1459  if (evi_start == NULL)
1460  ereport(ERROR,
1461  (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
1462  errmsg("extension \"%s\" has no installation script nor update path for version \"%s\"",
1463  pcontrol->name, versionName)));
1464 
1465  /* Otherwise, install best starting point and then upgrade */
1466  versionName = evi_start->name;
1467  }
1468 
1469  /*
1470  * Fetch control parameters for installation target version
1471  */
1472  control = read_extension_aux_control_file(pcontrol, versionName);
1473 
1474  /*
1475  * Determine the target schema to install the extension into
1476  */
1477  if (schemaName)
1478  {
1479  /* If the user is giving us the schema name, it must exist already. */
1480  schemaOid = get_namespace_oid(schemaName, false);
1481  }
1482 
1483  if (control->schema != NULL)
1484  {
1485  /*
1486  * The extension is not relocatable and the author gave us a schema
1487  * for it.
1488  *
1489  * Unless CASCADE parameter was given, it's an error to give a schema
1490  * different from control->schema if control->schema is specified.
1491  */
1492  if (schemaName && strcmp(control->schema, schemaName) != 0 &&
1493  !cascade)
1494  ereport(ERROR,
1495  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1496  errmsg("extension \"%s\" must be installed in schema \"%s\"",
1497  control->name,
1498  control->schema)));
1499 
1500  /* Always use the schema from control file for current extension. */
1501  schemaName = control->schema;
1502 
1503  /* Find or create the schema in case it does not exist. */
1504  schemaOid = get_namespace_oid(schemaName, true);
1505 
1506  if (!OidIsValid(schemaOid))
1507  {
1509 
1510  csstmt->schemaname = schemaName;
1511  csstmt->authrole = NULL; /* will be created by current user */
1512  csstmt->schemaElts = NIL;
1513  csstmt->if_not_exists = false;
1514  CreateSchemaCommand(csstmt, "(generated CREATE SCHEMA command)",
1515  -1, -1);
1516 
1517  /*
1518  * CreateSchemaCommand includes CommandCounterIncrement, so new
1519  * schema is now visible.
1520  */
1521  schemaOid = get_namespace_oid(schemaName, false);
1522  }
1523  }
1524  else if (!OidIsValid(schemaOid))
1525  {
1526  /*
1527  * Neither user nor author of the extension specified schema; use the
1528  * current default creation namespace, which is the first explicit
1529  * entry in the search_path.
1530  */
1531  List *search_path = fetch_search_path(false);
1532 
1533  if (search_path == NIL) /* nothing valid in search_path? */
1534  ereport(ERROR,
1535  (errcode(ERRCODE_UNDEFINED_SCHEMA),
1536  errmsg("no schema has been selected to create in")));
1537  schemaOid = linitial_oid(search_path);
1538  schemaName = get_namespace_name(schemaOid);
1539  if (schemaName == NULL) /* recently-deleted namespace? */
1540  ereport(ERROR,
1541  (errcode(ERRCODE_UNDEFINED_SCHEMA),
1542  errmsg("no schema has been selected to create in")));
1543 
1544  list_free(search_path);
1545  }
1546 
1547  /*
1548  * Make note if a temporary namespace has been accessed in this
1549  * transaction.
1550  */
1551  if (isTempNamespace(schemaOid))
1553 
1554  /*
1555  * We don't check creation rights on the target namespace here. If the
1556  * extension script actually creates any objects there, it will fail if
1557  * the user doesn't have such permissions. But there are cases such as
1558  * procedural languages where it's convenient to set schema = pg_catalog
1559  * yet we don't want to restrict the command to users with ACL_CREATE for
1560  * pg_catalog.
1561  */
1562 
1563  /*
1564  * Look up the prerequisite extensions, install them if necessary, and
1565  * build lists of their OIDs and the OIDs of their target schemas.
1566  */
1567  requiredExtensions = NIL;
1568  requiredSchemas = NIL;
1569  foreach(lc, control->requires)
1570  {
1571  char *curreq = (char *) lfirst(lc);
1572  Oid reqext;
1573  Oid reqschema;
1574 
1575  reqext = get_required_extension(curreq,
1576  extensionName,
1577  origSchemaName,
1578  cascade,
1579  parents,
1580  is_create);
1581  reqschema = get_extension_schema(reqext);
1582  requiredExtensions = lappend_oid(requiredExtensions, reqext);
1583  requiredSchemas = lappend_oid(requiredSchemas, reqschema);
1584  }
1585 
1586  /*
1587  * Insert new tuple into pg_extension, and create dependency entries.
1588  */
1589  address = InsertExtensionTuple(control->name, extowner,
1590  schemaOid, control->relocatable,
1591  versionName,
1592  PointerGetDatum(NULL),
1593  PointerGetDatum(NULL),
1594  requiredExtensions);
1595  extensionOid = address.objectId;
1596 
1597  /*
1598  * Apply any control-file comment on extension
1599  */
1600  if (control->comment != NULL)
1601  CreateComments(extensionOid, ExtensionRelationId, 0, control->comment);
1602 
1603  /*
1604  * Execute the installation script file
1605  */
1606  execute_extension_script(extensionOid, control,
1607  NULL, versionName,
1608  requiredSchemas,
1609  schemaName, schemaOid);
1610 
1611  /*
1612  * If additional update scripts have to be executed, apply the updates as
1613  * though a series of ALTER EXTENSION UPDATE commands were given
1614  */
1615  ApplyExtensionUpdates(extensionOid, pcontrol,
1616  versionName, updateVersions,
1617  origSchemaName, cascade, is_create);
1618 
1619  return address;
1620 }
1621 
1622 /*
1623  * Get the OID of an extension listed in "requires", possibly creating it.
1624  */
1625 static Oid
1626 get_required_extension(char *reqExtensionName,
1627  char *extensionName,
1628  char *origSchemaName,
1629  bool cascade,
1630  List *parents,
1631  bool is_create)
1632 {
1633  Oid reqExtensionOid;
1634 
1635  reqExtensionOid = get_extension_oid(reqExtensionName, true);
1636  if (!OidIsValid(reqExtensionOid))
1637  {
1638  if (cascade)
1639  {
1640  /* Must install it. */
1641  ObjectAddress addr;
1642  List *cascade_parents;
1643  ListCell *lc;
1644 
1645  /* Check extension name validity before trying to cascade. */
1646  check_valid_extension_name(reqExtensionName);
1647 
1648  /* Check for cyclic dependency between extensions. */
1649  foreach(lc, parents)
1650  {
1651  char *pname = (char *) lfirst(lc);
1652 
1653  if (strcmp(pname, reqExtensionName) == 0)
1654  ereport(ERROR,
1655  (errcode(ERRCODE_INVALID_RECURSION),
1656  errmsg("cyclic dependency detected between extensions \"%s\" and \"%s\"",
1657  reqExtensionName, extensionName)));
1658  }
1659 
1660  ereport(NOTICE,
1661  (errmsg("installing required extension \"%s\"",
1662  reqExtensionName)));
1663 
1664  /* Add current extension to list of parents to pass down. */
1665  cascade_parents = lappend(list_copy(parents), extensionName);
1666 
1667  /*
1668  * Create the required extension. We propagate the SCHEMA option
1669  * if any, and CASCADE, but no other options.
1670  */
1671  addr = CreateExtensionInternal(reqExtensionName,
1672  origSchemaName,
1673  NULL,
1674  cascade,
1675  cascade_parents,
1676  is_create);
1677 
1678  /* Get its newly-assigned OID. */
1679  reqExtensionOid = addr.objectId;
1680  }
1681  else
1682  ereport(ERROR,
1683  (errcode(ERRCODE_UNDEFINED_OBJECT),
1684  errmsg("required extension \"%s\" is not installed",
1685  reqExtensionName),
1686  is_create ?
1687  errhint("Use CREATE EXTENSION ... CASCADE to install required extensions too.") : 0));
1688  }
1689 
1690  return reqExtensionOid;
1691 }
1692 
1693 /*
1694  * CREATE EXTENSION
1695  */
1698 {
1699  DefElem *d_schema = NULL;
1700  DefElem *d_new_version = NULL;
1701  DefElem *d_cascade = NULL;
1702  char *schemaName = NULL;
1703  char *versionName = NULL;
1704  bool cascade = false;
1705  ListCell *lc;
1706 
1707  /* Check extension name validity before any filesystem access */
1709 
1710  /*
1711  * Check for duplicate extension name. The unique index on
1712  * pg_extension.extname would catch this anyway, and serves as a backstop
1713  * in case of race conditions; but this is a friendlier error message, and
1714  * besides we need a check to support IF NOT EXISTS.
1715  */
1716  if (get_extension_oid(stmt->extname, true) != InvalidOid)
1717  {
1718  if (stmt->if_not_exists)
1719  {
1720  ereport(NOTICE,
1722  errmsg("extension \"%s\" already exists, skipping",
1723  stmt->extname)));
1724  return InvalidObjectAddress;
1725  }
1726  else
1727  ereport(ERROR,
1729  errmsg("extension \"%s\" already exists",
1730  stmt->extname)));
1731  }
1732 
1733  /*
1734  * We use global variables to track the extension being created, so we can
1735  * create only one extension at the same time.
1736  */
1737  if (creating_extension)
1738  ereport(ERROR,
1739  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1740  errmsg("nested CREATE EXTENSION is not supported")));
1741 
1742  /* Deconstruct the statement option list */
1743  foreach(lc, stmt->options)
1744  {
1745  DefElem *defel = (DefElem *) lfirst(lc);
1746 
1747  if (strcmp(defel->defname, "schema") == 0)
1748  {
1749  if (d_schema)
1750  errorConflictingDefElem(defel, pstate);
1751  d_schema = defel;
1752  schemaName = defGetString(d_schema);
1753  }
1754  else if (strcmp(defel->defname, "new_version") == 0)
1755  {
1756  if (d_new_version)
1757  errorConflictingDefElem(defel, pstate);
1758  d_new_version = defel;
1759  versionName = defGetString(d_new_version);
1760  }
1761  else if (strcmp(defel->defname, "cascade") == 0)
1762  {
1763  if (d_cascade)
1764  errorConflictingDefElem(defel, pstate);
1765  d_cascade = defel;
1766  cascade = defGetBoolean(d_cascade);
1767  }
1768  else
1769  elog(ERROR, "unrecognized option: %s", defel->defname);
1770  }
1771 
1772  /* Call CreateExtensionInternal to do the real work. */
1773  return CreateExtensionInternal(stmt->extname,
1774  schemaName,
1775  versionName,
1776  cascade,
1777  NIL,
1778  true);
1779 }
1780 
1781 /*
1782  * InsertExtensionTuple
1783  *
1784  * Insert the new pg_extension row, and create extension's dependency entries.
1785  * Return the OID assigned to the new row.
1786  *
1787  * This is exported for the benefit of pg_upgrade, which has to create a
1788  * pg_extension entry (and the extension-level dependencies) without
1789  * actually running the extension's script.
1790  *
1791  * extConfig and extCondition should be arrays or PointerGetDatum(NULL).
1792  * We declare them as plain Datum to avoid needing array.h in extension.h.
1793  */
1795 InsertExtensionTuple(const char *extName, Oid extOwner,
1796  Oid schemaOid, bool relocatable, const char *extVersion,
1797  Datum extConfig, Datum extCondition,
1798  List *requiredExtensions)
1799 {
1800  Oid extensionOid;
1801  Relation rel;
1802  Datum values[Natts_pg_extension];
1803  bool nulls[Natts_pg_extension];
1804  HeapTuple tuple;
1805  ObjectAddress myself;
1806  ObjectAddress nsp;
1807  ObjectAddresses *refobjs;
1808  ListCell *lc;
1809 
1810  /*
1811  * Build and insert the pg_extension tuple
1812  */
1813  rel = table_open(ExtensionRelationId, RowExclusiveLock);
1814 
1815  memset(values, 0, sizeof(values));
1816  memset(nulls, 0, sizeof(nulls));
1817 
1818  extensionOid = GetNewOidWithIndex(rel, ExtensionOidIndexId,
1819  Anum_pg_extension_oid);
1820  values[Anum_pg_extension_oid - 1] = ObjectIdGetDatum(extensionOid);
1821  values[Anum_pg_extension_extname - 1] =
1823  values[Anum_pg_extension_extowner - 1] = ObjectIdGetDatum(extOwner);
1824  values[Anum_pg_extension_extnamespace - 1] = ObjectIdGetDatum(schemaOid);
1825  values[Anum_pg_extension_extrelocatable - 1] = BoolGetDatum(relocatable);
1826  values[Anum_pg_extension_extversion - 1] = CStringGetTextDatum(extVersion);
1827 
1828  if (extConfig == PointerGetDatum(NULL))
1829  nulls[Anum_pg_extension_extconfig - 1] = true;
1830  else
1831  values[Anum_pg_extension_extconfig - 1] = extConfig;
1832 
1833  if (extCondition == PointerGetDatum(NULL))
1834  nulls[Anum_pg_extension_extcondition - 1] = true;
1835  else
1836  values[Anum_pg_extension_extcondition - 1] = extCondition;
1837 
1838  tuple = heap_form_tuple(rel->rd_att, values, nulls);
1839 
1840  CatalogTupleInsert(rel, tuple);
1841 
1842  heap_freetuple(tuple);
1844 
1845  /*
1846  * Record dependencies on owner, schema, and prerequisite extensions
1847  */
1848  recordDependencyOnOwner(ExtensionRelationId, extensionOid, extOwner);
1849 
1850  refobjs = new_object_addresses();
1851 
1852  ObjectAddressSet(myself, ExtensionRelationId, extensionOid);
1853 
1854  ObjectAddressSet(nsp, NamespaceRelationId, schemaOid);
1855  add_exact_object_address(&nsp, refobjs);
1856 
1857  foreach(lc, requiredExtensions)
1858  {
1859  Oid reqext = lfirst_oid(lc);
1860  ObjectAddress otherext;
1861 
1862  ObjectAddressSet(otherext, ExtensionRelationId, reqext);
1863  add_exact_object_address(&otherext, refobjs);
1864  }
1865 
1866  /* Record all of them (this includes duplicate elimination) */
1868  free_object_addresses(refobjs);
1869 
1870  /* Post creation hook for new extension */
1871  InvokeObjectPostCreateHook(ExtensionRelationId, extensionOid, 0);
1872 
1873  return myself;
1874 }
1875 
1876 /*
1877  * Guts of extension deletion.
1878  *
1879  * All we need do here is remove the pg_extension tuple itself. Everything
1880  * else is taken care of by the dependency infrastructure.
1881  */
1882 void
1884 {
1885  Relation rel;
1886  SysScanDesc scandesc;
1887  HeapTuple tuple;
1888  ScanKeyData entry[1];
1889 
1890  /*
1891  * Disallow deletion of any extension that's currently open for insertion;
1892  * else subsequent executions of recordDependencyOnCurrentExtension()
1893  * could create dangling pg_depend records that refer to a no-longer-valid
1894  * pg_extension OID. This is needed not so much because we think people
1895  * might write "DROP EXTENSION foo" in foo's own script files, as because
1896  * errors in dependency management in extension script files could give
1897  * rise to cases where an extension is dropped as a result of recursing
1898  * from some contained object. Because of that, we must test for the case
1899  * here, not at some higher level of the DROP EXTENSION command.
1900  */
1901  if (extId == CurrentExtensionObject)
1902  ereport(ERROR,
1903  (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
1904  errmsg("cannot drop extension \"%s\" because it is being modified",
1905  get_extension_name(extId))));
1906 
1907  rel = table_open(ExtensionRelationId, RowExclusiveLock);
1908 
1909  ScanKeyInit(&entry[0],
1910  Anum_pg_extension_oid,
1911  BTEqualStrategyNumber, F_OIDEQ,
1912  ObjectIdGetDatum(extId));
1913  scandesc = systable_beginscan(rel, ExtensionOidIndexId, true,
1914  NULL, 1, entry);
1915 
1916  tuple = systable_getnext(scandesc);
1917 
1918  /* We assume that there can be at most one matching tuple */
1919  if (HeapTupleIsValid(tuple))
1920  CatalogTupleDelete(rel, &tuple->t_self);
1921 
1922  systable_endscan(scandesc);
1923 
1925 }
1926 
1927 /*
1928  * This function lists the available extensions (one row per primary control
1929  * file in the control directory). We parse each control file and report the
1930  * interesting fields.
1931  *
1932  * The system view pg_available_extensions provides a user interface to this
1933  * SRF, adding information about whether the extensions are installed in the
1934  * current DB.
1935  */
1936 Datum
1938 {
1939  ReturnSetInfo *rsinfo = (ReturnSetInfo *) fcinfo->resultinfo;
1940  char *location;
1941  DIR *dir;
1942  struct dirent *de;
1943 
1944  /* Build tuplestore to hold the result rows */
1945  SetSingleFuncCall(fcinfo, 0);
1946 
1947  location = get_extension_control_directory();
1948  dir = AllocateDir(location);
1949 
1950  /*
1951  * If the control directory doesn't exist, we want to silently return an
1952  * empty set. Any other error will be reported by ReadDir.
1953  */
1954  if (dir == NULL && errno == ENOENT)
1955  {
1956  /* do nothing */
1957  }
1958  else
1959  {
1960  while ((de = ReadDir(dir, location)) != NULL)
1961  {
1962  ExtensionControlFile *control;
1963  char *extname;
1964  Datum values[3];
1965  bool nulls[3];
1966 
1967  if (!is_extension_control_filename(de->d_name))
1968  continue;
1969 
1970  /* extract extension name from 'name.control' filename */
1971  extname = pstrdup(de->d_name);
1972  *strrchr(extname, '.') = '\0';
1973 
1974  /* ignore it if it's an auxiliary control file */
1975  if (strstr(extname, "--"))
1976  continue;
1977 
1978  control = read_extension_control_file(extname);
1979 
1980  memset(values, 0, sizeof(values));
1981  memset(nulls, 0, sizeof(nulls));
1982 
1983  /* name */
1985  CStringGetDatum(control->name));
1986  /* default_version */
1987  if (control->default_version == NULL)
1988  nulls[1] = true;
1989  else
1991  /* comment */
1992  if (control->comment == NULL)
1993  nulls[2] = true;
1994  else
1995  values[2] = CStringGetTextDatum(control->comment);
1996 
1997  tuplestore_putvalues(rsinfo->setResult, rsinfo->setDesc,
1998  values, nulls);
1999  }
2000 
2001  FreeDir(dir);
2002  }
2003 
2004  return (Datum) 0;
2005 }
2006 
2007 /*
2008  * This function lists the available extension versions (one row per
2009  * extension installation script). For each version, we parse the related
2010  * control file(s) and report the interesting fields.
2011  *
2012  * The system view pg_available_extension_versions provides a user interface
2013  * to this SRF, adding information about which versions are installed in the
2014  * current DB.
2015  */
2016 Datum
2018 {
2019  ReturnSetInfo *rsinfo = (ReturnSetInfo *) fcinfo->resultinfo;
2020  char *location;
2021  DIR *dir;
2022  struct dirent *de;
2023 
2024  /* Build tuplestore to hold the result rows */
2025  SetSingleFuncCall(fcinfo, 0);
2026 
2027  location = get_extension_control_directory();
2028  dir = AllocateDir(location);
2029 
2030  /*
2031  * If the control directory doesn't exist, we want to silently return an
2032  * empty set. Any other error will be reported by ReadDir.
2033  */
2034  if (dir == NULL && errno == ENOENT)
2035  {
2036  /* do nothing */
2037  }
2038  else
2039  {
2040  while ((de = ReadDir(dir, location)) != NULL)
2041  {
2042  ExtensionControlFile *control;
2043  char *extname;
2044 
2045  if (!is_extension_control_filename(de->d_name))
2046  continue;
2047 
2048  /* extract extension name from 'name.control' filename */
2049  extname = pstrdup(de->d_name);
2050  *strrchr(extname, '.') = '\0';
2051 
2052  /* ignore it if it's an auxiliary control file */
2053  if (strstr(extname, "--"))
2054  continue;
2055 
2056  /* read the control file */
2057  control = read_extension_control_file(extname);
2058 
2059  /* scan extension's script directory for install scripts */
2061  rsinfo->setDesc);
2062  }
2063 
2064  FreeDir(dir);
2065  }
2066 
2067  return (Datum) 0;
2068 }
2069 
2070 /*
2071  * Inner loop for pg_available_extension_versions:
2072  * read versions of one extension, add rows to tupstore
2073  */
2074 static void
2076  Tuplestorestate *tupstore,
2077  TupleDesc tupdesc)
2078 {
2079  List *evi_list;
2080  ListCell *lc;
2081 
2082  /* Extract the version update graph from the script directory */
2083  evi_list = get_ext_ver_list(pcontrol);
2084 
2085  /* For each installable version ... */
2086  foreach(lc, evi_list)
2087  {
2089  ExtensionControlFile *control;
2090  Datum values[8];
2091  bool nulls[8];
2092  ListCell *lc2;
2093 
2094  if (!evi->installable)
2095  continue;
2096 
2097  /*
2098  * Fetch parameters for specific version (pcontrol is not changed)
2099  */
2100  control = read_extension_aux_control_file(pcontrol, evi->name);
2101 
2102  memset(values, 0, sizeof(values));
2103  memset(nulls, 0, sizeof(nulls));
2104 
2105  /* name */
2107  CStringGetDatum(control->name));
2108  /* version */
2109  values[1] = CStringGetTextDatum(evi->name);
2110  /* superuser */
2111  values[2] = BoolGetDatum(control->superuser);
2112  /* trusted */
2113  values[3] = BoolGetDatum(control->trusted);
2114  /* relocatable */
2115  values[4] = BoolGetDatum(control->relocatable);
2116  /* schema */
2117  if (control->schema == NULL)
2118  nulls[5] = true;
2119  else
2121  CStringGetDatum(control->schema));
2122  /* requires */
2123  if (control->requires == NIL)
2124  nulls[6] = true;
2125  else
2126  values[6] = convert_requires_to_datum(control->requires);
2127  /* comment */
2128  if (control->comment == NULL)
2129  nulls[7] = true;
2130  else
2131  values[7] = CStringGetTextDatum(control->comment);
2132 
2133  tuplestore_putvalues(tupstore, tupdesc, values, nulls);
2134 
2135  /*
2136  * Find all non-directly-installable versions that would be installed
2137  * starting from this version, and report them, inheriting the
2138  * parameters that aren't changed in updates from this version.
2139  */
2140  foreach(lc2, evi_list)
2141  {
2143  List *best_path;
2144 
2145  if (evi2->installable)
2146  continue;
2147  if (find_install_path(evi_list, evi2, &best_path) == evi)
2148  {
2149  /*
2150  * Fetch parameters for this version (pcontrol is not changed)
2151  */
2152  control = read_extension_aux_control_file(pcontrol, evi2->name);
2153 
2154  /* name stays the same */
2155  /* version */
2156  values[1] = CStringGetTextDatum(evi2->name);
2157  /* superuser */
2158  values[2] = BoolGetDatum(control->superuser);
2159  /* trusted */
2160  values[3] = BoolGetDatum(control->trusted);
2161  /* relocatable */
2162  values[4] = BoolGetDatum(control->relocatable);
2163  /* schema stays the same */
2164  /* requires */
2165  if (control->requires == NIL)
2166  nulls[6] = true;
2167  else
2168  {
2169  values[6] = convert_requires_to_datum(control->requires);
2170  nulls[6] = false;
2171  }
2172  /* comment stays the same */
2173 
2174  tuplestore_putvalues(tupstore, tupdesc, values, nulls);
2175  }
2176  }
2177  }
2178 }
2179 
2180 /*
2181  * Test whether the given extension exists (not whether it's installed)
2182  *
2183  * This checks for the existence of a matching control file in the extension
2184  * directory. That's not a bulletproof check, since the file might be
2185  * invalid, but this is only used for hints so it doesn't have to be 100%
2186  * right.
2187  */
2188 bool
2189 extension_file_exists(const char *extensionName)
2190 {
2191  bool result = false;
2192  char *location;
2193  DIR *dir;
2194  struct dirent *de;
2195 
2196  location = get_extension_control_directory();
2197  dir = AllocateDir(location);
2198 
2199  /*
2200  * If the control directory doesn't exist, we want to silently return
2201  * false. Any other error will be reported by ReadDir.
2202  */
2203  if (dir == NULL && errno == ENOENT)
2204  {
2205  /* do nothing */
2206  }
2207  else
2208  {
2209  while ((de = ReadDir(dir, location)) != NULL)
2210  {
2211  char *extname;
2212 
2214  continue;
2215 
2216  /* extract extension name from 'name.control' filename */
2217  extname = pstrdup(de->d_name);
2218  *strrchr(extname, '.') = '\0';
2219 
2220  /* ignore it if it's an auxiliary control file */
2221  if (strstr(extname, "--"))
2222  continue;
2223 
2224  /* done if it matches request */
2225  if (strcmp(extname, extensionName) == 0)
2226  {
2227  result = true;
2228  break;
2229  }
2230  }
2231 
2232  FreeDir(dir);
2233  }
2234 
2235  return result;
2236 }
2237 
2238 /*
2239  * Convert a list of extension names to a name[] Datum
2240  */
2241 static Datum
2243 {
2244  Datum *datums;
2245  int ndatums;
2246  ArrayType *a;
2247  ListCell *lc;
2248 
2249  ndatums = list_length(requires);
2250  datums = (Datum *) palloc(ndatums * sizeof(Datum));
2251  ndatums = 0;
2252  foreach(lc, requires)
2253  {
2254  char *curreq = (char *) lfirst(lc);
2255 
2256  datums[ndatums++] =
2258  }
2259  a = construct_array_builtin(datums, ndatums, NAMEOID);
2260  return PointerGetDatum(a);
2261 }
2262 
2263 /*
2264  * This function reports the version update paths that exist for the
2265  * specified extension.
2266  */
2267 Datum
2269 {
2270  Name extname = PG_GETARG_NAME(0);
2271  ReturnSetInfo *rsinfo = (ReturnSetInfo *) fcinfo->resultinfo;
2272  List *evi_list;
2273  ExtensionControlFile *control;
2274  ListCell *lc1;
2275 
2276  /* Check extension name validity before any filesystem access */
2278 
2279  /* Build tuplestore to hold the result rows */
2280  SetSingleFuncCall(fcinfo, 0);
2281 
2282  /* Read the extension's control file */
2283  control = read_extension_control_file(NameStr(*extname));
2284 
2285  /* Extract the version update graph from the script directory */
2286  evi_list = get_ext_ver_list(control);
2287 
2288  /* Iterate over all pairs of versions */
2289  foreach(lc1, evi_list)
2290  {
2292  ListCell *lc2;
2293 
2294  foreach(lc2, evi_list)
2295  {
2297  List *path;
2298  Datum values[3];
2299  bool nulls[3];
2300 
2301  if (evi1 == evi2)
2302  continue;
2303 
2304  /* Find shortest path from evi1 to evi2 */
2305  path = find_update_path(evi_list, evi1, evi2, false, true);
2306 
2307  /* Emit result row */
2308  memset(values, 0, sizeof(values));
2309  memset(nulls, 0, sizeof(nulls));
2310 
2311  /* source */
2312  values[0] = CStringGetTextDatum(evi1->name);
2313  /* target */
2314  values[1] = CStringGetTextDatum(evi2->name);
2315  /* path */
2316  if (path == NIL)
2317  nulls[2] = true;
2318  else
2319  {
2320  StringInfoData pathbuf;
2321  ListCell *lcv;
2322 
2323  initStringInfo(&pathbuf);
2324  /* The path doesn't include start vertex, but show it */
2325  appendStringInfoString(&pathbuf, evi1->name);
2326  foreach(lcv, path)
2327  {
2328  char *versionName = (char *) lfirst(lcv);
2329 
2330  appendStringInfoString(&pathbuf, "--");
2331  appendStringInfoString(&pathbuf, versionName);
2332  }
2333  values[2] = CStringGetTextDatum(pathbuf.data);
2334  pfree(pathbuf.data);
2335  }
2336 
2337  tuplestore_putvalues(rsinfo->setResult, rsinfo->setDesc,
2338  values, nulls);
2339  }
2340  }
2341 
2342  return (Datum) 0;
2343 }
2344 
2345 /*
2346  * pg_extension_config_dump
2347  *
2348  * Record information about a configuration table that belongs to an
2349  * extension being created, but whose contents should be dumped in whole
2350  * or in part during pg_dump.
2351  */
2352 Datum
2354 {
2355  Oid tableoid = PG_GETARG_OID(0);
2356  text *wherecond = PG_GETARG_TEXT_PP(1);
2357  char *tablename;
2358  Relation extRel;
2359  ScanKeyData key[1];
2360  SysScanDesc extScan;
2361  HeapTuple extTup;
2362  Datum arrayDatum;
2363  Datum elementDatum;
2364  int arrayLength;
2365  int arrayIndex;
2366  bool isnull;
2367  Datum repl_val[Natts_pg_extension];
2368  bool repl_null[Natts_pg_extension];
2369  bool repl_repl[Natts_pg_extension];
2370  ArrayType *a;
2371 
2372  /*
2373  * We only allow this to be called from an extension's SQL script. We
2374  * shouldn't need any permissions check beyond that.
2375  */
2376  if (!creating_extension)
2377  ereport(ERROR,
2378  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2379  errmsg("%s can only be called from an SQL script executed by CREATE EXTENSION",
2380  "pg_extension_config_dump()")));
2381 
2382  /*
2383  * Check that the table exists and is a member of the extension being
2384  * created. This ensures that we don't need to register an additional
2385  * dependency to protect the extconfig entry.
2386  */
2387  tablename = get_rel_name(tableoid);
2388  if (tablename == NULL)
2389  ereport(ERROR,
2391  errmsg("OID %u does not refer to a table", tableoid)));
2392  if (getExtensionOfObject(RelationRelationId, tableoid) !=
2394  ereport(ERROR,
2395  (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
2396  errmsg("table \"%s\" is not a member of the extension being created",
2397  tablename)));
2398 
2399  /*
2400  * Add the table OID and WHERE condition to the extension's extconfig and
2401  * extcondition arrays.
2402  *
2403  * If the table is already in extconfig, treat this as an update of the
2404  * WHERE condition.
2405  */
2406 
2407  /* Find the pg_extension tuple */
2408  extRel = table_open(ExtensionRelationId, RowExclusiveLock);
2409 
2410  ScanKeyInit(&key[0],
2411  Anum_pg_extension_oid,
2412  BTEqualStrategyNumber, F_OIDEQ,
2414 
2415  extScan = systable_beginscan(extRel, ExtensionOidIndexId, true,
2416  NULL, 1, key);
2417 
2418  extTup = systable_getnext(extScan);
2419 
2420  if (!HeapTupleIsValid(extTup)) /* should not happen */
2421  elog(ERROR, "could not find tuple for extension %u",
2423 
2424  memset(repl_val, 0, sizeof(repl_val));
2425  memset(repl_null, false, sizeof(repl_null));
2426  memset(repl_repl, false, sizeof(repl_repl));
2427 
2428  /* Build or modify the extconfig value */
2429  elementDatum = ObjectIdGetDatum(tableoid);
2430 
2431  arrayDatum = heap_getattr(extTup, Anum_pg_extension_extconfig,
2432  RelationGetDescr(extRel), &isnull);
2433  if (isnull)
2434  {
2435  /* Previously empty extconfig, so build 1-element array */
2436  arrayLength = 0;
2437  arrayIndex = 1;
2438 
2439  a = construct_array_builtin(&elementDatum, 1, OIDOID);
2440  }
2441  else
2442  {
2443  /* Modify or extend existing extconfig array */
2444  Oid *arrayData;
2445  int i;
2446 
2447  a = DatumGetArrayTypeP(arrayDatum);
2448 
2449  arrayLength = ARR_DIMS(a)[0];
2450  if (ARR_NDIM(a) != 1 ||
2451  ARR_LBOUND(a)[0] != 1 ||
2452  arrayLength < 0 ||
2453  ARR_HASNULL(a) ||
2454  ARR_ELEMTYPE(a) != OIDOID)
2455  elog(ERROR, "extconfig is not a 1-D Oid array");
2456  arrayData = (Oid *) ARR_DATA_PTR(a);
2457 
2458  arrayIndex = arrayLength + 1; /* set up to add after end */
2459 
2460  for (i = 0; i < arrayLength; i++)
2461  {
2462  if (arrayData[i] == tableoid)
2463  {
2464  arrayIndex = i + 1; /* replace this element instead */
2465  break;
2466  }
2467  }
2468 
2469  a = array_set(a, 1, &arrayIndex,
2470  elementDatum,
2471  false,
2472  -1 /* varlena array */ ,
2473  sizeof(Oid) /* OID's typlen */ ,
2474  true /* OID's typbyval */ ,
2475  TYPALIGN_INT /* OID's typalign */ );
2476  }
2477  repl_val[Anum_pg_extension_extconfig - 1] = PointerGetDatum(a);
2478  repl_repl[Anum_pg_extension_extconfig - 1] = true;
2479 
2480  /* Build or modify the extcondition value */
2481  elementDatum = PointerGetDatum(wherecond);
2482 
2483  arrayDatum = heap_getattr(extTup, Anum_pg_extension_extcondition,
2484  RelationGetDescr(extRel), &isnull);
2485  if (isnull)
2486  {
2487  if (arrayLength != 0)
2488  elog(ERROR, "extconfig and extcondition arrays do not match");
2489 
2490  a = construct_array_builtin(&elementDatum, 1, TEXTOID);
2491  }
2492  else
2493  {
2494  a = DatumGetArrayTypeP(arrayDatum);
2495 
2496  if (ARR_NDIM(a) != 1 ||
2497  ARR_LBOUND(a)[0] != 1 ||
2498  ARR_HASNULL(a) ||
2499  ARR_ELEMTYPE(a) != TEXTOID)
2500  elog(ERROR, "extcondition is not a 1-D text array");
2501  if (ARR_DIMS(a)[0] != arrayLength)
2502  elog(ERROR, "extconfig and extcondition arrays do not match");
2503 
2504  /* Add or replace at same index as in extconfig */
2505  a = array_set(a, 1, &arrayIndex,
2506  elementDatum,
2507  false,
2508  -1 /* varlena array */ ,
2509  -1 /* TEXT's typlen */ ,
2510  false /* TEXT's typbyval */ ,
2511  TYPALIGN_INT /* TEXT's typalign */ );
2512  }
2513  repl_val[Anum_pg_extension_extcondition - 1] = PointerGetDatum(a);
2514  repl_repl[Anum_pg_extension_extcondition - 1] = true;
2515 
2516  extTup = heap_modify_tuple(extTup, RelationGetDescr(extRel),
2517  repl_val, repl_null, repl_repl);
2518 
2519  CatalogTupleUpdate(extRel, &extTup->t_self, extTup);
2520 
2521  systable_endscan(extScan);
2522 
2523  table_close(extRel, RowExclusiveLock);
2524 
2525  PG_RETURN_VOID();
2526 }
2527 
2528 /*
2529  * extension_config_remove
2530  *
2531  * Remove the specified table OID from extension's extconfig, if present.
2532  * This is not currently exposed as a function, but it could be;
2533  * for now, we just invoke it from ALTER EXTENSION DROP.
2534  */
2535 static void
2536 extension_config_remove(Oid extensionoid, Oid tableoid)
2537 {
2538  Relation extRel;
2539  ScanKeyData key[1];
2540  SysScanDesc extScan;
2541  HeapTuple extTup;
2542  Datum arrayDatum;
2543  int arrayLength;
2544  int arrayIndex;
2545  bool isnull;
2546  Datum repl_val[Natts_pg_extension];
2547  bool repl_null[Natts_pg_extension];
2548  bool repl_repl[Natts_pg_extension];
2549  ArrayType *a;
2550 
2551  /* Find the pg_extension tuple */
2552  extRel = table_open(ExtensionRelationId, RowExclusiveLock);
2553 
2554  ScanKeyInit(&key[0],
2555  Anum_pg_extension_oid,
2556  BTEqualStrategyNumber, F_OIDEQ,
2557  ObjectIdGetDatum(extensionoid));
2558 
2559  extScan = systable_beginscan(extRel, ExtensionOidIndexId, true,
2560  NULL, 1, key);
2561 
2562  extTup = systable_getnext(extScan);
2563 
2564  if (!HeapTupleIsValid(extTup)) /* should not happen */
2565  elog(ERROR, "could not find tuple for extension %u",
2566  extensionoid);
2567 
2568  /* Search extconfig for the tableoid */
2569  arrayDatum = heap_getattr(extTup, Anum_pg_extension_extconfig,
2570  RelationGetDescr(extRel), &isnull);
2571  if (isnull)
2572  {
2573  /* nothing to do */
2574  a = NULL;
2575  arrayLength = 0;
2576  arrayIndex = -1;
2577  }
2578  else
2579  {
2580  Oid *arrayData;
2581  int i;
2582 
2583  a = DatumGetArrayTypeP(arrayDatum);
2584 
2585  arrayLength = ARR_DIMS(a)[0];
2586  if (ARR_NDIM(a) != 1 ||
2587  ARR_LBOUND(a)[0] != 1 ||
2588  arrayLength < 0 ||
2589  ARR_HASNULL(a) ||
2590  ARR_ELEMTYPE(a) != OIDOID)
2591  elog(ERROR, "extconfig is not a 1-D Oid array");
2592  arrayData = (Oid *) ARR_DATA_PTR(a);
2593 
2594  arrayIndex = -1; /* flag for no deletion needed */
2595 
2596  for (i = 0; i < arrayLength; i++)
2597  {
2598  if (arrayData[i] == tableoid)
2599  {
2600  arrayIndex = i; /* index to remove */
2601  break;
2602  }
2603  }
2604  }
2605 
2606  /* If tableoid is not in extconfig, nothing to do */
2607  if (arrayIndex < 0)
2608  {
2609  systable_endscan(extScan);
2610  table_close(extRel, RowExclusiveLock);
2611  return;
2612  }
2613 
2614  /* Modify or delete the extconfig value */
2615  memset(repl_val, 0, sizeof(repl_val));
2616  memset(repl_null, false, sizeof(repl_null));
2617  memset(repl_repl, false, sizeof(repl_repl));
2618 
2619  if (arrayLength <= 1)
2620  {
2621  /* removing only element, just set array to null */
2622  repl_null[Anum_pg_extension_extconfig - 1] = true;
2623  }
2624  else
2625  {
2626  /* squeeze out the target element */
2627  Datum *dvalues;
2628  int nelems;
2629  int i;
2630 
2631  /* We already checked there are no nulls */
2632  deconstruct_array_builtin(a, OIDOID, &dvalues, NULL, &nelems);
2633 
2634  for (i = arrayIndex; i < arrayLength - 1; i++)
2635  dvalues[i] = dvalues[i + 1];
2636 
2637  a = construct_array_builtin(dvalues, arrayLength - 1, OIDOID);
2638 
2639  repl_val[Anum_pg_extension_extconfig - 1] = PointerGetDatum(a);
2640  }
2641  repl_repl[Anum_pg_extension_extconfig - 1] = true;
2642 
2643  /* Modify or delete the extcondition value */
2644  arrayDatum = heap_getattr(extTup, Anum_pg_extension_extcondition,
2645  RelationGetDescr(extRel), &isnull);
2646  if (isnull)
2647  {
2648  elog(ERROR, "extconfig and extcondition arrays do not match");
2649  }
2650  else
2651  {
2652  a = DatumGetArrayTypeP(arrayDatum);
2653 
2654  if (ARR_NDIM(a) != 1 ||
2655  ARR_LBOUND(a)[0] != 1 ||
2656  ARR_HASNULL(a) ||
2657  ARR_ELEMTYPE(a) != TEXTOID)
2658  elog(ERROR, "extcondition is not a 1-D text array");
2659  if (ARR_DIMS(a)[0] != arrayLength)
2660  elog(ERROR, "extconfig and extcondition arrays do not match");
2661  }
2662 
2663  if (arrayLength <= 1)
2664  {
2665  /* removing only element, just set array to null */
2666  repl_null[Anum_pg_extension_extcondition - 1] = true;
2667  }
2668  else
2669  {
2670  /* squeeze out the target element */
2671  Datum *dvalues;
2672  int nelems;
2673  int i;
2674 
2675  /* We already checked there are no nulls */
2676  deconstruct_array_builtin(a, TEXTOID, &dvalues, NULL, &nelems);
2677 
2678  for (i = arrayIndex; i < arrayLength - 1; i++)
2679  dvalues[i] = dvalues[i + 1];
2680 
2681  a = construct_array_builtin(dvalues, arrayLength - 1, TEXTOID);
2682 
2683  repl_val[Anum_pg_extension_extcondition - 1] = PointerGetDatum(a);
2684  }
2685  repl_repl[Anum_pg_extension_extcondition - 1] = true;
2686 
2687  extTup = heap_modify_tuple(extTup, RelationGetDescr(extRel),
2688  repl_val, repl_null, repl_repl);
2689 
2690  CatalogTupleUpdate(extRel, &extTup->t_self, extTup);
2691 
2692  systable_endscan(extScan);
2693 
2694  table_close(extRel, RowExclusiveLock);
2695 }
2696 
2697 /*
2698  * Execute ALTER EXTENSION SET SCHEMA
2699  */
2701 AlterExtensionNamespace(const char *extensionName, const char *newschema, Oid *oldschema)
2702 {
2703  Oid extensionOid;
2704  Oid nspOid;
2705  Oid oldNspOid = InvalidOid;
2706  AclResult aclresult;
2707  Relation extRel;
2708  ScanKeyData key[2];
2709  SysScanDesc extScan;
2710  HeapTuple extTup;
2711  Form_pg_extension extForm;
2712  Relation depRel;
2713  SysScanDesc depScan;
2714  HeapTuple depTup;
2715  ObjectAddresses *objsMoved;
2716  ObjectAddress extAddr;
2717 
2718  extensionOid = get_extension_oid(extensionName, false);
2719 
2720  nspOid = LookupCreationNamespace(newschema);
2721 
2722  /*
2723  * Permission check: must own extension. Note that we don't bother to
2724  * check ownership of the individual member objects ...
2725  */
2726  if (!pg_extension_ownercheck(extensionOid, GetUserId()))
2728  extensionName);
2729 
2730  /* Permission check: must have creation rights in target namespace */
2731  aclresult = pg_namespace_aclcheck(nspOid, GetUserId(), ACL_CREATE);
2732  if (aclresult != ACLCHECK_OK)
2733  aclcheck_error(aclresult, OBJECT_SCHEMA, newschema);
2734 
2735  /*
2736  * If the schema is currently a member of the extension, disallow moving
2737  * the extension into the schema. That would create a dependency loop.
2738  */
2739  if (getExtensionOfObject(NamespaceRelationId, nspOid) == extensionOid)
2740  ereport(ERROR,
2741  (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
2742  errmsg("cannot move extension \"%s\" into schema \"%s\" "
2743  "because the extension contains the schema",
2744  extensionName, newschema)));
2745 
2746  /* Locate the pg_extension tuple */
2747  extRel = table_open(ExtensionRelationId, RowExclusiveLock);
2748 
2749  ScanKeyInit(&key[0],
2750  Anum_pg_extension_oid,
2751  BTEqualStrategyNumber, F_OIDEQ,
2752  ObjectIdGetDatum(extensionOid));
2753 
2754  extScan = systable_beginscan(extRel, ExtensionOidIndexId, true,
2755  NULL, 1, key);
2756 
2757  extTup = systable_getnext(extScan);
2758 
2759  if (!HeapTupleIsValid(extTup)) /* should not happen */
2760  elog(ERROR, "could not find tuple for extension %u",
2761  extensionOid);
2762 
2763  /* Copy tuple so we can modify it below */
2764  extTup = heap_copytuple(extTup);
2765  extForm = (Form_pg_extension) GETSTRUCT(extTup);
2766 
2767  systable_endscan(extScan);
2768 
2769  /*
2770  * If the extension is already in the target schema, just silently do
2771  * nothing.
2772  */
2773  if (extForm->extnamespace == nspOid)
2774  {
2775  table_close(extRel, RowExclusiveLock);
2776  return InvalidObjectAddress;
2777  }
2778 
2779  /* Check extension is supposed to be relocatable */
2780  if (!extForm->extrelocatable)
2781  ereport(ERROR,
2782  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2783  errmsg("extension \"%s\" does not support SET SCHEMA",
2784  NameStr(extForm->extname))));
2785 
2786  objsMoved = new_object_addresses();
2787 
2788  /*
2789  * Scan pg_depend to find objects that depend directly on the extension,
2790  * and alter each one's schema.
2791  */
2792  depRel = table_open(DependRelationId, AccessShareLock);
2793 
2794  ScanKeyInit(&key[0],
2795  Anum_pg_depend_refclassid,
2796  BTEqualStrategyNumber, F_OIDEQ,
2797  ObjectIdGetDatum(ExtensionRelationId));
2798  ScanKeyInit(&key[1],
2799  Anum_pg_depend_refobjid,
2800  BTEqualStrategyNumber, F_OIDEQ,
2801  ObjectIdGetDatum(extensionOid));
2802 
2803  depScan = systable_beginscan(depRel, DependReferenceIndexId, true,
2804  NULL, 2, key);
2805 
2806  while (HeapTupleIsValid(depTup = systable_getnext(depScan)))
2807  {
2808  Form_pg_depend pg_depend = (Form_pg_depend) GETSTRUCT(depTup);
2809  ObjectAddress dep;
2810  Oid dep_oldNspOid;
2811 
2812  /*
2813  * Ignore non-membership dependencies. (Currently, the only other
2814  * case we could see here is a normal dependency from another
2815  * extension.)
2816  */
2817  if (pg_depend->deptype != DEPENDENCY_EXTENSION)
2818  continue;
2819 
2820  dep.classId = pg_depend->classid;
2821  dep.objectId = pg_depend->objid;
2822  dep.objectSubId = pg_depend->objsubid;
2823 
2824  if (dep.objectSubId != 0) /* should not happen */
2825  elog(ERROR, "extension should not have a sub-object dependency");
2826 
2827  /* Relocate the object */
2828  dep_oldNspOid = AlterObjectNamespace_oid(dep.classId,
2829  dep.objectId,
2830  nspOid,
2831  objsMoved);
2832 
2833  /*
2834  * Remember previous namespace of first object that has one
2835  */
2836  if (oldNspOid == InvalidOid && dep_oldNspOid != InvalidOid)
2837  oldNspOid = dep_oldNspOid;
2838 
2839  /*
2840  * If not all the objects had the same old namespace (ignoring any
2841  * that are not in namespaces), complain.
2842  */
2843  if (dep_oldNspOid != InvalidOid && dep_oldNspOid != oldNspOid)
2844  ereport(ERROR,
2845  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2846  errmsg("extension \"%s\" does not support SET SCHEMA",
2847  NameStr(extForm->extname)),
2848  errdetail("%s is not in the extension's schema \"%s\"",
2849  getObjectDescription(&dep, false),
2850  get_namespace_name(oldNspOid))));
2851  }
2852 
2853  /* report old schema, if caller wants it */
2854  if (oldschema)
2855  *oldschema = oldNspOid;
2856 
2857  systable_endscan(depScan);
2858 
2860 
2861  /* Now adjust pg_extension.extnamespace */
2862  extForm->extnamespace = nspOid;
2863 
2864  CatalogTupleUpdate(extRel, &extTup->t_self, extTup);
2865 
2866  table_close(extRel, RowExclusiveLock);
2867 
2868  /* update dependencies to point to the new schema */
2869  changeDependencyFor(ExtensionRelationId, extensionOid,
2870  NamespaceRelationId, oldNspOid, nspOid);
2871 
2872  InvokeObjectPostAlterHook(ExtensionRelationId, extensionOid, 0);
2873 
2874  ObjectAddressSet(extAddr, ExtensionRelationId, extensionOid);
2875 
2876  return extAddr;
2877 }
2878 
2879 /*
2880  * Execute ALTER EXTENSION UPDATE
2881  */
2884 {
2885  DefElem *d_new_version = NULL;
2886  char *versionName;
2887  char *oldVersionName;
2888  ExtensionControlFile *control;
2889  Oid extensionOid;
2890  Relation extRel;
2891  ScanKeyData key[1];
2892  SysScanDesc extScan;
2893  HeapTuple extTup;
2894  List *updateVersions;
2895  Datum datum;
2896  bool isnull;
2897  ListCell *lc;
2898  ObjectAddress address;
2899 
2900  /*
2901  * We use global variables to track the extension being created, so we can
2902  * create/update only one extension at the same time.
2903  */
2904  if (creating_extension)
2905  ereport(ERROR,
2906  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2907  errmsg("nested ALTER EXTENSION is not supported")));
2908 
2909  /*
2910  * Look up the extension --- it must already exist in pg_extension
2911  */
2912  extRel = table_open(ExtensionRelationId, AccessShareLock);
2913 
2914  ScanKeyInit(&key[0],
2915  Anum_pg_extension_extname,
2916  BTEqualStrategyNumber, F_NAMEEQ,
2917  CStringGetDatum(stmt->extname));
2918 
2919  extScan = systable_beginscan(extRel, ExtensionNameIndexId, true,
2920  NULL, 1, key);
2921 
2922  extTup = systable_getnext(extScan);
2923 
2924  if (!HeapTupleIsValid(extTup))
2925  ereport(ERROR,
2926  (errcode(ERRCODE_UNDEFINED_OBJECT),
2927  errmsg("extension \"%s\" does not exist",
2928  stmt->extname)));
2929 
2930  extensionOid = ((Form_pg_extension) GETSTRUCT(extTup))->oid;
2931 
2932  /*
2933  * Determine the existing version we are updating from
2934  */
2935  datum = heap_getattr(extTup, Anum_pg_extension_extversion,
2936  RelationGetDescr(extRel), &isnull);
2937  if (isnull)
2938  elog(ERROR, "extversion is null");
2939  oldVersionName = text_to_cstring(DatumGetTextPP(datum));
2940 
2941  systable_endscan(extScan);
2942 
2943  table_close(extRel, AccessShareLock);
2944 
2945  /* Permission check: must own extension */
2946  if (!pg_extension_ownercheck(extensionOid, GetUserId()))
2948  stmt->extname);
2949 
2950  /*
2951  * Read the primary control file. Note we assume that it does not contain
2952  * any non-ASCII data, so there is no need to worry about encoding at this
2953  * point.
2954  */
2955  control = read_extension_control_file(stmt->extname);
2956 
2957  /*
2958  * Read the statement option list
2959  */
2960  foreach(lc, stmt->options)
2961  {
2962  DefElem *defel = (DefElem *) lfirst(lc);
2963 
2964  if (strcmp(defel->defname, "new_version") == 0)
2965  {
2966  if (d_new_version)
2967  errorConflictingDefElem(defel, pstate);
2968  d_new_version = defel;
2969  }
2970  else
2971  elog(ERROR, "unrecognized option: %s", defel->defname);
2972  }
2973 
2974  /*
2975  * Determine the version to update to
2976  */
2977  if (d_new_version && d_new_version->arg)
2978  versionName = strVal(d_new_version->arg);
2979  else if (control->default_version)
2980  versionName = control->default_version;
2981  else
2982  {
2983  ereport(ERROR,
2984  (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
2985  errmsg("version to install must be specified")));
2986  versionName = NULL; /* keep compiler quiet */
2987  }
2988  check_valid_version_name(versionName);
2989 
2990  /*
2991  * If we're already at that version, just say so
2992  */
2993  if (strcmp(oldVersionName, versionName) == 0)
2994  {
2995  ereport(NOTICE,
2996  (errmsg("version \"%s\" of extension \"%s\" is already installed",
2997  versionName, stmt->extname)));
2998  return InvalidObjectAddress;
2999  }
3000 
3001  /*
3002  * Identify the series of update script files we need to execute
3003  */
3004  updateVersions = identify_update_path(control,
3005  oldVersionName,
3006  versionName);
3007 
3008  /*
3009  * Update the pg_extension row and execute the update scripts, one at a
3010  * time
3011  */
3012  ApplyExtensionUpdates(extensionOid, control,
3013  oldVersionName, updateVersions,
3014  NULL, false, false);
3015 
3016  ObjectAddressSet(address, ExtensionRelationId, extensionOid);
3017 
3018  return address;
3019 }
3020 
3021 /*
3022  * Apply a series of update scripts as though individual ALTER EXTENSION
3023  * UPDATE commands had been given, including altering the pg_extension row
3024  * and dependencies each time.
3025  *
3026  * This might be more work than necessary, but it ensures that old update
3027  * scripts don't break if newer versions have different control parameters.
3028  */
3029 static void
3031  ExtensionControlFile *pcontrol,
3032  const char *initialVersion,
3033  List *updateVersions,
3034  char *origSchemaName,
3035  bool cascade,
3036  bool is_create)
3037 {
3038  const char *oldVersionName = initialVersion;
3039  ListCell *lcv;
3040 
3041  foreach(lcv, updateVersions)
3042  {
3043  char *versionName = (char *) lfirst(lcv);
3044  ExtensionControlFile *control;
3045  char *schemaName;
3046  Oid schemaOid;
3047  List *requiredExtensions;
3048  List *requiredSchemas;
3049  Relation extRel;
3050  ScanKeyData key[1];
3051  SysScanDesc extScan;
3052  HeapTuple extTup;
3053  Form_pg_extension extForm;
3054  Datum values[Natts_pg_extension];
3055  bool nulls[Natts_pg_extension];
3056  bool repl[Natts_pg_extension];
3057  ObjectAddress myself;
3058  ListCell *lc;
3059 
3060  /*
3061  * Fetch parameters for specific version (pcontrol is not changed)
3062  */
3063  control = read_extension_aux_control_file(pcontrol, versionName);
3064 
3065  /* Find the pg_extension tuple */
3066  extRel = table_open(ExtensionRelationId, RowExclusiveLock);
3067 
3068  ScanKeyInit(&key[0],
3069  Anum_pg_extension_oid,
3070  BTEqualStrategyNumber, F_OIDEQ,
3071  ObjectIdGetDatum(extensionOid));
3072 
3073  extScan = systable_beginscan(extRel, ExtensionOidIndexId, true,
3074  NULL, 1, key);
3075 
3076  extTup = systable_getnext(extScan);
3077 
3078  if (!HeapTupleIsValid(extTup)) /* should not happen */
3079  elog(ERROR, "could not find tuple for extension %u",
3080  extensionOid);
3081 
3082  extForm = (Form_pg_extension) GETSTRUCT(extTup);
3083 
3084  /*
3085  * Determine the target schema (set by original install)
3086  */
3087  schemaOid = extForm->extnamespace;
3088  schemaName = get_namespace_name(schemaOid);
3089 
3090  /*
3091  * Modify extrelocatable and extversion in the pg_extension tuple
3092  */
3093  memset(values, 0, sizeof(values));
3094  memset(nulls, 0, sizeof(nulls));
3095  memset(repl, 0, sizeof(repl));
3096 
3097  values[Anum_pg_extension_extrelocatable - 1] =
3098  BoolGetDatum(control->relocatable);
3099  repl[Anum_pg_extension_extrelocatable - 1] = true;
3100  values[Anum_pg_extension_extversion - 1] =
3101  CStringGetTextDatum(versionName);
3102  repl[Anum_pg_extension_extversion - 1] = true;
3103 
3104  extTup = heap_modify_tuple(extTup, RelationGetDescr(extRel),
3105  values, nulls, repl);
3106 
3107  CatalogTupleUpdate(extRel, &extTup->t_self, extTup);
3108 
3109  systable_endscan(extScan);
3110 
3111  table_close(extRel, RowExclusiveLock);
3112 
3113  /*
3114  * Look up the prerequisite extensions for this version, install them
3115  * if necessary, and build lists of their OIDs and the OIDs of their
3116  * target schemas.
3117  */
3118  requiredExtensions = NIL;
3119  requiredSchemas = NIL;
3120  foreach(lc, control->requires)
3121  {
3122  char *curreq = (char *) lfirst(lc);
3123  Oid reqext;
3124  Oid reqschema;
3125 
3126  reqext = get_required_extension(curreq,
3127  control->name,
3128  origSchemaName,
3129  cascade,
3130  NIL,
3131  is_create);
3132  reqschema = get_extension_schema(reqext);
3133  requiredExtensions = lappend_oid(requiredExtensions, reqext);
3134  requiredSchemas = lappend_oid(requiredSchemas, reqschema);
3135  }
3136 
3137  /*
3138  * Remove and recreate dependencies on prerequisite extensions
3139  */
3140  deleteDependencyRecordsForClass(ExtensionRelationId, extensionOid,
3141  ExtensionRelationId,
3143 
3144  myself.classId = ExtensionRelationId;
3145  myself.objectId = extensionOid;
3146  myself.objectSubId = 0;
3147 
3148  foreach(lc, requiredExtensions)
3149  {
3150  Oid reqext = lfirst_oid(lc);
3151  ObjectAddress otherext;
3152 
3153  otherext.classId = ExtensionRelationId;
3154  otherext.objectId = reqext;
3155  otherext.objectSubId = 0;
3156 
3157  recordDependencyOn(&myself, &otherext, DEPENDENCY_NORMAL);
3158  }
3159 
3160  InvokeObjectPostAlterHook(ExtensionRelationId, extensionOid, 0);
3161 
3162  /*
3163  * Finally, execute the update script file
3164  */
3165  execute_extension_script(extensionOid, control,
3166  oldVersionName, versionName,
3167  requiredSchemas,
3168  schemaName, schemaOid);
3169 
3170  /*
3171  * Update prior-version name and loop around. Since
3172  * execute_sql_string did a final CommandCounterIncrement, we can
3173  * update the pg_extension row again.
3174  */
3175  oldVersionName = versionName;
3176  }
3177 }
3178 
3179 /*
3180  * Execute ALTER EXTENSION ADD/DROP
3181  *
3182  * Return value is the address of the altered extension.
3183  *
3184  * objAddr is an output argument which, if not NULL, is set to the address of
3185  * the added/dropped object.
3186  */
3189  ObjectAddress *objAddr)
3190 {
3191  ObjectAddress extension;
3192  ObjectAddress object;
3193  Relation relation;
3194  Oid oldExtension;
3195 
3196  switch (stmt->objtype)
3197  {
3198  case OBJECT_DATABASE:
3199  case OBJECT_EXTENSION:
3200  case OBJECT_INDEX:
3201  case OBJECT_PUBLICATION:
3202  case OBJECT_ROLE:
3203  case OBJECT_STATISTIC_EXT:
3204  case OBJECT_SUBSCRIPTION:
3205  case OBJECT_TABLESPACE:
3206  ereport(ERROR,
3207  (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
3208  errmsg("cannot add an object of this type to an extension")));
3209  break;
3210  default:
3211  /* OK */
3212  break;
3213  }
3214 
3215  /*
3216  * Find the extension and acquire a lock on it, to ensure it doesn't get
3217  * dropped concurrently. A sharable lock seems sufficient: there's no
3218  * reason not to allow other sorts of manipulations, such as add/drop of
3219  * other objects, to occur concurrently. Concurrently adding/dropping the
3220  * *same* object would be bad, but we prevent that by using a non-sharable
3221  * lock on the individual object, below.
3222  */
3224  (Node *) makeString(stmt->extname),
3225  &relation, AccessShareLock, false);
3226 
3227  /* Permission check: must own extension */
3228  if (!pg_extension_ownercheck(extension.objectId, GetUserId()))
3230  stmt->extname);
3231 
3232  /*
3233  * Translate the parser representation that identifies the object into an
3234  * ObjectAddress. get_object_address() will throw an error if the object
3235  * does not exist, and will also acquire a lock on the object to guard
3236  * against concurrent DROP and ALTER EXTENSION ADD/DROP operations.
3237  */
3238  object = get_object_address(stmt->objtype, stmt->object,
3239  &relation, ShareUpdateExclusiveLock, false);
3240 
3241  Assert(object.objectSubId == 0);
3242  if (objAddr)
3243  *objAddr = object;
3244 
3245  /* Permission check: must own target object, too */
3246  check_object_ownership(GetUserId(), stmt->objtype, object,
3247  stmt->object, relation);
3248 
3249  /*
3250  * Check existing extension membership.
3251  */
3252  oldExtension = getExtensionOfObject(object.classId, object.objectId);
3253 
3254  if (stmt->action > 0)
3255  {
3256  /*
3257  * ADD, so complain if object is already attached to some extension.
3258  */
3259  if (OidIsValid(oldExtension))
3260  ereport(ERROR,
3261  (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
3262  errmsg("%s is already a member of extension \"%s\"",
3263  getObjectDescription(&object, false),
3264  get_extension_name(oldExtension))));
3265 
3266  /*
3267  * Prevent a schema from being added to an extension if the schema
3268  * contains the extension. That would create a dependency loop.
3269  */
3270  if (object.classId == NamespaceRelationId &&
3271  object.objectId == get_extension_schema(extension.objectId))
3272  ereport(ERROR,
3273  (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
3274  errmsg("cannot add schema \"%s\" to extension \"%s\" "
3275  "because the schema contains the extension",
3276  get_namespace_name(object.objectId),
3277  stmt->extname)));
3278 
3279  /*
3280  * OK, add the dependency.
3281  */
3282  recordDependencyOn(&object, &extension, DEPENDENCY_EXTENSION);
3283 
3284  /*
3285  * Also record the initial ACL on the object, if any.
3286  *
3287  * Note that this will handle the object's ACLs, as well as any ACLs
3288  * on object subIds. (In other words, when the object is a table,
3289  * this will record the table's ACL and the ACLs for the columns on
3290  * the table, if any).
3291  */
3292  recordExtObjInitPriv(object.objectId, object.classId);
3293  }
3294  else
3295  {
3296  /*
3297  * DROP, so complain if it's not a member.
3298  */
3299  if (oldExtension != extension.objectId)
3300  ereport(ERROR,
3301  (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
3302  errmsg("%s is not a member of extension \"%s\"",
3303  getObjectDescription(&object, false),
3304  stmt->extname)));
3305 
3306  /*
3307  * OK, drop the dependency.
3308  */
3309  if (deleteDependencyRecordsForClass(object.classId, object.objectId,
3310  ExtensionRelationId,
3311  DEPENDENCY_EXTENSION) != 1)
3312  elog(ERROR, "unexpected number of extension dependency records");
3313 
3314  /*
3315  * If it's a relation, it might have an entry in the extension's
3316  * extconfig array, which we must remove.
3317  */
3318  if (object.classId == RelationRelationId)
3319  extension_config_remove(extension.objectId, object.objectId);
3320 
3321  /*
3322  * Remove all the initial ACLs, if any.
3323  *
3324  * Note that this will remove the object's ACLs, as well as any ACLs
3325  * on object subIds. (In other words, when the object is a table,
3326  * this will remove the table's ACL and the ACLs for the columns on
3327  * the table, if any).
3328  */
3329  removeExtObjInitPriv(object.objectId, object.classId);
3330  }
3331 
3332  InvokeObjectPostAlterHook(ExtensionRelationId, extension.objectId, 0);
3333 
3334  /*
3335  * If get_object_address() opened the relation for us, we close it to keep
3336  * the reference count correct - but we retain any locks acquired by
3337  * get_object_address() until commit time, to guard against concurrent
3338  * activity.
3339  */
3340  if (relation != NULL)
3341  relation_close(relation, NoLock);
3342 
3343  return extension;
3344 }
3345 
3346 /*
3347  * Read the whole of file into memory.
3348  *
3349  * The file contents are returned as a single palloc'd chunk. For convenience
3350  * of the callers, an extra \0 byte is added to the end.
3351  */
3352 static char *
3353 read_whole_file(const char *filename, int *length)
3354 {
3355  char *buf;
3356  FILE *file;
3357  size_t bytes_to_read;
3358  struct stat fst;
3359 
3360  if (stat(filename, &fst) < 0)
3361  ereport(ERROR,
3363  errmsg("could not stat file \"%s\": %m", filename)));
3364 
3365  if (fst.st_size > (MaxAllocSize - 1))
3366  ereport(ERROR,
3367  (errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED),
3368  errmsg("file \"%s\" is too large", filename)));
3369  bytes_to_read = (size_t) fst.st_size;
3370 
3371  if ((file = AllocateFile(filename, PG_BINARY_R)) == NULL)
3372  ereport(ERROR,
3374  errmsg("could not open file \"%s\" for reading: %m",
3375  filename)));
3376 
3377  buf = (char *) palloc(bytes_to_read + 1);
3378 
3379  *length = fread(buf, 1, bytes_to_read, file);
3380 
3381  if (ferror(file))
3382  ereport(ERROR,
3384  errmsg("could not read file \"%s\": %m", filename)));
3385 
3386  FreeFile(file);
3387 
3388  buf[*length] = '\0';
3389  return buf;
3390 }
AclResult
Definition: acl.h:181
@ ACLCHECK_OK
Definition: acl.h:182
@ ACLCHECK_NOT_OWNER
Definition: acl.h:184
AclResult pg_namespace_aclcheck(Oid nsp_oid, Oid roleid, AclMode mode)
Definition: aclchk.c:5109
bool pg_extension_ownercheck(Oid ext_oid, Oid roleid)
Definition: aclchk.c:5667
void recordExtObjInitPriv(Oid objoid, Oid classoid)
Definition: aclchk.c:5980
void aclcheck_error(AclResult aclerr, ObjectType objtype, const char *objectname)
Definition: aclchk.c:3512
AclResult pg_database_aclcheck(Oid db_oid, Oid roleid, AclMode mode)
Definition: aclchk.c:5033
void removeExtObjInitPriv(Oid objoid, Oid classoid)
Definition: aclchk.c:6278
Oid AlterObjectNamespace_oid(Oid classId, Oid objid, Oid nspOid, ObjectAddresses *objsMoved)
Definition: alter.c:589
#define ARR_NDIM(a)
Definition: array.h:283
#define ARR_DATA_PTR(a)
Definition: array.h:315
#define DatumGetArrayTypeP(X)
Definition: array.h:254
#define ARR_ELEMTYPE(a)
Definition: array.h:285
#define ARR_DIMS(a)
Definition: array.h:287
#define ARR_HASNULL(a)
Definition: array.h:284
#define ARR_LBOUND(a)
Definition: array.h:289
ArrayType * construct_array_builtin(Datum *elems, int nelems, Oid elmtype)
Definition: arrayfuncs.c:3339
ArrayType * array_set(ArrayType *array, int nSubscripts, int *indx, Datum dataValue, bool isNull, int arraytyplen, int elmlen, bool elmbyval, char elmalign)
Definition: arrayfuncs.c:3121
void deconstruct_array_builtin(ArrayType *array, Oid elmtype, Datum **elemsp, bool **nullsp, int *nelemsp)
Definition: arrayfuncs.c:3643
bool parse_bool(const char *value, bool *result)
Definition: bool.c:30
static Datum values[MAXATTR]
Definition: bootstrap.c:156
#define CStringGetTextDatum(s)
Definition: builtins.h:85
#define NameStr(name)
Definition: c.h:692
#define PG_BINARY_R
Definition: c.h:1281
#define OidIsValid(objectId)
Definition: c.h:721
Oid GetNewOidWithIndex(Relation relation, Oid indexId, AttrNumber oidcolumn)
Definition: catalog.c:391
void CreateComments(Oid oid, Oid classoid, int32 subid, const char *comment)
Definition: comment.c:143
bool defGetBoolean(DefElem *def)
Definition: define.c:108
char * defGetString(DefElem *def)
Definition: define.c:49
void errorConflictingDefElem(DefElem *defel, ParseState *pstate)
Definition: define.c:352
void record_object_address_dependencies(const ObjectAddress *depender, ObjectAddresses *referenced, DependencyType behavior)
Definition: dependency.c:2711
ObjectAddresses * new_object_addresses(void)
Definition: dependency.c:2447
void add_exact_object_address(const ObjectAddress *object, ObjectAddresses *addrs)
Definition: dependency.c:2502
void free_object_addresses(ObjectAddresses *addrs)
Definition: dependency.c:2742
@ DEPENDENCY_EXTENSION
Definition: dependency.h:38
@ DEPENDENCY_NORMAL
Definition: dependency.h:33
DestReceiver * CreateDestReceiver(CommandDest dest)
Definition: dest.c:113
@ DestNone
Definition: dest.h:89
int errcode_for_file_access(void)
Definition: elog.c:716
int errdetail(const char *fmt,...)
Definition: elog.c:1037
int errhint(const char *fmt,...)
Definition: elog.c:1151
int errcode(int sqlerrcode)
Definition: elog.c:693
int errmsg(const char *fmt,...)
Definition: elog.c:904
#define PG_END_TRY()
Definition: elog.h:324
#define PG_TRY()
Definition: elog.h:299
#define WARNING
Definition: elog.h:30
#define DEBUG1
Definition: elog.h:24
#define PG_FINALLY()
Definition: elog.h:316
#define ERROR
Definition: elog.h:33
#define NOTICE
Definition: elog.h:29
#define ereport(elevel,...)
Definition: elog.h:143
int pg_valid_server_encoding(const char *name)
Definition: encnames.c:500
void ExecutorEnd(QueryDesc *queryDesc)
Definition: execMain.c:461
void ExecutorFinish(QueryDesc *queryDesc)
Definition: execMain.c:401
void ExecutorStart(QueryDesc *queryDesc, int eflags)
Definition: execMain.c:131
void ExecutorRun(QueryDesc *queryDesc, ScanDirection direction, uint64 count, bool execute_once)
Definition: execMain.c:300
static ExtensionVersionInfo * get_ext_ver_info(const char *versionname, List **evi_list)
Definition: extension.c:1072
static bool is_extension_script_filename(const char *filename)
Definition: extension.c:363
static char * read_whole_file(const char *filename, int *length)
Definition: extension.c:3353
ObjectAddress InsertExtensionTuple(const char *extName, Oid extOwner, Oid schemaOid, bool relocatable, const char *extVersion, Datum extConfig, Datum extCondition, List *requiredExtensions)
Definition: extension.c:1795
static void check_valid_extension_name(const char *extensionname)
Definition: extension.c:261
static char * read_extension_script_file(const ExtensionControlFile *control, const char *filename)
Definition: extension.c:679
static List * identify_update_path(ExtensionControlFile *control, const char *oldVersion, const char *newVersion)
Definition: extension.c:1196
struct ExtensionVersionInfo ExtensionVersionInfo
ObjectAddress CreateExtension(ParseState *pstate, CreateExtensionStmt *stmt)
Definition: extension.c:1697
static void check_valid_version_name(const char *versionname)
Definition: extension.c:308
static bool is_extension_control_filename(const char *filename)
Definition: extension.c:355
static Oid get_required_extension(char *reqExtensionName, char *extensionName, char *origSchemaName, bool cascade, List *parents, bool is_create)
Definition: extension.c:1626
static char * get_extension_script_filename(ExtensionControlFile *control, const char *from_version, const char *version)
Definition: extension.c:439
static List * get_ext_ver_list(ExtensionControlFile *control)
Definition: extension.c:1133
static void execute_extension_script(Oid extensionOid, ExtensionControlFile *control, const char *from_version, const char *version, List *requiredSchemas, const char *schemaName, Oid schemaOid)
Definition: extension.c:847
static void parse_extension_control_file(ExtensionControlFile *control, const char *version)
Definition: extension.c:471
bool creating_extension
Definition: extension.c:71
Datum pg_available_extension_versions(PG_FUNCTION_ARGS)
Definition: extension.c:2017
static void extension_config_remove(Oid extensionoid, Oid tableoid)
Definition: extension.c:2536
static ExtensionVersionInfo * get_nearest_unprocessed_vertex(List *evi_list)
Definition: extension.c:1105
ObjectAddress AlterExtensionNamespace(const char *extensionName, const char *newschema, Oid *oldschema)
Definition: extension.c:2701
static char * get_extension_control_directory(void)
Definition: extension.c:371
static char * get_extension_script_directory(ExtensionControlFile *control)
Definition: extension.c:398
static void execute_sql_string(const char *sql)
Definition: extension.c:720
static ExtensionControlFile * read_extension_control_file(const char *extname)
Definition: extension.c:627
ObjectAddress ExecAlterExtensionStmt(ParseState *pstate, AlterExtensionStmt *stmt)
Definition: extension.c:2883
Oid CurrentExtensionObject
Definition: extension.c:72
ObjectAddress ExecAlterExtensionContentsStmt(AlterExtensionContentsStmt *stmt, ObjectAddress *objAddr)
Definition: extension.c:3188
Datum pg_extension_update_paths(PG_FUNCTION_ARGS)
Definition: extension.c:2268
Oid get_extension_oid(const char *extname, bool missing_ok)
Definition: extension.c:140
Datum pg_available_extensions(PG_FUNCTION_ARGS)
Definition: extension.c:1937
Datum pg_extension_config_dump(PG_FUNCTION_ARGS)
Definition: extension.c:2353
static ExtensionVersionInfo * find_install_path(List *evi_list, ExtensionVersionInfo *evi_target, List **best_path)
Definition: extension.c:1332
static Datum convert_requires_to_datum(List *requires)
Definition: extension.c:2242
static char * get_extension_control_filename(const char *extname)
Definition: extension.c:384
static Oid get_extension_schema(Oid ext_oid)
Definition: extension.c:224
static ExtensionControlFile * read_extension_aux_control_file(const ExtensionControlFile *pcontrol, const char *version)
Definition: extension.c:656
struct ExtensionControlFile ExtensionControlFile
char * get_extension_name(Oid ext_oid)
Definition: extension.c:185
void RemoveExtensionById(Oid extId)
Definition: extension.c:1883
static void get_available_versions_for_extension(ExtensionControlFile *pcontrol, Tuplestorestate *tupstore, TupleDesc tupdesc)
Definition: extension.c:2075
static List * find_update_path(List *evi_list, ExtensionVersionInfo *evi_start, ExtensionVersionInfo *evi_target, bool reject_indirect, bool reinitialize)
Definition: extension.c:1239
bool extension_file_exists(const char *extensionName)
Definition: extension.c:2189
static bool extension_is_trusted(ExtensionControlFile *control)
Definition: extension.c:827
static void ApplyExtensionUpdates(Oid extensionOid, ExtensionControlFile *pcontrol, const char *initialVersion, List *updateVersions, char *origSchemaName, bool cascade, bool is_create)
Definition: extension.c:3030
static ObjectAddress CreateExtensionInternal(char *extensionName, char *schemaName, const char *versionName, bool cascade, List *parents, bool is_create)
Definition: extension.c:1387
static char * get_extension_aux_control_filename(ExtensionControlFile *control, const char *version)
Definition: extension.c:421
struct dirent * ReadDir(DIR *dir, const char *dirname)
Definition: fd.c:2788
int FreeDir(DIR *dir)
Definition: fd.c:2840
FILE * AllocateFile(const char *name, const char *mode)
Definition: fd.c:2461
int FreeFile(FILE *file)
Definition: fd.c:2660
DIR * AllocateDir(const char *dirname)
Definition: fd.c:2722
Datum DirectFunctionCall4Coll(PGFunction func, Oid collation, Datum arg1, Datum arg2, Datum arg3, Datum arg4)
Definition: fmgr.c:844
Datum DirectFunctionCall3Coll(PGFunction func, Oid collation, Datum arg1, Datum arg2, Datum arg3)
Definition: fmgr.c:819
#define PG_RETURN_VOID()
Definition: fmgr.h:349
#define PG_GETARG_OID(n)
Definition: fmgr.h:275
#define PG_GETARG_TEXT_PP(n)
Definition: fmgr.h:309
#define DatumGetTextPP(X)
Definition: fmgr.h:292
#define DirectFunctionCall1(func, arg1)
Definition: fmgr.h:631
#define PG_GETARG_NAME(n)
Definition: fmgr.h:278
#define PG_FUNCTION_ARGS
Definition: fmgr.h:193
void SetSingleFuncCall(FunctionCallInfo fcinfo, bits32 flags)
Definition: funcapi.c:76
void systable_endscan(SysScanDesc sysscan)
Definition: genam.c:598
HeapTuple systable_getnext(SysScanDesc sysscan)
Definition: genam.c:505
SysScanDesc systable_beginscan(Relation heapRelation, Oid indexId, bool indexOK, Snapshot snapshot, int nkeys, ScanKey key)
Definition: genam.c:386
char my_exec_path[MAXPGPATH]
Definition: globals.c:76
Oid MyDatabaseId
Definition: globals.c:89
bool check_function_bodies
Definition: guc.c:626
int client_min_messages
Definition: guc.c:637
int NewGUCNestLevel(void)
Definition: guc.c:6475
void AtEOXact_GUC(bool isCommit, int nestLevel)
Definition: guc.c:6489
int log_min_messages
Definition: guc.c:636
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:7562
@ GUC_ACTION_SAVE
Definition: guc.h:200
void FreeConfigVariables(ConfigVariable *list)
bool ParseConfigFp(FILE *fp, const char *config_file, int depth, int elevel, ConfigVariable **head_p, ConfigVariable **tail_p)
@ PGC_S_SESSION
Definition: guc.h:123
@ PGC_SUSET
Definition: guc.h:75
@ PGC_USERSET
Definition: guc.h:76
HeapTuple heap_form_tuple(TupleDesc tupleDescriptor, Datum *values, bool *isnull)
Definition: heaptuple.c:1020
HeapTuple heap_copytuple(HeapTuple tuple)
Definition: heaptuple.c:680
HeapTuple heap_modify_tuple(HeapTuple tuple, TupleDesc tupleDesc, Datum *replValues, bool *replIsnull, bool *doReplace)
Definition: heaptuple.c:1113
void heap_freetuple(HeapTuple htup)
Definition: heaptuple.c:1338
#define HeapTupleIsValid(tuple)
Definition: htup.h:78
static Datum heap_getattr(HeapTuple tup, int attnum, TupleDesc tupleDesc, bool *isnull)
Definition: htup_details.h:788
#define GETSTRUCT(TUP)
Definition: htup_details.h:649
void CatalogTupleUpdate(Relation heapRel, ItemPointer otid, HeapTuple tup)
Definition: indexing.c:301
void CatalogTupleInsert(Relation heapRel, HeapTuple tup)
Definition: indexing.c:221
void CatalogTupleDelete(Relation heapRel, ItemPointer tid)
Definition: indexing.c:350
int a
Definition: isn.c:69
int i
Definition: isn.c:73
if(TABLE==NULL||TABLE_index==NULL)
Definition: isn.c:77
Assert(fmt[strlen(fmt) - 1] !='\n')
List * lappend(List *list, void *datum)
Definition: list.c:338
List * lappend_oid(List *list, Oid datum)
Definition: list.c:374
List * list_copy(const List *oldlist)
Definition: list.c:1572
void list_free(List *list)
Definition: list.c:1545
List * lcons(void *datum, List *list)
Definition: list.c:494
#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_namespace_name(Oid nspid)
Definition: lsyscache.c:3326
char * get_rel_name(Oid relid)
Definition: lsyscache.c:1909
char * pg_any_to_server(const char *s, int len, int encoding)
Definition: mbutils.c:676
int GetDatabaseEncoding(void)
Definition: mbutils.c:1210
bool pg_verify_mbstr(int encoding, const char *mbstr, int len, bool noError)
Definition: mbutils.c:1515
char * pstrdup(const char *in)
Definition: mcxt.c:1305
void pfree(void *pointer)
Definition: mcxt.c:1175
void * palloc0(Size size)
Definition: mcxt.c:1099
MemoryContext CurrentMemoryContext
Definition: mcxt.c:42
void MemoryContextDelete(MemoryContext context)
Definition: mcxt.c:218
void * palloc(Size size)
Definition: mcxt.c:1068
#define AllocSetContextCreate
Definition: memutils.h:173
#define ALLOCSET_DEFAULT_SIZES
Definition: memutils.h:197
#define MaxAllocSize
Definition: memutils.h:40
#define SECURITY_LOCAL_USERID_CHANGE
Definition: miscadmin.h:312
char * GetUserNameFromId(Oid roleid, bool noerr)
Definition: miscinit.c:912
void GetUserIdAndSecContext(Oid *userid, int *sec_context)
Definition: miscinit.c:602
Oid GetUserId(void)
Definition: miscinit.c:491
void SetUserIdAndSecContext(Oid userid, int sec_context)
Definition: miscinit.c:609
Datum namein(PG_FUNCTION_ARGS)
Definition: name.c:48
bool isTempNamespace(Oid namespaceId)
Definition: namespace.c:3203
Oid LookupCreationNamespace(const char *nspname)
Definition: namespace.c:2982
List * fetch_search_path(bool includeImplicit)
Definition: namespace.c:4431
Oid get_namespace_oid(const char *nspname, bool missing_ok)
Definition: namespace.c:3089
#define IsA(nodeptr, _type_)
Definition: nodes.h:625
#define makeNode(_type_)
Definition: nodes.h:622
#define InvokeObjectPostCreateHook(classId, objectId, subId)
Definition: objectaccess.h:171
#define InvokeObjectPostAlterHook(classId, objectId, subId)
Definition: objectaccess.h:195
char * getObjectDescription(const ObjectAddress *object, bool missing_ok)
void check_object_ownership(Oid roleid, ObjectType objtype, ObjectAddress address, Node *object, Relation relation)
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)
Definition: objectaddress.h:40
static MemoryContext MemoryContextSwitchTo(MemoryContext context)
Definition: palloc.h:109
@ OBJECT_SCHEMA
Definition: parsenodes.h:2171
@ OBJECT_TABLESPACE
Definition: parsenodes.h:2177
@ OBJECT_ROLE
Definition: parsenodes.h:2168
@ OBJECT_EXTENSION
Definition: parsenodes.h:2150
@ OBJECT_INDEX
Definition: parsenodes.h:2155
@ OBJECT_DATABASE
Definition: parsenodes.h:2144
@ OBJECT_PUBLICATION
Definition: parsenodes.h:2165
@ OBJECT_SUBSCRIPTION
Definition: parsenodes.h:2173
@ OBJECT_STATISTIC_EXT
Definition: parsenodes.h:2174
#define CURSOR_OPT_PARALLEL_OK
Definition: parsenodes.h:3178
#define ACL_CREATE
Definition: parsenodes.h:91
#define MAXPGPATH
const void size_t len
void recordDependencyOn(const ObjectAddress *depender, const ObjectAddress *referenced, DependencyType behavior)
Definition: pg_depend.c:44
long changeDependencyFor(Oid classId, Oid objectId, Oid refClassId, Oid oldRefObjectId, Oid newRefObjectId)
Definition: pg_depend.c:399
long deleteDependencyRecordsForClass(Oid classId, Oid objectId, Oid refclassId, char deptype)
Definition: pg_depend.c:293
Oid getExtensionOfObject(Oid classId, Oid objectId)
Definition: pg_depend.c:674
FormData_pg_depend * Form_pg_depend
Definition: pg_depend.h:72
static char * filename
Definition: pg_dumpall.c:94
FormData_pg_extension * Form_pg_extension
Definition: pg_extension.h:52
#define lfirst(lc)
Definition: pg_list.h:170
#define lfirst_node(type, lc)
Definition: pg_list.h:174
static int list_length(const List *l)
Definition: pg_list.h:150
#define NIL
Definition: pg_list.h:66
#define linitial_oid(l)
Definition: pg_list.h:178
#define lfirst_oid(lc)
Definition: pg_list.h:172
void recordDependencyOnOwner(Oid classId, Oid objectId, Oid owner)
Definition: pg_shdepend.c:164
static char * buf
Definition: pg_test_fsync.c:67
#define ERRCODE_UNDEFINED_TABLE
Definition: pgbench.c:81
void get_share_path(const char *my_exec_path, char *ret_path)
Definition: path.c:825
#define is_absolute_path(filename)
Definition: port.h:89
char * first_dir_separator(const char *filename)
Definition: path.c:104
#define snprintf
Definition: port.h:225
List * pg_parse_query(const char *query_string)
Definition: postgres.c:592
List * pg_analyze_and_rewrite_fixedparams(RawStmt *parsetree, const char *query_string, const Oid *paramTypes, int numParams, QueryEnvironment *queryEnv)
Definition: postgres.c:640
List * pg_plan_queries(List *querytrees, const char *query_string, int cursorOptions, ParamListInfo boundParams)
Definition: postgres.c:951
#define CStringGetDatum(X)
Definition: postgres.h:622
uintptr_t Datum
Definition: postgres.h:411
#define ObjectIdGetDatum(X)
Definition: postgres.h:551
#define BoolGetDatum(X)
Definition: postgres.h:446
#define PointerGetDatum(X)
Definition: postgres.h:600
#define InvalidOid
Definition: postgres_ext.h:36
unsigned int Oid
Definition: postgres_ext.h:31
void FreeQueryDesc(QueryDesc *qdesc)
Definition: pquery.c:105
QueryDesc * CreateQueryDesc(PlannedStmt *plannedstmt, const char *sourceText, Snapshot snapshot, Snapshot crosscheck_snapshot, DestReceiver *dest, ParamListInfo params, QueryEnvironment *queryEnv, int instrument_options)
Definition: pquery.c:67
Datum textregexreplace(PG_FUNCTION_ARGS)
Definition: regexp.c:644
#define RelationGetDescr(relation)
Definition: rel.h:514
const char * quote_identifier(const char *ident)
Definition: ruleutils.c:12189
void ScanKeyInit(ScanKey entry, AttrNumber attributeNumber, StrategyNumber strategy, RegProcedure procedure, Datum argument)
Definition: scankey.c:76
Oid CreateSchemaCommand(CreateSchemaStmt *stmt, const char *queryString, int stmt_location, int stmt_len)
Definition: schemacmds.c:50
@ ForwardScanDirection
Definition: sdir.h:26
Snapshot GetTransactionSnapshot(void)
Definition: snapmgr.c:250
void PopActiveSnapshot(void)
Definition: snapmgr.c:776
void PushActiveSnapshot(Snapshot snap)
Definition: snapmgr.c:682
Snapshot GetActiveSnapshot(void)
Definition: snapmgr.c:803
void relation_close(Relation relation, LOCKMODE lockmode)
Definition: relation.c:206
#define BTEqualStrategyNumber
Definition: stratnum.h:31
#define ERRCODE_DUPLICATE_OBJECT
Definition: streamutil.c:32
void appendStringInfo(StringInfo str, const char *fmt,...)
Definition: stringinfo.c:91
void appendStringInfoString(StringInfo str, const char *s)
Definition: stringinfo.c:176
void initStringInfo(StringInfo str)
Definition: stringinfo.c:59
char * name
Definition: guc.h:138
struct ConfigVariable * next
Definition: guc.h:145
char * value
Definition: guc.h:139
RoleSpec * authrole
Definition: parsenodes.h:2201
Definition: dirent.c:26
char * defname
Definition: parsenodes.h:766
Node * arg
Definition: parsenodes.h:767
char * default_version
Definition: extension.c:81
char * module_pathname
Definition: extension.c:82
struct ExtensionVersionInfo * previous
Definition: extension.c:104
ItemPointerData t_self
Definition: htup.h:65
Definition: pg_list.h:52
Definition: nodes.h:575
Node * utilityStmt
Definition: plannodes.h:87
TupleDesc rd_att
Definition: rel.h:110
TupleDesc setDesc
Definition: execnodes.h:317
Tuplestorestate * setResult
Definition: execnodes.h:316
Definition: dirent.h:10
char d_name[MAX_PATH]
Definition: dirent.h:15
Definition: c.h:687
__int64 st_size
Definition: win32_port.h:273
Definition: c.h:633
bool superuser(void)
Definition: superuser.c:46
void table_close(Relation relation, LOCKMODE lockmode)
Definition: table.c:167
Relation table_open(Oid relationId, LOCKMODE lockmode)
Definition: table.c:39
void tuplestore_putvalues(Tuplestorestate *state, TupleDesc tdesc, Datum *values, bool *isnull)
Definition: tuplestore.c:750
void ProcessUtility(PlannedStmt *pstmt, const char *queryString, bool readOnlyTree, ProcessUtilityContext context, ParamListInfo params, QueryEnvironment *queryEnv, DestReceiver *dest, QueryCompletion *qc)
Definition: utility.c:506
@ PROCESS_UTILITY_QUERY
Definition: utility.h:23
String * makeString(char *str)
Definition: value.c:63
#define strVal(v)
Definition: value.h:72
char * text_to_cstring(const text *t)
Definition: varlena.c:221
bool SplitIdentifierString(char *rawstring, char separator, List **namelist)
Definition: varlena.c:3715
Datum replace_text(PG_FUNCTION_ARGS)
Definition: varlena.c:4254
#define stat
Definition: win32_port.h:283
void CommandCounterIncrement(void)
Definition: xact.c:1074
int MyXactFlags
Definition: xact.c:135
#define XACT_FLAGS_ACCESSEDTEMPNAMESPACE
Definition: xact.h:102