Newer
Older
/*-------------------------------------------------------------------------
*
* extension.c
* Commands to manipulate extensions
*
* Extensions in PostgreSQL allow management of collections of SQL objects.
*
* All we need internally to manage an extension is an OID so that the
* dependent objects can be associated with it. An extension is created by
* populating the pg_extension catalog from a "control" file.
* The extension control file is parsed with the same parser we use for
* postgresql.conf and recovery.conf. An extension also has an installation
* script file, containing SQL commands to create the extension's objects.
*
* Portions Copyright (c) 1996-2011, PostgreSQL Global Development Group
* Portions Copyright (c) 1994, Regents of the University of California
*
*
* IDENTIFICATION
* src/backend/commands/extension.c
*
*-------------------------------------------------------------------------
*/
#include "postgres.h"
#include <dirent.h>
#include <limits.h>
#include <unistd.h>
#include "access/sysattr.h"
#include "access/xact.h"
#include "catalog/dependency.h"
#include "catalog/indexing.h"
#include "catalog/namespace.h"
#include "catalog/pg_depend.h"
#include "catalog/pg_extension.h"
#include "catalog/pg_namespace.h"
#include "catalog/pg_type.h"
#include "commands/alter.h"
#include "commands/comment.h"
#include "commands/extension.h"
#include "commands/trigger.h"
#include "executor/executor.h"
#include "funcapi.h"
#include "mb/pg_wchar.h"
#include "miscadmin.h"
#include "tcop/tcopprot.h"
#include "tcop/utility.h"
#include "utils/builtins.h"
#include "utils/fmgroids.h"
#include "utils/guc.h"
#include "utils/lsyscache.h"
#include "utils/snapmgr.h"
#include "utils/tqual.h"
/* Globally visible state variables */
bool creating_extension = false;
Oid CurrentExtensionObject = InvalidOid;
/*
* Internal data structure to hold the results of parsing a control file
*/
typedef struct ExtensionControlFile
{
char *name; /* name of the extension */
char *directory; /* directory for script files */
char *default_version; /* default install target version, if any */
char *module_pathname; /* string to substitute for MODULE_PATHNAME */
char *comment; /* comment, if any */
char *schema; /* target schema (allowed if !relocatable) */
bool relocatable; /* is ALTER EXTENSION SET SCHEMA supported? */
int encoding; /* encoding of the script file, or -1 */
List *requires; /* names of prerequisite extensions */
} ExtensionControlFile;
/*
* Internal data structure for update path information
*/
typedef struct ExtensionVersionInfo
{
char *name; /* name of the starting version */
List *reachable; /* List of ExtensionVersionInfo's */
bool installable; /* does this version have an install script? */
/* working state for Dijkstra's algorithm: */
bool distance_known; /* is distance from start known yet? */
int distance; /* current worst-case distance estimate */
struct ExtensionVersionInfo *previous; /* current best predecessor */
} ExtensionVersionInfo;
/* Local functions */
static List *find_update_path(List *evi_list,
ExtensionVersionInfo *evi_start,
ExtensionVersionInfo *evi_target,
bool reinitialize);
static void get_available_versions_for_extension(ExtensionControlFile *pcontrol,
Tuplestorestate *tupstore,
TupleDesc tupdesc);
static void ApplyExtensionUpdates(Oid extensionOid,
ExtensionControlFile *pcontrol,
const char *initialVersion,
List *updateVersions);
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
/*
* get_extension_oid - given an extension name, look up the OID
*
* If missing_ok is false, throw an error if extension name not found. If
* true, just return InvalidOid.
*/
Oid
get_extension_oid(const char *extname, bool missing_ok)
{
Oid result;
Relation rel;
SysScanDesc scandesc;
HeapTuple tuple;
ScanKeyData entry[1];
rel = heap_open(ExtensionRelationId, AccessShareLock);
ScanKeyInit(&entry[0],
Anum_pg_extension_extname,
BTEqualStrategyNumber, F_NAMEEQ,
CStringGetDatum(extname));
scandesc = systable_beginscan(rel, ExtensionNameIndexId, true,
SnapshotNow, 1, entry);
tuple = systable_getnext(scandesc);
/* We assume that there can be at most one matching tuple */
if (HeapTupleIsValid(tuple))
result = HeapTupleGetOid(tuple);
else
result = InvalidOid;
systable_endscan(scandesc);
heap_close(rel, AccessShareLock);
if (!OidIsValid(result) && !missing_ok)
ereport(ERROR,
(errcode(ERRCODE_UNDEFINED_OBJECT),
errmsg("extension \"%s\" does not exist",
extname)));
return result;
}
/*
* get_extension_name - given an extension OID, look up the name
*
* Returns a palloc'd string, or NULL if no such extension.
*/
char *
get_extension_name(Oid ext_oid)
{
char *result;
Relation rel;
SysScanDesc scandesc;
HeapTuple tuple;
ScanKeyData entry[1];
rel = heap_open(ExtensionRelationId, AccessShareLock);
ScanKeyInit(&entry[0],
ObjectIdAttributeNumber,
BTEqualStrategyNumber, F_OIDEQ,
ObjectIdGetDatum(ext_oid));
scandesc = systable_beginscan(rel, ExtensionOidIndexId, true,
SnapshotNow, 1, entry);
tuple = systable_getnext(scandesc);
/* We assume that there can be at most one matching tuple */
if (HeapTupleIsValid(tuple))
result = pstrdup(NameStr(((Form_pg_extension) GETSTRUCT(tuple))->extname));
else
result = NULL;
systable_endscan(scandesc);
heap_close(rel, AccessShareLock);
return result;
}
/*
* get_extension_schema - given an extension OID, fetch its extnamespace
*
* Returns InvalidOid if no such extension.
*/
static Oid
get_extension_schema(Oid ext_oid)
{
Oid result;
Relation rel;
SysScanDesc scandesc;
HeapTuple tuple;
ScanKeyData entry[1];
rel = heap_open(ExtensionRelationId, AccessShareLock);
ScanKeyInit(&entry[0],
ObjectIdAttributeNumber,
BTEqualStrategyNumber, F_OIDEQ,
ObjectIdGetDatum(ext_oid));
scandesc = systable_beginscan(rel, ExtensionOidIndexId, true,
SnapshotNow, 1, entry);
tuple = systable_getnext(scandesc);
/* We assume that there can be at most one matching tuple */
if (HeapTupleIsValid(tuple))
result = ((Form_pg_extension) GETSTRUCT(tuple))->extnamespace;
else
result = InvalidOid;
systable_endscan(scandesc);
heap_close(rel, AccessShareLock);
return result;
}
/*
* Utility functions to check validity of extension and version names
*/
static void
check_valid_extension_name(const char *extensionname)
{
int namelen = strlen(extensionname);
/*
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
* Disallow empty names (the parser rejects empty identifiers anyway,
* but let's check).
*/
if (namelen == 0)
ereport(ERROR,
(errcode(ERRCODE_INVALID_PARAMETER_VALUE),
errmsg("invalid extension name: \"%s\"", extensionname),
errdetail("Extension names must not be empty.")));
/*
* No double dashes, since that would make script filenames ambiguous.
*/
if (strstr(extensionname, "--"))
ereport(ERROR,
(errcode(ERRCODE_INVALID_PARAMETER_VALUE),
errmsg("invalid extension name: \"%s\"", extensionname),
errdetail("Extension names must not contain \"--\".")));
/*
* No leading or trailing dash either. (We could probably allow this,
* but it would require much care in filename parsing and would make
* filenames visually if not formally ambiguous. Since there's no
* real-world use case, let's just forbid it.)
*/
if (extensionname[0] == '-' || extensionname[namelen - 1] == '-')
ereport(ERROR,
(errcode(ERRCODE_INVALID_PARAMETER_VALUE),
errmsg("invalid extension name: \"%s\"", extensionname),
errdetail("Extension names must not begin or end with \"-\".")));
/*
* No directory separators either (this is sufficient to prevent ".."
* style attacks).
*/
if (first_dir_separator(extensionname) != NULL)
ereport(ERROR,
(errcode(ERRCODE_INVALID_PARAMETER_VALUE),
errmsg("invalid extension name: \"%s\"", extensionname),
errdetail("Extension names must not contain directory separator characters.")));
}
static void
check_valid_version_name(const char *versionname)
{
int namelen = strlen(versionname);
/*
* Disallow empty names (we could possibly allow this, but there seems
* little point).
*/
if (namelen == 0)
ereport(ERROR,
(errcode(ERRCODE_INVALID_PARAMETER_VALUE),
errmsg("invalid extension version name: \"%s\"", versionname),
errdetail("Version names must not be empty.")));
/*
* No double dashes, since that would make script filenames ambiguous.
*/
if (strstr(versionname, "--"))
ereport(ERROR,
(errcode(ERRCODE_INVALID_PARAMETER_VALUE),
errmsg("invalid extension version name: \"%s\"", versionname),
errdetail("Version names must not contain \"--\".")));
/*
* No leading or trailing dash either.
*/
if (versionname[0] == '-' || versionname[namelen - 1] == '-')
ereport(ERROR,
(errcode(ERRCODE_INVALID_PARAMETER_VALUE),
errmsg("invalid extension version name: \"%s\"", versionname),
errdetail("Version names must not begin or end with \"-\".")));
/*
* No directory separators either (this is sufficient to prevent ".."
* style attacks).
*/
if (first_dir_separator(versionname) != NULL)
ereport(ERROR,
(errcode(ERRCODE_INVALID_PARAMETER_VALUE),
errmsg("invalid extension version name: \"%s\"", versionname),
errdetail("Version names must not contain directory separator characters.")));
}
/*
* Utility functions to handle extension-related path names
*/
static bool
is_extension_control_filename(const char *filename)
{
const char *extension = strrchr(filename, '.');
return (extension != NULL) && (strcmp(extension, ".control") == 0);
}
static bool
is_extension_script_filename(const char *filename)
{
const char *extension = strrchr(filename, '.');
return (extension != NULL) && (strcmp(extension, ".sql") == 0);
}
static char *
get_extension_control_directory(void)
{
char sharepath[MAXPGPATH];
char *result;
get_share_path(my_exec_path, sharepath);
result = (char *) palloc(MAXPGPATH);
snprintf(result, MAXPGPATH, "%s/extension", sharepath);
return result;
}
static char *
get_extension_control_filename(const char *extname)
{
char sharepath[MAXPGPATH];
char *result;
get_share_path(my_exec_path, sharepath);
result = (char *) palloc(MAXPGPATH);
snprintf(result, MAXPGPATH, "%s/extension/%s.control",
sharepath, extname);
return result;
}
static char *
get_extension_script_directory(ExtensionControlFile *control)
{
char sharepath[MAXPGPATH];
char *result;
/*
* The directory parameter can be omitted, absolute, or relative to the
* installation's share directory.
*/
if (!control->directory)
return get_extension_control_directory();
if (is_absolute_path(control->directory))
return pstrdup(control->directory);
get_share_path(my_exec_path, sharepath);
result = (char *) palloc(MAXPGPATH);
snprintf(result, MAXPGPATH, "%s/%s", sharepath, control->directory);
return result;
}
static char *
get_extension_aux_control_filename(ExtensionControlFile *control,
const char *version)
{
char *result;
char *scriptdir;
scriptdir = get_extension_script_directory(control);
result = (char *) palloc(MAXPGPATH);
snprintf(result, MAXPGPATH, "%s/%s--%s.control",
scriptdir, control->name, version);
pfree(scriptdir);
return result;
}
static char *
get_extension_script_filename(ExtensionControlFile *control,
const char *from_version, const char *version)
{
char *result;
char *scriptdir;
scriptdir = get_extension_script_directory(control);
result = (char *) palloc(MAXPGPATH);
if (from_version)
snprintf(result, MAXPGPATH, "%s/%s--%s--%s.sql",
scriptdir, control->name, from_version, version);
else
snprintf(result, MAXPGPATH, "%s/%s--%s.sql",
scriptdir, control->name, version);
pfree(scriptdir);
return result;
}
/*
* Parse contents of primary or auxiliary control file, and fill in
* fields of *control. We parse primary file if version == NULL,
* else the optional auxiliary file for that version.
* Control files are supposed to be very short, half a dozen lines,
* so we don't worry about memory allocation risks here. Also we don't
* worry about what encoding it's in; all values are expected to be ASCII.
static void
parse_extension_control_file(ExtensionControlFile *control,
const char *version)
char *filename;
FILE *file;
ConfigVariable *item,
*head = NULL,
*tail = NULL;
/*
* Locate the file to read. Auxiliary files are optional.
if (version)
filename = get_extension_aux_control_filename(control, version);
else
filename = get_extension_control_filename(control->name);
if ((file = AllocateFile(filename, "r")) == NULL)
{
if (version && errno == ENOENT)
{
/* no auxiliary file for this version */
pfree(filename);
return;
}
ereport(ERROR,
(errcode_for_file_access(),
errmsg("could not open extension control file \"%s\": %m",
filename)));
}
/*
* Parse the file content, using GUC's file parsing code
*/
ParseConfigFp(file, filename, 0, ERROR, &head, &tail);
FreeFile(file);
/*
* Convert the ConfigVariable list into ExtensionControlFile entries.
*/
for (item = head; item != NULL; item = item->next)
{
if (strcmp(item->name, "directory") == 0)
if (version)
ereport(ERROR,
(errcode(ERRCODE_SYNTAX_ERROR),
errmsg("parameter \"%s\" cannot be set in a secondary extension control file",
item->name)));
control->directory = pstrdup(item->value);
else if (strcmp(item->name, "default_version") == 0)
if (version)
ereport(ERROR,
(errcode(ERRCODE_SYNTAX_ERROR),
errmsg("parameter \"%s\" cannot be set in a secondary extension control file",
item->name)));
control->default_version = pstrdup(item->value);
else if (strcmp(item->name, "module_pathname") == 0)
{
control->module_pathname = pstrdup(item->value);
}
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
else if (strcmp(item->name, "comment") == 0)
{
control->comment = pstrdup(item->value);
}
else if (strcmp(item->name, "schema") == 0)
{
control->schema = pstrdup(item->value);
}
else if (strcmp(item->name, "relocatable") == 0)
{
if (!parse_bool(item->value, &control->relocatable))
ereport(ERROR,
(errcode(ERRCODE_INVALID_PARAMETER_VALUE),
errmsg("parameter \"%s\" requires a Boolean value",
item->name)));
}
else if (strcmp(item->name, "encoding") == 0)
{
control->encoding = pg_valid_server_encoding(item->value);
if (control->encoding < 0)
ereport(ERROR,
(errcode(ERRCODE_UNDEFINED_OBJECT),
errmsg("\"%s\" is not a valid encoding name",
item->value)));
}
else if (strcmp(item->name, "requires") == 0)
{
/* Need a modifiable copy of string */
char *rawnames = pstrdup(item->value);
/* Parse string into list of identifiers */
if (!SplitIdentifierString(rawnames, ',', &control->requires))
{
/* syntax error in name list */
ereport(ERROR,
(errcode(ERRCODE_INVALID_PARAMETER_VALUE),
errmsg("parameter \"%s\" must be a list of extension names",
item->name)));
}
}
else
ereport(ERROR,
(errcode(ERRCODE_SYNTAX_ERROR),
errmsg("unrecognized parameter \"%s\" in file \"%s\"",
item->name, filename)));
}
FreeConfigVariables(head);
if (control->relocatable && control->schema != NULL)
ereport(ERROR,
(errcode(ERRCODE_SYNTAX_ERROR),
errmsg("parameter \"schema\" cannot be specified when \"relocatable\" is true")));
pfree(filename);
}
/*
* Read the primary control file for the specified extension.
*/
static ExtensionControlFile *
read_extension_control_file(const char *extname)
{
ExtensionControlFile *control;
* Set up default values. Pointer fields are initially null.
control = (ExtensionControlFile *) palloc0(sizeof(ExtensionControlFile));
control->name = pstrdup(extname);
control->relocatable = false;
control->encoding = -1;
/*
* Parse the primary control file.
*/
parse_extension_control_file(control, NULL);
return control;
}
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
/*
* Read the auxiliary control file for the specified extension and version.
*
* Returns a new modified ExtensionControlFile struct; the original struct
* (reflecting just the primary control file) is not modified.
*/
static ExtensionControlFile *
read_extension_aux_control_file(const ExtensionControlFile *pcontrol,
const char *version)
{
ExtensionControlFile *acontrol;
/*
* Flat-copy the struct. Pointer fields share values with original.
*/
acontrol = (ExtensionControlFile *) palloc(sizeof(ExtensionControlFile));
memcpy(acontrol, pcontrol, sizeof(ExtensionControlFile));
/*
* Parse the auxiliary control file, overwriting struct fields
*/
parse_extension_control_file(acontrol, version);
return acontrol;
}
* Read a SQL script file into a string, and convert to database encoding
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
*/
static char *
read_extension_script_file(const ExtensionControlFile *control,
const char *filename)
{
int src_encoding;
int dest_encoding = GetDatabaseEncoding();
bytea *content;
char *src_str;
char *dest_str;
int len;
content = read_binary_file(filename, 0, -1);
/* use database encoding if not given */
if (control->encoding < 0)
src_encoding = dest_encoding;
else
src_encoding = control->encoding;
/* make sure that source string is valid in the expected encoding */
len = VARSIZE_ANY_EXHDR(content);
src_str = VARDATA_ANY(content);
pg_verify_mbstr_len(src_encoding, src_str, len, false);
/* convert the encoding to the database encoding */
dest_str = (char *) pg_do_encoding_conversion((unsigned char *) src_str,
len,
src_encoding,
dest_encoding);
/* if no conversion happened, we have to arrange for null termination */
if (dest_str == src_str)
{
dest_str = (char *) palloc(len + 1);
memcpy(dest_str, src_str, len);
dest_str[len] = '\0';
}
return dest_str;
}
/*
* Execute given SQL string.
*
* filename is used only to report errors.
*
* Note: it's tempting to just use SPI to execute the string, but that does
* not work very well. The really serious problem is that SPI will parse,
* analyze, and plan the whole string before executing any of it; of course
* this fails if there are any plannable statements referring to objects
* created earlier in the script. A lesser annoyance is that SPI insists
* on printing the whole string as errcontext in case of any error, and that
* could be very long.
*/
static void
execute_sql_string(const char *sql, const char *filename)
{
List *raw_parsetree_list;
DestReceiver *dest;
ListCell *lc1;
/*
* Parse the SQL string into a list of raw parse trees.
*/
raw_parsetree_list = pg_parse_query(sql);
/* All output from SELECTs goes to the bit bucket */
dest = CreateDestReceiver(DestNone);
/*
* Do parse analysis, rule rewrite, planning, and execution for each raw
* parsetree. We must fully execute each query before beginning parse
* analysis on the next one, since there may be interdependencies.
*/
foreach(lc1, raw_parsetree_list)
{
Node *parsetree = (Node *) lfirst(lc1);
List *stmt_list;
ListCell *lc2;
stmt_list = pg_analyze_and_rewrite(parsetree,
sql,
NULL,
0);
stmt_list = pg_plan_queries(stmt_list, 0, NULL);
foreach(lc2, stmt_list)
{
Node *stmt = (Node *) lfirst(lc2);
if (IsA(stmt, TransactionStmt))
ereport(ERROR,
(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
errmsg("transaction control statements are not allowed within an extension script")));
CommandCounterIncrement();
PushActiveSnapshot(GetTransactionSnapshot());
if (IsA(stmt, PlannedStmt) &&
((PlannedStmt *) stmt)->utilityStmt == NULL)
{
QueryDesc *qdesc;
qdesc = CreateQueryDesc((PlannedStmt *) stmt,
sql,
GetActiveSnapshot(), NULL,
dest, NULL, 0);
AfterTriggerBeginQuery();
ExecutorStart(qdesc, 0);
ExecutorRun(qdesc, ForwardScanDirection, 0);
AfterTriggerEndQuery(qdesc->estate);
ExecutorEnd(qdesc);
FreeQueryDesc(qdesc);
}
else
{
ProcessUtility(stmt,
sql,
NULL,
false, /* not top level */
dest,
NULL);
}
PopActiveSnapshot();
}
}
/* Be sure to advance the command counter after the last script command */
CommandCounterIncrement();
}
/*
* Execute the appropriate script file for installing or updating the extension
*
* If from_version isn't NULL, it's an update
*/
static void
execute_extension_script(Oid extensionOid, ExtensionControlFile *control,
const char *from_version,
const char *version,
List *requiredSchemas,
const char *schemaName, Oid schemaOid)
{
char *filename;
char *save_client_min_messages,
*save_log_min_messages,
*save_search_path;
StringInfoData pathbuf;
ListCell *lc;
filename = get_extension_script_filename(control, from_version, version);
/*
* Force client_min_messages and log_min_messages to be at least WARNING,
* so that we won't spam the user with useless NOTICE messages from common
* script actions like creating shell types.
*
* We use the equivalent of SET LOCAL to ensure the setting is undone
* upon error.
*/
save_client_min_messages =
pstrdup(GetConfigOption("client_min_messages", false));
if (client_min_messages < WARNING)
(void) set_config_option("client_min_messages", "warning",
PGC_USERSET, PGC_S_SESSION,
GUC_ACTION_LOCAL, true);
save_log_min_messages =
pstrdup(GetConfigOption("log_min_messages", false));
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
if (log_min_messages < WARNING)
(void) set_config_option("log_min_messages", "warning",
PGC_SUSET, PGC_S_SESSION,
GUC_ACTION_LOCAL, true);
/*
* Set up the search path to contain the target schema, then the schemas
* of any prerequisite extensions, and nothing else. In particular this
* makes the target schema be the default creation target namespace.
*
* Note: it might look tempting to use PushOverrideSearchPath for this,
* but we cannot do that. We have to actually set the search_path GUC
* in case the extension script examines or changes it.
*/
save_search_path = pstrdup(GetConfigOption("search_path", false));
initStringInfo(&pathbuf);
appendStringInfoString(&pathbuf, quote_identifier(schemaName));
foreach(lc, requiredSchemas)
{
Oid reqschema = lfirst_oid(lc);
char *reqname = get_namespace_name(reqschema);
if (reqname)
appendStringInfo(&pathbuf, ", %s", quote_identifier(reqname));
}
(void) set_config_option("search_path", pathbuf.data,
PGC_USERSET, PGC_S_SESSION,
GUC_ACTION_LOCAL, true);
/*
* Set creating_extension and related variables so that
* recordDependencyOnCurrentExtension and other functions do the right
* things. On failure, ensure we reset these variables.
*/
creating_extension = true;
CurrentExtensionObject = extensionOid;
PG_TRY();
{
char *sql = read_extension_script_file(control, filename);
/*
* If it's not relocatable, substitute the target schema name for
* occcurrences of @extschema@.
*
* For a relocatable extension, we just run the script as-is.
* There cannot be any need for @extschema@, else it wouldn't
* be relocatable.
*/
if (!control->relocatable)
{
const char *qSchemaName = quote_identifier(schemaName);
sql = text_to_cstring(
DatumGetTextPP(
DirectFunctionCall3(replace_text,
CStringGetTextDatum(sql),
CStringGetTextDatum("@extschema@"),
CStringGetTextDatum(qSchemaName))));
/*
* If module_pathname was set in the control file, substitute its
* value for occurrences of MODULE_PATHNAME.
*/
if (control->module_pathname)
{
sql = text_to_cstring(
DatumGetTextPP(
DirectFunctionCall3(replace_text,
CStringGetTextDatum(sql),
CStringGetTextDatum("MODULE_PATHNAME"),
CStringGetTextDatum(control->module_pathname))));
}
execute_sql_string(sql, filename);
}
PG_CATCH();
{
creating_extension = false;
CurrentExtensionObject = InvalidOid;
PG_RE_THROW();
}
PG_END_TRY();
creating_extension = false;
CurrentExtensionObject = InvalidOid;
/*
* Restore GUC variables for the remainder of the current transaction.
* Again use SET LOCAL, so we won't affect the session value.
*/
(void) set_config_option("search_path", save_search_path,
PGC_USERSET, PGC_S_SESSION,
GUC_ACTION_LOCAL, true);
(void) set_config_option("client_min_messages", save_client_min_messages,
PGC_USERSET, PGC_S_SESSION,
GUC_ACTION_LOCAL, true);
(void) set_config_option("log_min_messages", save_log_min_messages,
PGC_SUSET, PGC_S_SESSION,
GUC_ACTION_LOCAL, true);
/*
* Find or create an ExtensionVersionInfo for the specified version name
*
* Currently, we just use a List of the ExtensionVersionInfo's. Searching
* for them therefore uses about O(N^2) time when there are N versions of
* the extension. We could change the data structure to a hash table if
* this ever becomes a bottleneck.
*/
static ExtensionVersionInfo *
get_ext_ver_info(const char *versionname, List **evi_list)
{
ExtensionVersionInfo *evi;
ListCell *lc;
foreach(lc, *evi_list)
{
evi = (ExtensionVersionInfo *) lfirst(lc);
if (strcmp(evi->name, versionname) == 0)
return evi;
}
evi = (ExtensionVersionInfo *) palloc(sizeof(ExtensionVersionInfo));
evi->name = pstrdup(versionname);
evi->reachable = NIL;
evi->installable = false;
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
/* initialize for later application of Dijkstra's algorithm */
evi->distance_known = false;
evi->distance = INT_MAX;
evi->previous = NULL;
*evi_list = lappend(*evi_list, evi);
return evi;
}
/*
* Locate the nearest unprocessed ExtensionVersionInfo
*
* This part of the algorithm is also about O(N^2). A priority queue would
* make it much faster, but for now there's no need.
*/
static ExtensionVersionInfo *
get_nearest_unprocessed_vertex(List *evi_list)
{
ExtensionVersionInfo *evi = NULL;
ListCell *lc;
foreach(lc, evi_list)
{
ExtensionVersionInfo *evi2 = (ExtensionVersionInfo *) lfirst(lc);
/* only vertices whose distance is still uncertain are candidates */
if (evi2->distance_known)
continue;
/* remember the closest such vertex */
if (evi == NULL ||
evi->distance > evi2->distance)
evi = evi2;
}
return evi;
}
/*
* Obtain information about the set of update scripts available for the
* specified extension. The result is a List of ExtensionVersionInfo
* structs, each with a subsidiary list of the ExtensionVersionInfos for
* the versions that can be reached in one step from that version.
*/
static List *
get_ext_ver_list(ExtensionControlFile *control)
{
List *evi_list = NIL;
int extnamelen = strlen(control->name);
char *location;
DIR *dir;
struct dirent *de;
location = get_extension_script_directory(control);
dir = AllocateDir(location);
while ((de = ReadDir(dir, location)) != NULL)
{
char *vername;
char *vername2;
ExtensionVersionInfo *evi;
ExtensionVersionInfo *evi2;
/* must be a .sql file ... */
if (!is_extension_script_filename(de->d_name))
continue;
/* ... matching extension name followed by separator */
if (strncmp(de->d_name, control->name, extnamelen) != 0 ||
de->d_name[extnamelen] != '-' ||
de->d_name[extnamelen + 1] != '-')
continue;
/* extract version name(s) from 'extname--something.sql' filename */
vername = pstrdup(de->d_name + extnamelen + 2);
*strrchr(vername, '.') = '\0';
vername2 = strstr(vername, "--");
if (!vername2)
{
/* It's an install, not update, script; record its version name */