1 /*-------------------------------------------------------------------------
5 * These routines execute some of the CREATE statements. In an earlier
6 * version of Postgres, these were "define" statements.
8 * Portions Copyright (c) 1996-2001, PostgreSQL Global Development Group
9 * Portions Copyright (c) 1994, Regents of the University of California
13 * $Header: /cvsroot/pgsql/src/backend/commands/define.c,v 1.52 2001/02/12 20:07:21 tgl Exp $
16 * The "DefineFoo" routines take the parse tree and pick out the
17 * appropriate arguments/flags, passing the results to the
18 * corresponding "FooDefine" routines (in src/catalog) that do
19 * the actual catalog-munging. These routines also verify permission
20 * of the user to execute the command.
23 * These things must be defined and committed in the following order:
25 * input/output, recv/send procedures
31 * Most of the parse-tree manipulation routines are defined in
34 *-------------------------------------------------------------------------
41 #include "access/heapam.h"
42 #include "catalog/catname.h"
43 #include "catalog/pg_aggregate.h"
44 #include "catalog/pg_language.h"
45 #include "catalog/pg_operator.h"
46 #include "catalog/pg_proc.h"
47 #include "catalog/pg_shadow.h"
48 #include "catalog/pg_type.h"
49 #include "commands/defrem.h"
51 #include "optimizer/cost.h"
52 #include "parser/parse_expr.h"
53 #include "tcop/dest.h"
54 #include "utils/builtins.h"
55 #include "utils/syscache.h"
57 static char *defGetString(DefElem *def);
58 static double defGetNumeric(DefElem *def);
59 static int defGetTypeLength(DefElem *def);
61 #define DEFAULT_TYPDELIM ','
65 case_translate_language_name(const char *input, char *output)
67 /*-------------------------------------------------------------------------
68 Translate the input language name to lower case, except if it's "C",
69 translate to upper case.
70 --------------------------------------------------------------------------*/
73 for (i = 0; i < NAMEDATALEN-1 && input[i]; ++i)
74 output[i] = tolower((unsigned char) input[i]);
78 if (strcmp(output, "c") == 0)
85 compute_return_type(TypeName *returnType,
86 char **prorettype_p, bool *returnsSet_p)
88 /*---------------------------------------------------------------------------
89 Examine the "returns" clause returnType of the CREATE FUNCTION statement
90 and return information about it as *prorettype_p and *returnsSet.
91 ----------------------------------------------------------------------------*/
92 *prorettype_p = TypeNameToInternalName(returnType);
93 *returnsSet_p = returnType->setof;
98 compute_full_attributes(List *parameters,
99 int32 *byte_pct_p, int32 *perbyte_cpu_p,
100 int32 *percall_cpu_p, int32 *outin_ratio_p,
101 bool *canCache_p, bool *isStrict_p)
103 /*--------------------------------------------------------------------------
104 Interpret the parameters *parameters and return their contents as
107 These parameters supply optional information about a function.
108 All have defaults if not specified.
110 Note: currently, only two of these parameters actually do anything:
112 * canCache means the optimizer's constant-folder is allowed to
113 pre-evaluate the function when all its inputs are constants.
115 * isStrict means the function should not be called when any NULL
116 inputs are present; instead a NULL result value should be assumed.
118 The other four parameters are not used anywhere. They used to be
119 used in the "expensive functions" optimizer, but that's been dead code
122 Since canCache and isStrict are useful for any function, we now allow
123 attributes to be supplied for all functions regardless of language.
124 ---------------------------------------------------------------------------*/
128 *byte_pct_p = BYTE_PCT;
129 *perbyte_cpu_p = PERBYTE_CPU;
130 *percall_cpu_p = PERCALL_CPU;
131 *outin_ratio_p = OUTIN_RATIO;
135 foreach(pl, parameters)
137 DefElem *param = (DefElem *) lfirst(pl);
139 if (strcasecmp(param->defname, "iscachable") == 0)
141 else if (strcasecmp(param->defname, "isstrict") == 0)
143 else if (strcasecmp(param->defname, "trusted") == 0)
147 * we don't have untrusted functions any more. The 4.2
148 * implementation is lousy anyway so I took it out. -ay 10/94
150 elog(ERROR, "untrusted function has been decommissioned.");
152 else if (strcasecmp(param->defname, "byte_pct") == 0)
153 *byte_pct_p = (int) defGetNumeric(param);
154 else if (strcasecmp(param->defname, "perbyte_cpu") == 0)
155 *perbyte_cpu_p = (int) defGetNumeric(param);
156 else if (strcasecmp(param->defname, "percall_cpu") == 0)
157 *percall_cpu_p = (int) defGetNumeric(param);
158 else if (strcasecmp(param->defname, "outin_ratio") == 0)
159 *outin_ratio_p = (int) defGetNumeric(param);
161 elog(NOTICE, "Unrecognized function attribute '%s' ignored",
168 * For a dynamically linked C language object, the form of the clause is
170 * AS <object file name> [, <link symbol name> ]
174 * AS <object reference, or sql code>
179 interpret_AS_clause(const char *languageName, const List *as,
180 char **prosrc_str_p, char **probin_str_p)
184 if (strcmp(languageName, "C") == 0)
188 * For "C" language, store the file name in probin and, when
189 * given, the link symbol name in prosrc.
191 *probin_str_p = strVal(lfirst(as));
192 if (lnext(as) == NULL)
195 *prosrc_str_p = strVal(lsecond(as));
199 /* Everything else wants the given string in prosrc. */
200 *prosrc_str_p = strVal(lfirst(as));
203 if (lnext(as) != NIL)
204 elog(ERROR, "CREATE FUNCTION: only one AS item needed for %s language",
213 * Execute a CREATE FUNCTION utility statement.
217 CreateFunction(ProcedureStmt *stmt, CommandDest dest)
220 /* pathname of executable file that executes this function, if any */
223 /* SQL that executes this function, if any */
226 /* Type of return value (or member of set of values) from function */
228 char languageName[NAMEDATALEN];
230 * name of language of function, with case adjusted: "C",
231 * "internal", "sql", etc.
235 /* The function returns a set of values, as opposed to a singleton. */
238 * The following are optional user-supplied attributes of the
248 /* Convert language name to canonical case */
249 case_translate_language_name(stmt->language, languageName);
252 * Apply appropriate security checks depending on language.
254 if (strcmp(languageName, "C") == 0 ||
255 strcmp(languageName, "internal") == 0)
259 "Only users with Postgres superuser privilege are "
260 "permitted to create a function in the '%s' language.\n\t"
261 "Others may use the 'sql' language "
262 "or the created procedural languages.",
265 else if (strcmp(languageName, "sql") == 0)
267 /* No security check needed for SQL functions */
271 HeapTuple languageTuple;
272 Form_pg_language languageStruct;
274 /* Lookup the language in the system cache */
275 languageTuple = SearchSysCache(LANGNAME,
276 PointerGetDatum(languageName),
278 if (!HeapTupleIsValid(languageTuple))
280 "Unrecognized language specified in a CREATE FUNCTION: "
281 "'%s'.\n\tRecognized languages are sql, C, "
282 "internal, and created procedural languages.",
285 /* Check that this language is a PL */
286 languageStruct = (Form_pg_language) GETSTRUCT(languageTuple);
287 if (!languageStruct->lanispl)
289 "Language '%s' isn't defined as PL", languageName);
292 * Functions in untrusted procedural languages are restricted to
293 * be defined by postgres superusers only
295 if (!languageStruct->lanpltrusted && !superuser())
296 elog(ERROR, "Only users with Postgres superuser privilege "
297 "are permitted to create a function in the '%s' "
301 ReleaseSysCache(languageTuple);
305 * Convert remaining parameters of CREATE to form wanted by
308 Assert(IsA(stmt->returnType, TypeName));
309 compute_return_type((TypeName *) stmt->returnType,
310 &prorettype, &returnsSet);
312 compute_full_attributes(stmt->withClause,
313 &byte_pct, &perbyte_cpu, &percall_cpu,
314 &outin_ratio, &canCache, &isStrict);
316 interpret_AS_clause(languageName, stmt->as, &prosrc_str, &probin_str);
319 * And now that we have all the parameters, and know we're permitted
320 * to do so, go ahead and create the function.
322 ProcedureCreate(stmt->funcname,
326 prosrc_str, /* converted to text later */
327 probin_str, /* converted to text later */
328 true, /* (obsolete "trusted") */
341 /* --------------------------------
344 * this function extracts all the information from the
345 * parameter list generated by the parser and then has
346 * OperatorCreate() do all the actual work.
348 * 'parameters' is a list of DefElem
349 * --------------------------------
352 DefineOperator(char *oprName,
355 uint16 precedence = 0; /* operator precedence */
356 bool canHash = false;/* operator hashes */
357 bool isLeftAssociative = true; /* operator is left
359 char *functionName = NULL; /* function for operator */
360 char *typeName1 = NULL; /* first type name */
361 char *typeName2 = NULL; /* second type name */
362 char *commutatorName = NULL; /* optional commutator operator
364 char *negatorName = NULL; /* optional negator operator name */
365 char *restrictionName = NULL; /* optional restrict. sel.
367 char *joinName = NULL;/* optional join sel. procedure name */
368 char *sortName1 = NULL; /* optional first sort operator */
369 char *sortName2 = NULL; /* optional second sort operator */
373 * loop over the definition list and extract the information we need.
375 foreach(pl, parameters)
377 DefElem *defel = (DefElem *) lfirst(pl);
379 if (strcasecmp(defel->defname, "leftarg") == 0)
381 typeName1 = defGetString(defel);
382 if (IsA(defel->arg, TypeName)
383 && ((TypeName *) defel->arg)->setof)
384 elog(ERROR, "setof type not implemented for leftarg");
386 else if (strcasecmp(defel->defname, "rightarg") == 0)
388 typeName2 = defGetString(defel);
389 if (IsA(defel->arg, TypeName)
390 && ((TypeName *) defel->arg)->setof)
391 elog(ERROR, "setof type not implemented for rightarg");
393 else if (strcasecmp(defel->defname, "procedure") == 0)
394 functionName = defGetString(defel);
395 else if (strcasecmp(defel->defname, "precedence") == 0)
397 /* NOT IMPLEMENTED (never worked in v4.2) */
398 elog(NOTICE, "CREATE OPERATOR: precedence not implemented");
400 else if (strcasecmp(defel->defname, "associativity") == 0)
402 /* NOT IMPLEMENTED (never worked in v4.2) */
403 elog(NOTICE, "CREATE OPERATOR: associativity not implemented");
405 else if (strcasecmp(defel->defname, "commutator") == 0)
406 commutatorName = defGetString(defel);
407 else if (strcasecmp(defel->defname, "negator") == 0)
408 negatorName = defGetString(defel);
409 else if (strcasecmp(defel->defname, "restrict") == 0)
410 restrictionName = defGetString(defel);
411 else if (strcasecmp(defel->defname, "join") == 0)
412 joinName = defGetString(defel);
413 else if (strcasecmp(defel->defname, "hashes") == 0)
415 else if (strcasecmp(defel->defname, "sort1") == 0)
418 * XXX ( ... [ , sort1 = oprname ] [ , sort2 = oprname ] ... )
419 * XXX is undocumented in the reference manual source as of
423 sortName1 = defGetString(defel);
425 else if (strcasecmp(defel->defname, "sort2") == 0)
426 sortName2 = defGetString(defel);
429 elog(NOTICE, "DefineOperator: attribute \"%s\" not recognized",
435 * make sure we have our required definitions
437 if (functionName == NULL)
438 elog(ERROR, "Define: \"procedure\" unspecified");
441 * now have OperatorCreate do all the work..
444 OperatorCreate(oprName, /* operator name */
445 typeName1, /* first type name */
446 typeName2, /* second type name */
447 functionName,/* function for operator */
448 precedence, /* operator precedence */
449 isLeftAssociative, /* operator is left associative */
450 commutatorName, /* optional commutator operator
452 negatorName, /* optional negator operator name */
453 restrictionName, /* optional restrict. sel.
455 joinName, /* optional join sel. procedure name */
456 canHash, /* operator hashes */
457 sortName1, /* optional first sort operator */
458 sortName2); /* optional second sort operator */
462 /* -------------------
467 DefineAggregate(char *aggName, List *parameters)
469 char *transfuncName = NULL;
470 char *finalfuncName = NULL;
471 char *baseType = NULL;
472 char *transType = NULL;
473 char *initval = NULL;
476 foreach(pl, parameters)
478 DefElem *defel = (DefElem *) lfirst(pl);
481 * sfunc1, stype1, and initcond1 are accepted as obsolete spellings
482 * for sfunc, stype, initcond.
484 if (strcasecmp(defel->defname, "sfunc") == 0)
485 transfuncName = defGetString(defel);
486 else if (strcasecmp(defel->defname, "sfunc1") == 0)
487 transfuncName = defGetString(defel);
488 else if (strcasecmp(defel->defname, "finalfunc") == 0)
489 finalfuncName = defGetString(defel);
490 else if (strcasecmp(defel->defname, "basetype") == 0)
491 baseType = defGetString(defel);
492 else if (strcasecmp(defel->defname, "stype") == 0)
493 transType = defGetString(defel);
494 else if (strcasecmp(defel->defname, "stype1") == 0)
495 transType = defGetString(defel);
496 else if (strcasecmp(defel->defname, "initcond") == 0)
497 initval = defGetString(defel);
498 else if (strcasecmp(defel->defname, "initcond1") == 0)
499 initval = defGetString(defel);
501 elog(NOTICE, "DefineAggregate: attribute \"%s\" not recognized",
506 * make sure we have our required definitions
508 if (baseType == NULL)
509 elog(ERROR, "Define: \"basetype\" unspecified");
510 if (transType == NULL)
511 elog(ERROR, "Define: \"stype\" unspecified");
512 if (transfuncName == NULL)
513 elog(ERROR, "Define: \"sfunc\" unspecified");
516 * Most of the argument-checking is done inside of AggregateCreate
518 AggregateCreate(aggName, /* aggregate name */
519 transfuncName, /* step function name */
520 finalfuncName, /* final function name */
521 baseType, /* type of data being aggregated */
522 transType, /* transition data type */
523 initval); /* initial condition */
528 * Registers a new type.
532 DefineType(char *typeName, List *parameters)
534 int16 internalLength = 0; /* int2 */
535 int16 externalLength = 0; /* int2 */
536 char *elemName = NULL;
537 char *inputName = NULL;
538 char *outputName = NULL;
539 char *sendName = NULL;
540 char *receiveName = NULL;
541 char *defaultValue = NULL; /* Datum */
542 bool byValue = false;
543 char delimiter = DEFAULT_TYPDELIM;
546 char alignment = 'i'; /* default alignment */
547 char storage = 'p'; /* default storage in TOAST */
550 * Type names must be one character shorter than other names,
551 * allowing room to create the corresponding array type name with
554 if (strlen(typeName) > (NAMEDATALEN - 2))
556 elog(ERROR, "DefineType: type names must be %d characters or less",
560 foreach(pl, parameters)
562 DefElem *defel = (DefElem *) lfirst(pl);
564 if (strcasecmp(defel->defname, "internallength") == 0)
565 internalLength = defGetTypeLength(defel);
566 else if (strcasecmp(defel->defname, "externallength") == 0)
567 externalLength = defGetTypeLength(defel);
568 else if (strcasecmp(defel->defname, "input") == 0)
569 inputName = defGetString(defel);
570 else if (strcasecmp(defel->defname, "output") == 0)
571 outputName = defGetString(defel);
572 else if (strcasecmp(defel->defname, "send") == 0)
573 sendName = defGetString(defel);
574 else if (strcasecmp(defel->defname, "delimiter") == 0)
576 char *p = defGetString(defel);
580 else if (strcasecmp(defel->defname, "receive") == 0)
581 receiveName = defGetString(defel);
582 else if (strcasecmp(defel->defname, "element") == 0)
583 elemName = defGetString(defel);
584 else if (strcasecmp(defel->defname, "default") == 0)
585 defaultValue = defGetString(defel);
586 else if (strcasecmp(defel->defname, "passedbyvalue") == 0)
588 else if (strcasecmp(defel->defname, "alignment") == 0)
590 char *a = defGetString(defel);
592 if (strcasecmp(a, "double") == 0)
594 else if (strcasecmp(a, "int4") == 0)
598 elog(ERROR, "DefineType: \"%s\" alignment not recognized",
602 else if (strcasecmp(defel->defname, "storage") == 0)
604 char *a = defGetString(defel);
606 if (strcasecmp(a, "plain") == 0)
608 else if (strcasecmp(a, "external") == 0)
610 else if (strcasecmp(a, "extended") == 0)
612 else if (strcasecmp(a, "main") == 0)
616 elog(ERROR, "DefineType: \"%s\" storage not recognized",
622 elog(NOTICE, "DefineType: attribute \"%s\" not recognized",
628 * make sure we have our required definitions
630 if (inputName == NULL)
631 elog(ERROR, "Define: \"input\" unspecified");
632 if (outputName == NULL)
633 elog(ERROR, "Define: \"output\" unspecified");
635 if (internalLength != -1 && storage != 'p')
636 elog(ERROR, "Define: fixed size types must have storage PLAIN");
639 * now have TypeCreate do all the real work.
642 TypeCreate(typeName, /* type name */
643 InvalidOid, /* preassigned type oid (not done here) */
644 InvalidOid, /* relation oid (n/a here) */
645 internalLength, /* internal size */
646 externalLength, /* external size */
647 'b', /* type-type (base type) */
648 delimiter, /* array element delimiter */
649 inputName, /* input procedure */
650 outputName, /* output procedure */
651 receiveName, /* receive procedure */
652 sendName, /* send procedure */
653 elemName, /* element type name */
654 defaultValue, /* default type value */
655 byValue, /* passed by value */
656 alignment, /* required alignment */
657 storage); /* TOAST strategy */
660 * When we create a base type (as opposed to a complex type)
661 * we need to have an array entry for it in pg_type as well.
664 shadow_type = makeArrayTypeName(typeName);
666 TypeCreate(shadow_type, /* type name */
667 InvalidOid, /* preassigned type oid (not done here) */
668 InvalidOid, /* relation oid (n/a here) */
669 -1, /* internal size */
670 -1, /* external size */
671 'b', /* type-type (base type) */
672 DEFAULT_TYPDELIM,/* array element delimiter */
673 "array_in", /* input procedure */
674 "array_out", /* output procedure */
675 "array_in", /* receive procedure */
676 "array_out", /* send procedure */
677 typeName, /* element type name */
678 NULL, /* never a default type value */
679 false, /* never passed by value */
680 alignment, /* NB: must be 'i' or 'd' for arrays... */
681 'x'); /* ARRAY is always toastable */
687 defGetString(DefElem *def)
689 if (def->arg == NULL)
690 elog(ERROR, "Define: \"%s\" requires a parameter",
692 switch (nodeTag(def->arg))
696 char *str = palloc(32);
698 snprintf(str, 32, "%ld", (long) intVal(def->arg));
702 /* T_Float values are kept in string form, so this type cheat
703 * works (and doesn't risk losing precision)
705 return strVal(def->arg);
707 return strVal(def->arg);
709 return TypeNameToInternalName((TypeName *) def->arg);
711 elog(ERROR, "Define: cannot interpret argument of \"%s\"",
714 return NULL; /* keep compiler quiet */
718 defGetNumeric(DefElem *def)
720 if (def->arg == NULL)
721 elog(ERROR, "Define: \"%s\" requires a numeric value",
723 switch (nodeTag(def->arg))
726 return (double) intVal(def->arg);
728 return floatVal(def->arg);
730 elog(ERROR, "Define: \"%s\" requires a numeric value",
733 return 0; /* keep compiler quiet */
737 defGetTypeLength(DefElem *def)
739 if (def->arg == NULL)
740 elog(ERROR, "Define: \"%s\" requires a parameter",
742 switch (nodeTag(def->arg))
745 return intVal(def->arg);
747 elog(ERROR, "Define: \"%s\" requires an integral value",
751 if (strcasecmp(strVal(def->arg), "variable") == 0)
752 return -1; /* variable length */
755 /* cope if grammar chooses to believe "variable" is a typename */
756 if (strcasecmp(TypeNameToInternalName((TypeName *) def->arg),
758 return -1; /* variable length */
761 elog(ERROR, "Define: cannot interpret argument of \"%s\"",
764 elog(ERROR, "Define: invalid argument for \"%s\"",
766 return 0; /* keep compiler quiet */