4 /*-------------------------------------------------------------------------
7 * POSTGRES SQL YACC rules/actions
9 * Portions Copyright (c) 1996-2001, PostgreSQL Global Development Group
10 * Portions Copyright (c) 1994, Regents of the University of California
14 * $Header: /cvsroot/pgsql/src/backend/parser/gram.y,v 2.323 2002/06/15 03:00:03 thomas Exp $
17 * AUTHOR DATE MAJOR EVENT
18 * Andrew Yu Sept, 1994 POSTQUEL to SQL conversion
19 * Andrew Yu Oct, 1994 lispy code conversion
22 * CAPITALS are used to represent terminal symbols.
23 * non-capitals are used to represent non-terminals.
24 * SQL92-specific syntax is separated from plain SQL/Postgres syntax
25 * to help isolate the non-extensible portions of the parser.
27 * In general, nothing in this file should initiate database accesses
28 * nor depend on changeable state (such as SET variables). If you do
29 * database accesses, your code will fail when we have aborted the
30 * current transaction and are just parsing commands to find the next
31 * ROLLBACK or COMMIT. If you make use of SET variables, then you
32 * will do the wrong thing in multi-query strings like this:
33 * SET SQL_inheritance TO off; SELECT * FROM foo;
34 * because the entire string is parsed by gram.y before the SET gets
35 * executed. Anything that depends on the database or changeable state
36 * should be handled inside parse_analyze() so that it happens at the
37 * right time not the wrong time. The handling of SQL_inheritance is
41 * If you use a list, make sure the datum is a node so that the printing
44 * Sometimes we assign constants to makeStrings. Make sure we don't free
47 *-------------------------------------------------------------------------
53 #include "access/htup.h"
54 #include "catalog/index.h"
55 #include "catalog/namespace.h"
56 #include "catalog/pg_type.h"
57 #include "nodes/makefuncs.h"
58 #include "nodes/params.h"
59 #include "nodes/parsenodes.h"
60 #include "parser/gramparse.h"
61 #include "storage/lmgr.h"
62 #include "utils/numeric.h"
63 #include "utils/datetime.h"
64 #include "utils/date.h"
67 #include "mb/pg_wchar.h"
69 #define GetStandardEncoding() 0 /* PG_SQL_ASCII */
70 #define GetStandardEncodingName() "SQL_ASCII"
73 extern List *parsetree; /* final parse result is delivered here */
75 static bool QueryIsRule = FALSE;
76 static Oid *param_type_info;
77 static int pfunc_num_args;
81 * If you need access to certain yacc-generated variables and find that
82 * they're static by default, uncomment the next line. (this is not a
85 /*#define __YYSCLASS*/
87 static Node *makeTypeCast(Node *arg, TypeName *typename);
88 static Node *makeStringConst(char *str, TypeName *typename);
89 static Node *makeIntConst(int val);
90 static Node *makeFloatConst(char *str);
91 static Node *makeAConst(Value *v);
92 static Node *makeRowExpr(List *opr, List *largs, List *rargs);
93 static SelectStmt *findLeftmostSelect(SelectStmt *node);
94 static void insertSelectOptions(SelectStmt *stmt,
95 List *sortClause, List *forUpdate,
96 Node *limitOffset, Node *limitCount);
97 static Node *makeSetOp(SetOperation op, bool all, Node *larg, Node *rarg);
98 static Node *doNegate(Node *n);
99 static void doNegateFloat(Value *v);
101 #define MASK(b) (1 << (b))
117 ColumnRef *columnref;
121 SortGroupBy *sortgroupby;
128 PrivTarget *privtarget;
131 VariableSetStmt *vsetstmt;
134 %type <node> stmt, schema_stmt,
135 AlterDatabaseSetStmt, AlterGroupStmt, AlterSchemaStmt, AlterTableStmt,
136 AlterUserStmt, AlterUserSetStmt, AnalyzeStmt,
137 ClosePortalStmt, ClusterStmt, CommentStmt, ConstraintsSetStmt,
138 CopyStmt, CreateAsStmt, CreateDomainStmt, CreateGroupStmt, CreatePLangStmt,
139 CreateSchemaStmt, CreateSeqStmt, CreateStmt, CreateAssertStmt, CreateTrigStmt,
140 CreateUserStmt, CreatedbStmt, CursorStmt, DefineStmt, DeleteStmt,
141 DropGroupStmt, DropPLangStmt, DropSchemaStmt, DropStmt, DropAssertStmt, DropTrigStmt,
142 DropRuleStmt, DropUserStmt, DropdbStmt, ExplainStmt, FetchStmt,
143 GrantStmt, IndexStmt, InsertStmt, ListenStmt, LoadStmt, LockStmt,
144 NotifyStmt, OptimizableStmt, CreateFunctionStmt, ReindexStmt,
145 RemoveAggrStmt, RemoveFuncStmt, RemoveOperStmt,
146 RenameStmt, RevokeStmt, RuleActionStmt, RuleActionStmtOrEmpty,
147 RuleStmt, SelectStmt, TransactionStmt, TruncateStmt,
148 UnlistenStmt, UpdateStmt, VacuumStmt, VariableResetStmt,
149 VariableSetStmt, VariableShowStmt, ViewStmt, CheckPointStmt
151 %type <node> select_no_parens, select_with_parens, select_clause,
154 %type <node> alter_column_default
155 %type <ival> drop_behavior, opt_drop_behavior
157 %type <list> createdb_opt_list, createdb_opt_item
158 %type <boolean> opt_equal
160 %type <ival> opt_lock, lock_type
161 %type <boolean> opt_force, opt_or_replace
163 %type <list> user_list
165 %type <list> OptGroupList
166 %type <defelt> OptGroupElem
168 %type <list> OptUserList
169 %type <defelt> OptUserElem
171 %type <str> OptSchemaName
172 %type <list> OptSchemaEltList
174 %type <boolean> TriggerActionTime, TriggerForSpec, opt_trusted, opt_procedural
175 %type <str> opt_lancompiler
177 %type <str> TriggerEvents
178 %type <value> TriggerFuncArg
180 %type <str> relation_name, copy_file_name, copy_delimiter, copy_null,
181 database_name, access_method_clause, access_method, attr_name,
182 index_name, name, function_name, file_name
184 %type <list> func_name, handler_name, qual_Op, qual_all_Op, OptUseOp,
185 opt_class, opt_validator
187 %type <range> qualified_name, OptConstrFromTable
190 all_Op, MathOp, opt_name, SpecialRuleRelation
192 %type <str> opt_level, opt_encoding
194 %type <list> grantee_list
195 %type <ival> privilege
196 %type <list> privileges, privilege_list
197 %type <privtarget> privilege_target
198 %type <node> function_with_argtypes
199 %type <list> function_with_argtypes_list
200 %type <chr> TriggerOneEvent
202 %type <list> stmtblock, stmtmulti,
203 OptTableElementList, OptInherit, definition, opt_distinct,
204 opt_with, func_args, func_args_list, func_as, createfunc_opt_list
205 oper_argtypes, RuleActionList, RuleActionMulti,
206 opt_column_list, columnList, opt_name_list,
207 sort_clause, sortby_list, index_params, index_list, name_list,
208 from_clause, from_list, opt_array_bounds, qualified_name_list,
209 any_name, any_name_list, any_operator, expr_list, dotted_name, attrs,
210 target_list, update_target_list, insert_column_list,
212 def_list, opt_indirection, group_clause, TriggerFuncArgs,
213 select_limit, opt_select_limit
215 %type <range> into_clause, OptTempTableName
217 %type <defelt> createfunc_opt_item
218 %type <typnam> func_arg, func_return, func_type, aggr_argtype
220 %type <boolean> opt_arg, TriggerForOpt, TriggerForType, OptTemp, OptWithOids
222 %type <list> for_update_clause, opt_for_update_clause, update_list
223 %type <boolean> opt_all
224 %type <boolean> opt_table
225 %type <boolean> opt_chain, opt_trans
227 %type <node> join_outer, join_qual
228 %type <jtype> join_type
230 %type <list> extract_list, overlay_list, position_list
231 %type <list> substr_list, trim_list
232 %type <ival> opt_interval
233 %type <node> overlay_placing, substr_from, substr_for
235 %type <boolean> opt_binary, opt_using, opt_instead, opt_cursor
236 %type <boolean> opt_with_copy, index_opt_unique, opt_verbose, opt_full
237 %type <boolean> opt_freeze, analyze_keyword
239 %type <ival> copy_dirn, direction, reindex_type, drop_type,
240 opt_column, event, comment_type
242 %type <ival> fetch_how_many
244 %type <node> select_limit_value, select_offset_value
246 %type <list> OptSeqList
247 %type <defelt> OptSeqElem
249 %type <istmt> insert_rest
251 %type <vsetstmt> set_rest
253 %type <node> OptTableElement, ConstraintElem
254 %type <node> columnDef
255 %type <defelt> def_elem
256 %type <node> def_arg, columnElem, where_clause, insert_column_item,
257 a_expr, b_expr, c_expr, AexprConst,
258 in_expr, having_clause, func_table
259 %type <list> row_descriptor, row_list, in_expr_nodes
260 %type <node> row_expr
261 %type <node> case_expr, case_arg, when_clause, case_default
262 %type <list> when_clause_list
263 %type <ival> sub_type
264 %type <list> OptCreateAs, CreateAsList
265 %type <node> CreateAsElement
266 %type <value> NumericOnly, FloatOnly, IntegerOnly
267 %type <columnref> columnref
268 %type <alias> alias_clause
269 %type <sortgroupby> sortby
270 %type <ielem> index_elem, func_index
271 %type <node> table_ref
272 %type <jexpr> joined_table
273 %type <range> relation_expr
274 %type <target> target_el, insert_target_el, update_target_el
276 %type <typnam> Typename, SimpleTypename, ConstTypename,
277 GenericType, Numeric, opt_float, Character,
278 ConstDatetime, ConstInterval, Bit
279 %type <str> character
280 %type <str> extract_arg
281 %type <str> opt_charset, opt_collate
282 %type <ival> opt_numeric, opt_decimal
283 %type <boolean> opt_varying, opt_timezone
286 %type <str> Sconst, comment_text
287 %type <str> UserId, opt_boolean, ColId_or_Sconst
288 %type <list> var_list, var_list_or_default
289 %type <str> ColId, ColLabel, type_name
290 %type <node> var_value, zone_value
292 %type <keyword> unreserved_keyword, func_name_keyword
293 %type <keyword> col_name_keyword, reserved_keyword
295 %type <node> TableConstraint
296 %type <list> ColQualList
297 %type <node> ColConstraint, ColConstraintElem, ConstraintAttr
298 %type <ival> key_actions, key_delete, key_update, key_reference
299 %type <str> key_match
300 %type <ival> ConstraintAttributeSpec, ConstraintDeferrabilitySpec,
303 %type <list> constraints_set_list
304 %type <boolean> constraints_set_mode
306 %type <boolean> opt_as
310 * If you make any token changes, update the keyword table in
311 * parser/keywords.c and add new keywords to the appropriate one of
312 * the reserved-or-not-so-reserved keyword lists, below.
315 /* ordinary key words in alphabetical order */
316 %token <keyword> ABORT_TRANS, ABSOLUTE, ACCESS, ACTION, ADD, AFTER,
317 AGGREGATE, ALL, ALTER, ANALYSE, ANALYZE, AND, ANY, AS, ASC, ASSERTION,
320 BACKWARD, BEFORE, BEGIN_TRANS, BETWEEN, BIGINT, BINARY, BIT, BOTH,
323 CACHE, CALLED, CASCADE, CASE, CAST, CHAIN, CHAR_P, CHARACTER,
324 CHARACTERISTICS, CHECK, CHECKPOINT, CLOSE, CLUSTER, COALESCE, COLLATE,
325 COLUMN, COMMENT, COMMIT, COMMITTED, CONSTRAINT, CONSTRAINTS, COPY,
326 CREATE, CREATEDB, CREATEUSER, CROSS, CURRENT_DATE, CURRENT_TIME,
327 CURRENT_TIMESTAMP, CURRENT_USER, CURSOR, CYCLE,
329 DATABASE, DAY_P, DEC, DECIMAL, DECLARE, DEFAULT, DEFERRABLE, DEFERRED,
330 DEFINER, DELETE_P, DELIMITERS, DESC, DISTINCT, DO, DOMAIN_P, DOUBLE, DROP,
332 EACH, ELSE, ENCODING, ENCRYPTED, END_TRANS, ESCAPE, EXCEPT, EXCLUSIVE,
333 EXECUTE, EXISTS, EXPLAIN, EXTERNAL, EXTRACT,
335 FALSE_P, FETCH, FLOAT_P, FOR, FORCE, FOREIGN, FORWARD, FREEZE, FROM,
338 GET, GLOBAL, GRANT, GROUP_P,
339 HANDLER, HAVING, HOUR_P,
341 ILIKE, IMMEDIATE, IMMUTABLE, IMPLICIT, IN_P, INCREMENT, INDEX, INHERITS,
342 INITIALLY, INNER_P, INOUT, INPUT, INSENSITIVE, INSERT, INSTEAD, INT,
343 INTEGER, INTERSECT, INTERVAL, INTO, INVOKER, IS, ISNULL, ISOLATION,
348 LANCOMPILER, LANGUAGE, LEADING, LEFT, LEVEL, LIKE, LIMIT, LISTEN,
349 LOAD, LOCAL, LOCALTIME, LOCALTIMESTAMP, LOCATION, LOCK_P,
351 MATCH, MAXVALUE, MINUTE_P, MINVALUE, MODE, MONTH_P, MOVE,
353 NAMES, NATIONAL, NATURAL, NCHAR, NEW, NEXT, NO, NOCREATEDB,
354 NOCREATEUSER, NONE, NOT, NOTHING, NOTIFY, NOTNULL, NULL_P, NULLIF,
357 OF, OFF, OFFSET, OIDS, OLD, ON, ONLY, OPERATOR, OPTION, OR, ORDER,
358 OUT_P, OUTER_P, OVERLAPS, OVERLAY, OWNER,
360 PARTIAL, PASSWORD, PATH_P, PENDANT, PLACING, POSITION, PRECISION, PRIMARY,
361 PRIOR, PRIVILEGES, PROCEDURE, PROCEDURAL,
363 READ, REAL, REFERENCES, REINDEX, RELATIVE, RENAME, REPLACE, RESET,
364 RESTRICT, RETURNS, REVOKE, RIGHT, ROLLBACK, ROW, RULE,
366 SCHEMA, SCROLL, SECOND_P, SECURITY, SELECT, SEQUENCE, SERIALIZABLE,
367 SESSION, SESSION_USER, SET, SETOF, SHARE, SHOW, SIMILAR, SMALLINT, SOME,
368 STABLE, START, STATEMENT, STATISTICS, STDIN, STDOUT, STORAGE, STRICT,
371 TABLE, TEMP, TEMPLATE, TEMPORARY, THEN, TIME, TIMESTAMP, TO, TOAST,
372 TRAILING, TRANSACTION, TRIGGER, TRIM, TRUE_P, TRUNCATE, TRUSTED, TYPE_P,
374 UNENCRYPTED, UNION, UNIQUE, UNKNOWN, UNLISTEN, UNTIL, UPDATE, USAGE,
377 VACUUM, VALID, VALIDATOR, VALUES, VARCHAR, VARYING, VERBOSE, VERSION, VIEW, VOLATILE,
378 WHEN, WHERE, WITH, WITHOUT, WORK,
382 /* The grammar thinks these are keywords, but they are not in the keywords.c
383 * list and so can never be entered directly. The filter in parser.c
384 * creates these tokens when required.
388 /* Special keywords, not in the query language - see the "lex" file */
389 %token <str> IDENT, FCONST, SCONST, BITCONST, Op
390 %token <ival> ICONST, PARAM
392 /* these are not real. they are here so that they get generated as #define's*/
395 /* precedence: lowest to highest */
398 %left JOIN UNIONJOIN CROSS LEFT FULL RIGHT INNER_P NATURAL
404 %nonassoc LIKE ILIKE SIMILAR
409 %left POSTFIXOP /* dummy for postfix Op rules */
410 %left Op OPERATOR /* multi-character ops and user-defined operators */
413 %nonassoc IS NULL_P TRUE_P FALSE_P UNKNOWN /* sets precedence for IS NULL, etc */
417 /* Unary Operators */
418 %left AT ZONE /* sets precedence for AT TIME ZONE */
428 * Handle comment-only lines, and ;; SELECT * FROM pg_class ;;;
429 * psql already handles such cases, but other interfaces don't.
436 /* the thrashing around here is to discard "empty" statements... */
437 stmtmulti: stmtmulti ';' stmt
438 { if ($3 != (Node *)NULL)
439 $$ = lappend($1, $3);
444 { if ($1 != (Node *)NULL)
451 stmt : AlterDatabaseSetStmt
511 { $$ = (Node *)NULL; }
514 /*****************************************************************************
516 * Create a new Postgres DBMS user
519 *****************************************************************************/
521 CreateUserStmt: CREATE USER UserId OptUserList
523 CreateUserStmt *n = makeNode(CreateUserStmt);
528 | CREATE USER UserId WITH OptUserList
530 CreateUserStmt *n = makeNode(CreateUserStmt);
537 /*****************************************************************************
539 * Alter a postgresql DBMS user
542 *****************************************************************************/
544 AlterUserStmt: ALTER USER UserId OptUserList
546 AlterUserStmt *n = makeNode(AlterUserStmt);
551 | ALTER USER UserId WITH OptUserList
553 AlterUserStmt *n = makeNode(AlterUserStmt);
561 AlterUserSetStmt: ALTER USER UserId SET set_rest
563 AlterUserSetStmt *n = makeNode(AlterUserSetStmt);
565 n->variable = $5->name;
569 | ALTER USER UserId VariableResetStmt
571 AlterUserSetStmt *n = makeNode(AlterUserSetStmt);
573 n->variable = ((VariableResetStmt *)$4)->name;
580 /*****************************************************************************
582 * Drop a postgresql DBMS user
585 *****************************************************************************/
587 DropUserStmt: DROP USER user_list
589 DropUserStmt *n = makeNode(DropUserStmt);
596 * Options for CREATE USER and ALTER USER
598 OptUserList: OptUserList OptUserElem { $$ = lappend($1, $2); }
599 | /* EMPTY */ { $$ = NIL; }
602 OptUserElem: PASSWORD Sconst
604 $$ = makeNode(DefElem);
605 $$->defname = "password";
606 $$->arg = (Node *)makeString($2);
608 | ENCRYPTED PASSWORD Sconst
610 $$ = makeNode(DefElem);
611 $$->defname = "encryptedPassword";
612 $$->arg = (Node *)makeString($3);
614 | UNENCRYPTED PASSWORD Sconst
616 $$ = makeNode(DefElem);
617 $$->defname = "unencryptedPassword";
618 $$->arg = (Node *)makeString($3);
622 $$ = makeNode(DefElem);
623 $$->defname = "sysid";
624 $$->arg = (Node *)makeInteger($2);
628 $$ = makeNode(DefElem);
629 $$->defname = "createdb";
630 $$->arg = (Node *)makeInteger(TRUE);
634 $$ = makeNode(DefElem);
635 $$->defname = "createdb";
636 $$->arg = (Node *)makeInteger(FALSE);
640 $$ = makeNode(DefElem);
641 $$->defname = "createuser";
642 $$->arg = (Node *)makeInteger(TRUE);
646 $$ = makeNode(DefElem);
647 $$->defname = "createuser";
648 $$->arg = (Node *)makeInteger(FALSE);
650 | IN_P GROUP_P user_list
652 $$ = makeNode(DefElem);
653 $$->defname = "groupElts";
654 $$->arg = (Node *)$3;
658 $$ = makeNode(DefElem);
659 $$->defname = "validUntil";
660 $$->arg = (Node *)makeString($3);
664 user_list: user_list ',' UserId
666 $$ = lappend($1, makeString($3));
670 $$ = makeList1(makeString($1));
676 /*****************************************************************************
678 * Create a postgresql group
681 *****************************************************************************/
683 CreateGroupStmt: CREATE GROUP_P UserId OptGroupList
685 CreateGroupStmt *n = makeNode(CreateGroupStmt);
690 | CREATE GROUP_P UserId WITH OptGroupList
692 CreateGroupStmt *n = makeNode(CreateGroupStmt);
700 * Options for CREATE GROUP
702 OptGroupList: OptGroupList OptGroupElem { $$ = lappend($1, $2); }
703 | /* EMPTY */ { $$ = NIL; }
706 OptGroupElem: USER user_list
708 $$ = makeNode(DefElem);
709 $$->defname = "userElts";
710 $$->arg = (Node *)$2;
714 $$ = makeNode(DefElem);
715 $$->defname = "sysid";
716 $$->arg = (Node *)makeInteger($2);
721 /*****************************************************************************
723 * Alter a postgresql group
726 *****************************************************************************/
728 AlterGroupStmt: ALTER GROUP_P UserId ADD USER user_list
730 AlterGroupStmt *n = makeNode(AlterGroupStmt);
736 | ALTER GROUP_P UserId DROP USER user_list
738 AlterGroupStmt *n = makeNode(AlterGroupStmt);
747 /*****************************************************************************
749 * Drop a postgresql group
752 *****************************************************************************/
754 DropGroupStmt: DROP GROUP_P UserId
756 DropGroupStmt *n = makeNode(DropGroupStmt);
763 /*****************************************************************************
765 * Manipulate a schema
768 *****************************************************************************/
770 CreateSchemaStmt: CREATE SCHEMA OptSchemaName AUTHORIZATION UserId OptSchemaEltList
772 CreateSchemaStmt *n = makeNode(CreateSchemaStmt);
773 /* One can omit the schema name or the authorization id... */
782 | CREATE SCHEMA ColId OptSchemaEltList
784 CreateSchemaStmt *n = makeNode(CreateSchemaStmt);
785 /* ...but not both */
793 AlterSchemaStmt: ALTER SCHEMA ColId
795 elog(ERROR, "ALTER SCHEMA not yet supported");
799 DropSchemaStmt: DROP SCHEMA ColId
801 elog(ERROR, "DROP SCHEMA not yet supported");
805 OptSchemaName: ColId { $$ = $1; }
806 | /* EMPTY */ { $$ = NULL; }
809 OptSchemaEltList: OptSchemaEltList schema_stmt { $$ = lappend($1, $2); }
810 | /* EMPTY */ { $$ = NIL; }
814 * schema_stmt are the ones that can show up inside a CREATE SCHEMA
815 * statement (in addition to by themselves).
817 schema_stmt: CreateStmt
823 /*****************************************************************************
825 * Set PG internal variable
826 * SET name TO 'var_value'
827 * Include SQL92 syntax (thomas 1997-10-22):
828 * SET TIME ZONE 'var_value'
830 *****************************************************************************/
832 VariableSetStmt: SET set_rest
834 VariableSetStmt *n = $2;
840 VariableSetStmt *n = $3;
844 | SET SESSION set_rest
846 VariableSetStmt *n = $3;
852 set_rest: ColId TO var_list_or_default
854 VariableSetStmt *n = makeNode(VariableSetStmt);
859 | ColId '=' var_list_or_default
861 VariableSetStmt *n = makeNode(VariableSetStmt);
866 | TIME ZONE zone_value
868 VariableSetStmt *n = makeNode(VariableSetStmt);
869 n->name = "timezone";
871 n->args = makeList1($3);
874 | TRANSACTION ISOLATION LEVEL opt_level
876 VariableSetStmt *n = makeNode(VariableSetStmt);
877 n->name = "TRANSACTION ISOLATION LEVEL";
878 n->args = makeList1(makeStringConst($4, NULL));
881 | SESSION CHARACTERISTICS AS TRANSACTION ISOLATION LEVEL opt_level
883 VariableSetStmt *n = makeNode(VariableSetStmt);
884 n->name = "default_transaction_isolation";
885 n->args = makeList1(makeStringConst($7, NULL));
890 VariableSetStmt *n = makeNode(VariableSetStmt);
891 n->name = "client_encoding";
893 n->args = makeList1(makeStringConst($2, NULL));
896 | SESSION AUTHORIZATION ColId_or_Sconst
898 VariableSetStmt *n = makeNode(VariableSetStmt);
899 n->name = "session_authorization";
900 n->args = makeList1(makeStringConst($3, NULL));
903 | SESSION AUTHORIZATION DEFAULT
905 VariableSetStmt *n = makeNode(VariableSetStmt);
906 n->name = "session_authorization";
912 var_list_or_default: var_list
919 { $$ = makeList1($1); }
920 | var_list ',' var_value
921 { $$ = lappend($1, $3); }
924 var_value: opt_boolean
925 { $$ = makeStringConst($1, NULL); }
927 { $$ = makeStringConst($1, NULL); }
929 { $$ = makeAConst($1); }
932 opt_level: READ COMMITTED { $$ = "read committed"; }
933 | SERIALIZABLE { $$ = "serializable"; }
936 opt_boolean: TRUE_P { $$ = "true"; }
937 | FALSE_P { $$ = "false"; }
939 | OFF { $$ = "off"; }
942 /* Timezone values can be:
943 * - a string such as 'pst8pdt'
944 * - an identifier such as "pst8pdt"
945 * - an integer or floating point number
946 * - a time interval per SQL99
947 * ColId gives reduce/reduce errors against ConstInterval and LOCAL,
948 * so use IDENT and reject anything which is a reserved word.
952 $$ = makeStringConst($1, NULL);
956 $$ = makeStringConst($1, NULL);
958 | ConstInterval Sconst opt_interval
960 A_Const *n = (A_Const *) makeStringConst($2, $1);
963 if (($3 & ~(MASK(HOUR) | MASK(MINUTE))) != 0)
964 elog(ERROR, "Time zone interval must be HOUR or HOUR TO MINUTE");
965 n->typename->typmod = ((($3 & 0x7FFF) << 16) | 0xFFFF);
969 | ConstInterval '(' Iconst ')' Sconst opt_interval
971 A_Const *n = (A_Const *) makeStringConst($5, $1);
972 if (($3 < 0) || ($3 > MAX_INTERVAL_PRECISION))
973 elog(ERROR, "INTERVAL(%d) precision must be between %d and %d",
974 $3, 0, MAX_INTERVAL_PRECISION);
977 if (($6 & ~(MASK(HOUR) | MASK(MINUTE))) != 0)
978 elog(ERROR, "Time zone interval must be HOUR or HOUR TO MINUTE");
979 n->typename->typmod = ((($6 & 0x7FFF) << 16) | $3);
983 n->typename->typmod = ((0x7FFF << 16) | $3);
988 | NumericOnly { $$ = makeAConst($1); }
989 | DEFAULT { $$ = NULL; }
990 | LOCAL { $$ = NULL; }
993 opt_encoding: Sconst { $$ = $1; }
994 | DEFAULT { $$ = NULL; }
995 | /*EMPTY*/ { $$ = NULL; }
998 ColId_or_Sconst: ColId { $$ = $1; }
999 | SCONST { $$ = $1; }
1003 VariableShowStmt: SHOW ColId
1005 VariableShowStmt *n = makeNode(VariableShowStmt);
1011 VariableShowStmt *n = makeNode(VariableShowStmt);
1012 n->name = "timezone";
1015 | SHOW TRANSACTION ISOLATION LEVEL
1017 VariableShowStmt *n = makeNode(VariableShowStmt);
1018 n->name = "TRANSACTION ISOLATION LEVEL";
1021 | SHOW SESSION AUTHORIZATION
1023 VariableShowStmt *n = makeNode(VariableShowStmt);
1024 n->name = "session_authorization";
1029 VariableShowStmt *n = makeNode(VariableShowStmt);
1035 VariableResetStmt: RESET ColId
1037 VariableResetStmt *n = makeNode(VariableResetStmt);
1043 VariableResetStmt *n = makeNode(VariableResetStmt);
1044 n->name = "timezone";
1047 | RESET TRANSACTION ISOLATION LEVEL
1049 VariableResetStmt *n = makeNode(VariableResetStmt);
1050 n->name = "TRANSACTION ISOLATION LEVEL";
1053 | RESET SESSION AUTHORIZATION
1055 VariableResetStmt *n = makeNode(VariableResetStmt);
1056 n->name = "session_authorization";
1061 VariableResetStmt *n = makeNode(VariableResetStmt);
1068 ConstraintsSetStmt: SET CONSTRAINTS constraints_set_list constraints_set_mode
1070 ConstraintsSetStmt *n = makeNode(ConstraintsSetStmt);
1071 n->constraints = $3;
1077 constraints_set_list: ALL { $$ = NIL; }
1078 | name_list { $$ = $1; }
1081 constraints_set_mode: DEFERRED { $$ = TRUE; }
1082 | IMMEDIATE { $$ = FALSE; }
1087 * Checkpoint statement
1089 CheckPointStmt: CHECKPOINT
1091 CheckPointStmt *n = makeNode(CheckPointStmt);
1096 /*****************************************************************************
1098 * ALTER TABLE variations
1100 *****************************************************************************/
1103 /* ALTER TABLE <relation> ADD [COLUMN] <coldef> */
1104 ALTER TABLE relation_expr ADD opt_column columnDef
1106 AlterTableStmt *n = makeNode(AlterTableStmt);
1112 /* ALTER TABLE <relation> ALTER [COLUMN] <colname> {SET DEFAULT <expr>|DROP DEFAULT} */
1113 | ALTER TABLE relation_expr ALTER opt_column ColId alter_column_default
1115 AlterTableStmt *n = makeNode(AlterTableStmt);
1122 /* ALTER TABLE <relation> ALTER [COLUMN] <colname> DROP NOT NULL */
1123 | ALTER TABLE relation_expr ALTER opt_column ColId DROP NOT NULL_P
1125 AlterTableStmt *n = makeNode(AlterTableStmt);
1131 /* ALTER TABLE <relation> ALTER [COLUMN] <colname> SET NOT NULL */
1132 | ALTER TABLE relation_expr ALTER opt_column ColId SET NOT NULL_P
1134 AlterTableStmt *n = makeNode(AlterTableStmt);
1140 /* ALTER TABLE <relation> ALTER [COLUMN] <colname> SET STATISTICS <Iconst> */
1141 | ALTER TABLE relation_expr ALTER opt_column ColId SET STATISTICS Iconst
1143 AlterTableStmt *n = makeNode(AlterTableStmt);
1147 n->def = (Node *) makeInteger($9);
1150 /* ALTER TABLE <relation> ALTER [COLUMN] <colname> SET STORAGE <storagemode> */
1151 | ALTER TABLE relation_expr ALTER opt_column ColId SET STORAGE ColId
1153 AlterTableStmt *n = makeNode(AlterTableStmt);
1157 n->def = (Node *) makeString($9);
1160 /* ALTER TABLE <relation> DROP [COLUMN] <colname> {RESTRICT|CASCADE} */
1161 | ALTER TABLE relation_expr DROP opt_column ColId drop_behavior
1163 AlterTableStmt *n = makeNode(AlterTableStmt);
1170 /* ALTER TABLE <relation> ADD CONSTRAINT ... */
1171 | ALTER TABLE relation_expr ADD TableConstraint
1173 AlterTableStmt *n = makeNode(AlterTableStmt);
1179 /* ALTER TABLE <relation> DROP CONSTRAINT <name> {RESTRICT|CASCADE} */
1180 | ALTER TABLE relation_expr DROP CONSTRAINT name drop_behavior
1182 AlterTableStmt *n = makeNode(AlterTableStmt);
1189 /* ALTER TABLE <name> CREATE TOAST TABLE */
1190 | ALTER TABLE qualified_name CREATE TOAST TABLE
1192 AlterTableStmt *n = makeNode(AlterTableStmt);
1194 $3->inhOpt = INH_NO;
1198 /* ALTER TABLE <name> OWNER TO UserId */
1199 | ALTER TABLE qualified_name OWNER TO UserId
1201 AlterTableStmt *n = makeNode(AlterTableStmt);
1203 $3->inhOpt = INH_NO;
1210 alter_column_default:
1213 /* Treat SET DEFAULT NULL the same as DROP DEFAULT */
1214 if (exprIsNullConstant($3))
1219 | DROP DEFAULT { $$ = NULL; }
1222 drop_behavior: CASCADE { $$ = CASCADE; }
1223 | RESTRICT { $$ = RESTRICT; }
1226 opt_drop_behavior: CASCADE { $$ = CASCADE; }
1227 | RESTRICT { $$ = RESTRICT; }
1228 | /* EMPTY */ { $$ = RESTRICT; /* default */ }
1233 /*****************************************************************************
1238 *****************************************************************************/
1240 ClosePortalStmt: CLOSE opt_id
1242 ClosePortalStmt *n = makeNode(ClosePortalStmt);
1248 opt_id: ColId { $$ = $1; }
1249 | /*EMPTY*/ { $$ = NULL; }
1253 /*****************************************************************************
1256 * COPY [BINARY] <relname> FROM/TO
1257 * [USING DELIMITERS <delimiter>]
1259 *****************************************************************************/
1261 CopyStmt: COPY opt_binary qualified_name opt_with_copy copy_dirn copy_file_name copy_delimiter copy_null
1263 CopyStmt *n = makeNode(CopyStmt);
1282 * copy_file_name NULL indicates stdio is used. Whether stdin or stdout is
1283 * used depends on the direction. (It really doesn't make sense to copy from
1284 * stdout. We silently correct the "typo". - AY 9/94
1286 copy_file_name: Sconst { $$ = $1; }
1287 | STDIN { $$ = NULL; }
1288 | STDOUT { $$ = NULL; }
1291 opt_binary: BINARY { $$ = TRUE; }
1292 | /*EMPTY*/ { $$ = FALSE; }
1295 opt_with_copy: WITH OIDS { $$ = TRUE; }
1296 | /*EMPTY*/ { $$ = FALSE; }
1300 * the default copy delimiter is tab but the user can configure it
1302 copy_delimiter: opt_using DELIMITERS Sconst { $$ = $3; }
1303 | /*EMPTY*/ { $$ = "\t"; }
1306 opt_using: USING { $$ = TRUE; }
1307 | /*EMPTY*/ { $$ = TRUE; }
1310 copy_null: WITH NULL_P AS Sconst { $$ = $4; }
1311 | /*EMPTY*/ { $$ = "\\N"; }
1314 /*****************************************************************************
1319 *****************************************************************************/
1321 CreateStmt: CREATE OptTemp TABLE qualified_name '(' OptTableElementList ')' OptInherit OptWithOids
1323 CreateStmt *n = makeNode(CreateStmt);
1327 n->inhRelations = $8;
1328 n->constraints = NIL;
1335 * Redundancy here is needed to avoid shift/reduce conflicts,
1336 * since TEMP is not a reserved word. See also OptTempTableName.
1338 OptTemp: TEMPORARY { $$ = TRUE; }
1339 | TEMP { $$ = TRUE; }
1340 | LOCAL TEMPORARY { $$ = TRUE; }
1341 | LOCAL TEMP { $$ = TRUE; }
1344 elog(ERROR, "GLOBAL TEMPORARY TABLE is not currently supported");
1349 elog(ERROR, "GLOBAL TEMPORARY TABLE is not currently supported");
1352 | /*EMPTY*/ { $$ = FALSE; }
1355 OptTableElementList: OptTableElementList ',' OptTableElement
1358 $$ = lappend($1, $3);
1369 | /*EMPTY*/ { $$ = NIL; }
1372 OptTableElement: columnDef { $$ = $1; }
1373 | TableConstraint { $$ = $1; }
1376 columnDef: ColId Typename ColQualList opt_collate
1378 ColumnDef *n = makeNode(ColumnDef);
1381 n->constraints = $3;
1384 elog(NOTICE, "CREATE TABLE / COLLATE %s not yet implemented"
1385 "; clause ignored", $4);
1391 ColQualList: ColQualList ColConstraint { $$ = lappend($1, $2); }
1392 | /*EMPTY*/ { $$ = NIL; }
1396 CONSTRAINT name ColConstraintElem
1398 switch (nodeTag($3))
1402 Constraint *n = (Constraint *)$3;
1406 case T_FkConstraint:
1408 FkConstraint *n = (FkConstraint *)$3;
1409 n->constr_name = $2;
1423 /* DEFAULT NULL is already the default for Postgres.
1424 * But define it here and carry it forward into the system
1425 * to make it explicit.
1426 * - thomas 1998-09-13
1428 * WITH NULL and NULL are not SQL92-standard syntax elements,
1429 * so leave them out. Use DEFAULT NULL to explicitly indicate
1430 * that a column may have that value. WITH NULL leads to
1431 * shift/reduce conflicts with WITH TIME ZONE anyway.
1432 * - thomas 1999-01-08
1434 * DEFAULT expression must be b_expr not a_expr to prevent shift/reduce
1435 * conflict on NOT (since NOT might start a subsequent NOT NULL constraint,
1436 * or be part of a_expr NOT LIKE or similar constructs).
1441 Constraint *n = makeNode(Constraint);
1442 n->contype = CONSTR_NOTNULL;
1445 n->cooked_expr = NULL;
1451 Constraint *n = makeNode(Constraint);
1452 n->contype = CONSTR_NULL;
1455 n->cooked_expr = NULL;
1461 Constraint *n = makeNode(Constraint);
1462 n->contype = CONSTR_UNIQUE;
1465 n->cooked_expr = NULL;
1471 Constraint *n = makeNode(Constraint);
1472 n->contype = CONSTR_PRIMARY;
1475 n->cooked_expr = NULL;
1479 | CHECK '(' a_expr ')'
1481 Constraint *n = makeNode(Constraint);
1482 n->contype = CONSTR_CHECK;
1485 n->cooked_expr = NULL;
1491 Constraint *n = makeNode(Constraint);
1492 n->contype = CONSTR_DEFAULT;
1494 if (exprIsNullConstant($2))
1496 /* DEFAULT NULL should be reported as empty expr */
1503 n->cooked_expr = NULL;
1507 | REFERENCES qualified_name opt_column_list key_match key_actions
1509 FkConstraint *n = makeNode(FkConstraint);
1510 n->constr_name = NULL;
1516 n->deferrable = FALSE;
1517 n->initdeferred = FALSE;
1523 * ConstraintAttr represents constraint attributes, which we parse as if
1524 * they were independent constraint clauses, in order to avoid shift/reduce
1525 * conflicts (since NOT might start either an independent NOT NULL clause
1526 * or an attribute). analyze.c is responsible for attaching the attribute
1527 * information to the preceding "real" constraint node, and for complaining
1528 * if attribute clauses appear in the wrong place or wrong combinations.
1530 * See also ConstraintAttributeSpec, which can be used in places where
1531 * there is no parsing conflict.
1533 ConstraintAttr: DEFERRABLE
1535 Constraint *n = makeNode(Constraint);
1536 n->contype = CONSTR_ATTR_DEFERRABLE;
1541 Constraint *n = makeNode(Constraint);
1542 n->contype = CONSTR_ATTR_NOT_DEFERRABLE;
1545 | INITIALLY DEFERRED
1547 Constraint *n = makeNode(Constraint);
1548 n->contype = CONSTR_ATTR_DEFERRED;
1551 | INITIALLY IMMEDIATE
1553 Constraint *n = makeNode(Constraint);
1554 n->contype = CONSTR_ATTR_IMMEDIATE;
1560 /* ConstraintElem specifies constraint syntax which is not embedded into
1561 * a column definition. ColConstraintElem specifies the embedded form.
1562 * - thomas 1997-12-03
1564 TableConstraint: CONSTRAINT name ConstraintElem
1566 switch (nodeTag($3))
1570 Constraint *n = (Constraint *)$3;
1574 case T_FkConstraint:
1576 FkConstraint *n = (FkConstraint *)$3;
1577 n->constr_name = $2;
1589 ConstraintElem: CHECK '(' a_expr ')'
1591 Constraint *n = makeNode(Constraint);
1592 n->contype = CONSTR_CHECK;
1595 n->cooked_expr = NULL;
1598 | UNIQUE '(' columnList ')'
1600 Constraint *n = makeNode(Constraint);
1601 n->contype = CONSTR_UNIQUE;
1604 n->cooked_expr = NULL;
1608 | PRIMARY KEY '(' columnList ')'
1610 Constraint *n = makeNode(Constraint);
1611 n->contype = CONSTR_PRIMARY;
1614 n->cooked_expr = NULL;
1618 | FOREIGN KEY '(' columnList ')' REFERENCES qualified_name opt_column_list
1619 key_match key_actions ConstraintAttributeSpec
1621 FkConstraint *n = makeNode(FkConstraint);
1622 n->constr_name = NULL;
1628 n->deferrable = ($11 & 1) != 0;
1629 n->initdeferred = ($11 & 2) != 0;
1634 opt_column_list: '(' columnList ')' { $$ = $2; }
1635 | /*EMPTY*/ { $$ = NIL; }
1638 columnList: columnList ',' columnElem
1639 { $$ = lappend($1, $3); }
1641 { $$ = makeList1($1); }
1646 Ident *id = makeNode(Ident);
1652 key_match: MATCH FULL
1658 elog(ERROR, "FOREIGN KEY/MATCH PARTIAL not yet implemented");
1667 key_actions: key_delete { $$ = $1; }
1668 | key_update { $$ = $1; }
1669 | key_delete key_update { $$ = $1 | $2; }
1670 | key_update key_delete { $$ = $1 | $2; }
1671 | /*EMPTY*/ { $$ = 0; }
1674 key_delete: ON DELETE_P key_reference { $$ = $3 << FKCONSTR_ON_DELETE_SHIFT; }
1677 key_update: ON UPDATE key_reference { $$ = $3 << FKCONSTR_ON_UPDATE_SHIFT; }
1680 key_reference: NO ACTION { $$ = FKCONSTR_ON_KEY_NOACTION; }
1681 | RESTRICT { $$ = FKCONSTR_ON_KEY_RESTRICT; }
1682 | CASCADE { $$ = FKCONSTR_ON_KEY_CASCADE; }
1683 | SET NULL_P { $$ = FKCONSTR_ON_KEY_SETNULL; }
1684 | SET DEFAULT { $$ = FKCONSTR_ON_KEY_SETDEFAULT; }
1687 OptInherit: INHERITS '(' qualified_name_list ')' { $$ = $3; }
1688 | /*EMPTY*/ { $$ = NIL; }
1691 OptWithOids: WITH OIDS { $$ = TRUE; }
1692 | WITHOUT OIDS { $$ = FALSE; }
1693 | /*EMPTY*/ { $$ = TRUE; }
1698 * Note: CREATE TABLE ... AS SELECT ... is just another spelling for
1702 CreateAsStmt: CREATE OptTemp TABLE qualified_name OptCreateAs AS SelectStmt
1705 * When the SelectStmt is a set-operation tree, we must
1706 * stuff the INTO information into the leftmost component
1707 * Select, because that's where analyze.c will expect
1708 * to find it. Similarly, the output column names must
1709 * be attached to that Select's target list.
1711 SelectStmt *n = findLeftmostSelect((SelectStmt *) $7);
1712 if (n->into != NULL)
1713 elog(ERROR, "CREATE TABLE AS may not specify INTO");
1716 n->intoColNames = $5;
1721 OptCreateAs: '(' CreateAsList ')' { $$ = $2; }
1722 | /*EMPTY*/ { $$ = NIL; }
1725 CreateAsList: CreateAsList ',' CreateAsElement { $$ = lappend($1, $3); }
1726 | CreateAsElement { $$ = makeList1($1); }
1729 CreateAsElement: ColId
1731 ColumnDef *n = makeNode(ColumnDef);
1734 n->raw_default = NULL;
1735 n->cooked_default = NULL;
1736 n->is_not_null = FALSE;
1737 n->constraints = NULL;
1743 /*****************************************************************************
1746 * CREATE SEQUENCE seqname
1748 *****************************************************************************/
1750 CreateSeqStmt: CREATE OptTemp SEQUENCE qualified_name OptSeqList
1752 CreateSeqStmt *n = makeNode(CreateSeqStmt);
1760 OptSeqList: OptSeqList OptSeqElem
1761 { $$ = lappend($1, $2); }
1765 OptSeqElem: CACHE NumericOnly
1767 $$ = makeNode(DefElem);
1768 $$->defname = "cache";
1769 $$->arg = (Node *)$2;
1773 $$ = makeNode(DefElem);
1774 $$->defname = "cycle";
1775 $$->arg = (Node *)NULL;
1777 | INCREMENT NumericOnly
1779 $$ = makeNode(DefElem);
1780 $$->defname = "increment";
1781 $$->arg = (Node *)$2;
1783 | MAXVALUE NumericOnly
1785 $$ = makeNode(DefElem);
1786 $$->defname = "maxvalue";
1787 $$->arg = (Node *)$2;
1789 | MINVALUE NumericOnly
1791 $$ = makeNode(DefElem);
1792 $$->defname = "minvalue";
1793 $$->arg = (Node *)$2;
1797 $$ = makeNode(DefElem);
1798 $$->defname = "start";
1799 $$->arg = (Node *)$2;
1803 NumericOnly: FloatOnly { $$ = $1; }
1804 | IntegerOnly { $$ = $1; }
1820 $$ = makeInteger($1);
1824 $$ = makeInteger($2);
1825 $$->val.ival = - $$->val.ival;
1829 /*****************************************************************************
1832 * CREATE PROCEDURAL LANGUAGE ...
1833 * DROP PROCEDURAL LANGUAGE ...
1835 *****************************************************************************/
1837 CreatePLangStmt: CREATE opt_trusted opt_procedural LANGUAGE ColId_or_Sconst
1838 HANDLER handler_name opt_validator opt_lancompiler
1840 CreatePLangStmt *n = makeNode(CreatePLangStmt);
1843 n->plvalidator = $8;
1850 opt_trusted: TRUSTED { $$ = TRUE; }
1851 | /*EMPTY*/ { $$ = FALSE; }
1854 /* This ought to be just func_name, but that causes reduce/reduce conflicts
1855 * (CREATE LANGUAGE is the only place where func_name isn't followed by '(').
1856 * Work around by using name and dotted_name separately.
1859 { $$ = makeList1(makeString($1)); }
1864 opt_lancompiler: LANCOMPILER Sconst { $$ = $2; }
1865 | /*EMPTY*/ { $$ = ""; }
1868 opt_validator: VALIDATOR handler_name { $$ = $2; }
1869 | /*EMPTY*/ { $$ = NULL; }
1872 DropPLangStmt: DROP opt_procedural LANGUAGE ColId_or_Sconst
1874 DropPLangStmt *n = makeNode(DropPLangStmt);
1880 opt_procedural: PROCEDURAL { $$ = TRUE; }
1881 | /*EMPTY*/ { $$ = TRUE; }
1884 /*****************************************************************************
1887 * CREATE TRIGGER ...
1890 *****************************************************************************/
1892 CreateTrigStmt: CREATE TRIGGER name TriggerActionTime TriggerEvents ON
1893 qualified_name TriggerForSpec EXECUTE PROCEDURE
1894 func_name '(' TriggerFuncArgs ')'
1896 CreateTrigStmt *n = makeNode(CreateTrigStmt);
1903 memcpy (n->actions, $5, 4);
1904 n->lang = NULL; /* unused */
1905 n->text = NULL; /* unused */
1906 n->attr = NULL; /* unused */
1907 n->when = NULL; /* unused */
1909 n->isconstraint = FALSE;
1910 n->deferrable = FALSE;
1911 n->initdeferred = FALSE;
1912 n->constrrel = NULL;
1915 | CREATE CONSTRAINT TRIGGER name AFTER TriggerEvents ON
1916 qualified_name OptConstrFromTable
1917 ConstraintAttributeSpec
1918 FOR EACH ROW EXECUTE PROCEDURE
1919 func_name '(' TriggerFuncArgs ')'
1921 CreateTrigStmt *n = makeNode(CreateTrigStmt);
1928 memcpy (n->actions, $6, 4);
1929 n->lang = NULL; /* unused */
1930 n->text = NULL; /* unused */
1931 n->attr = NULL; /* unused */
1932 n->when = NULL; /* unused */
1934 n->isconstraint = TRUE;
1935 n->deferrable = ($10 & 1) != 0;
1936 n->initdeferred = ($10 & 2) != 0;
1943 TriggerActionTime: BEFORE { $$ = TRUE; }
1944 | AFTER { $$ = FALSE; }
1947 TriggerEvents: TriggerOneEvent
1949 char *e = palloc (4);
1950 e[0] = $1; e[1] = 0; $$ = e;
1952 | TriggerOneEvent OR TriggerOneEvent
1954 char *e = palloc (4);
1955 e[0] = $1; e[1] = $3; e[2] = 0; $$ = e;
1957 | TriggerOneEvent OR TriggerOneEvent OR TriggerOneEvent
1959 char *e = palloc (4);
1960 e[0] = $1; e[1] = $3; e[2] = $5; e[3] = 0;
1965 TriggerOneEvent: INSERT { $$ = 'i'; }
1966 | DELETE_P { $$ = 'd'; }
1967 | UPDATE { $$ = 'u'; }
1970 TriggerForSpec: FOR TriggerForOpt TriggerForType
1976 TriggerForOpt: EACH { $$ = TRUE; }
1977 | /*EMPTY*/ { $$ = FALSE; }
1980 TriggerForType: ROW { $$ = TRUE; }
1981 | STATEMENT { $$ = FALSE; }
1984 TriggerFuncArgs: TriggerFuncArg
1985 { $$ = makeList1($1); }
1986 | TriggerFuncArgs ',' TriggerFuncArg
1987 { $$ = lappend($1, $3); }
1992 TriggerFuncArg: ICONST
1995 sprintf (buf, "%d", $1);
1996 $$ = makeString(pstrdup(buf));
2000 $$ = makeString($1);
2004 $$ = makeString($1);
2008 $$ = makeString($1);
2012 $$ = makeString($1);
2016 OptConstrFromTable: /* Empty */
2020 | FROM qualified_name
2026 ConstraintAttributeSpec: ConstraintDeferrabilitySpec
2028 | ConstraintDeferrabilitySpec ConstraintTimeSpec
2030 if ($1 == 0 && $2 != 0)
2031 elog(ERROR, "INITIALLY DEFERRED constraint must be DEFERRABLE");
2034 | ConstraintTimeSpec
2041 | ConstraintTimeSpec ConstraintDeferrabilitySpec
2043 if ($2 == 0 && $1 != 0)
2044 elog(ERROR, "INITIALLY DEFERRED constraint must be DEFERRABLE");
2051 ConstraintDeferrabilitySpec: NOT DEFERRABLE
2057 ConstraintTimeSpec: INITIALLY IMMEDIATE
2059 | INITIALLY DEFERRED
2064 DropTrigStmt: DROP TRIGGER name ON qualified_name
2066 DropPropertyStmt *n = makeNode(DropPropertyStmt);
2069 n->removeType = DROP_TRIGGER;
2075 /*****************************************************************************
2078 * CREATE ASSERTION ...
2079 * DROP ASSERTION ...
2081 *****************************************************************************/
2083 CreateAssertStmt: CREATE ASSERTION name
2084 CHECK '(' a_expr ')' ConstraintAttributeSpec
2086 CreateTrigStmt *n = makeNode(CreateTrigStmt);
2088 n->args = makeList1($6);
2089 n->isconstraint = TRUE;
2090 n->deferrable = ($8 & 1) != 0;
2091 n->initdeferred = ($8 & 2) != 0;
2093 elog(ERROR, "CREATE ASSERTION is not yet supported");
2099 DropAssertStmt: DROP ASSERTION name
2101 DropPropertyStmt *n = makeNode(DropPropertyStmt);
2104 n->removeType = DROP_TRIGGER;
2105 elog(ERROR, "DROP ASSERTION is not yet supported");
2111 /*****************************************************************************
2114 * define (aggregate,operator,type)
2116 *****************************************************************************/
2118 DefineStmt: CREATE AGGREGATE func_name definition
2120 DefineStmt *n = makeNode(DefineStmt);
2121 n->defType = AGGREGATE;
2126 | CREATE OPERATOR any_operator definition
2128 DefineStmt *n = makeNode(DefineStmt);
2129 n->defType = OPERATOR;
2134 | CREATE TYPE_P any_name definition
2136 DefineStmt *n = makeNode(DefineStmt);
2137 n->defType = TYPE_P;
2142 | CREATE CHARACTER SET opt_as any_name GET definition opt_collate
2144 DefineStmt *n = makeNode(DefineStmt);
2145 n->defType = CHARACTER;
2152 definition: '(' def_list ')' { $$ = $2; }
2155 def_list: def_elem { $$ = makeList1($1); }
2156 | def_list ',' def_elem { $$ = lappend($1, $3); }
2159 def_elem: ColLabel '=' def_arg
2161 $$ = makeNode(DefElem);
2163 $$->arg = (Node *)$3;
2167 $$ = makeNode(DefElem);
2169 $$->arg = (Node *)NULL;
2173 /* Note: any simple identifier will be returned as a type name! */
2174 def_arg: func_return { $$ = (Node *)$1; }
2175 | all_Op { $$ = (Node *)makeString($1); }
2176 | NumericOnly { $$ = (Node *)$1; }
2177 | Sconst { $$ = (Node *)makeString($1); }
2181 /*****************************************************************************
2185 * DROP itemtype itemname [, itemname ...]
2187 *****************************************************************************/
2189 DropStmt: DROP drop_type any_name_list opt_drop_behavior
2191 DropStmt *n = makeNode(DropStmt);
2199 drop_type: TABLE { $$ = DROP_TABLE; }
2200 | SEQUENCE { $$ = DROP_SEQUENCE; }
2201 | VIEW { $$ = DROP_VIEW; }
2202 | INDEX { $$ = DROP_INDEX; }
2203 | TYPE_P { $$ = DROP_TYPE; }
2204 | DOMAIN_P { $$ = DROP_DOMAIN; }
2207 any_name_list: any_name
2208 { $$ = makeList1($1); }
2209 | any_name_list ',' any_name
2210 { $$ = lappend($1, $3); }
2214 { $$ = makeList1(makeString($1)); }
2219 /*****************************************************************************
2222 * truncate table relname
2224 *****************************************************************************/
2226 TruncateStmt: TRUNCATE opt_table qualified_name
2228 TruncateStmt *n = makeNode(TruncateStmt);
2234 /*****************************************************************************
2236 * The COMMENT ON statement can take different forms based upon the type of
2237 * the object associated with the comment. The form of the statement is:
2239 * COMMENT ON [ [ DATABASE | DOMAIN | INDEX | SEQUENCE | TABLE | TYPE | VIEW ]
2240 * <objname> | AGGREGATE <aggname> (<aggtype>) | FUNCTION
2241 * <funcname> (arg1, arg2, ...) | OPERATOR <op>
2242 * (leftoperand_typ rightoperand_typ) | TRIGGER <triggername> ON
2243 * <relname> | RULE <rulename> ON <relname> ] IS 'text'
2245 *****************************************************************************/
2247 CommentStmt: COMMENT ON comment_type any_name IS comment_text
2249 CommentStmt *n = makeNode(CommentStmt);
2256 | COMMENT ON AGGREGATE func_name '(' aggr_argtype ')' IS comment_text
2258 CommentStmt *n = makeNode(CommentStmt);
2259 n->objtype = AGGREGATE;
2261 n->objargs = makeList1($6);
2265 | COMMENT ON FUNCTION func_name func_args IS comment_text
2267 CommentStmt *n = makeNode(CommentStmt);
2268 n->objtype = FUNCTION;
2274 | COMMENT ON OPERATOR any_operator '(' oper_argtypes ')' IS comment_text
2276 CommentStmt *n = makeNode(CommentStmt);
2277 n->objtype = OPERATOR;
2283 | COMMENT ON TRIGGER name ON any_name IS comment_text
2285 CommentStmt *n = makeNode(CommentStmt);
2286 n->objtype = TRIGGER;
2287 n->objname = lappend($6, makeString($4));
2292 | COMMENT ON RULE name ON any_name IS comment_text
2294 CommentStmt *n = makeNode(CommentStmt);
2296 n->objname = lappend($6, makeString($4));
2301 | COMMENT ON RULE name IS comment_text
2303 /* Obsolete syntax supported for awhile for compatibility */
2304 CommentStmt *n = makeNode(CommentStmt);
2306 n->objname = makeList1(makeString($4));
2313 comment_type: COLUMN { $$ = COLUMN; }
2314 | DATABASE { $$ = DATABASE; }
2315 | SCHEMA { $$ = SCHEMA; }
2316 | INDEX { $$ = INDEX; }
2317 | SEQUENCE { $$ = SEQUENCE; }
2318 | TABLE { $$ = TABLE; }
2319 | DOMAIN_P { $$ = TYPE_P; }
2320 | TYPE_P { $$ = TYPE_P; }
2321 | VIEW { $$ = VIEW; }
2324 comment_text: Sconst { $$ = $1; }
2325 | NULL_P { $$ = NULL; }
2328 /*****************************************************************************
2331 * fetch/move [forward | backward] [ # | all ] [ in <portalname> ]
2332 * fetch [ forward | backward | absolute | relative ]
2333 * [ # | all | next | prior ] [ [ in | from ] <portalname> ]
2335 *****************************************************************************/
2337 FetchStmt: FETCH direction fetch_how_many from_in name
2339 FetchStmt *n = makeNode(FetchStmt);
2343 elog(ERROR,"FETCH / RELATIVE at current position is not supported");
2349 $2 = (($2 == FORWARD)? BACKWARD: FORWARD);
2357 | FETCH fetch_how_many from_in name
2359 FetchStmt *n = makeNode(FetchStmt);
2363 n->direction = BACKWARD;
2367 n->direction = FORWARD;
2374 | FETCH direction from_in name
2376 FetchStmt *n = makeNode(FetchStmt);
2387 | FETCH from_in name
2389 FetchStmt *n = makeNode(FetchStmt);
2390 n->direction = FORWARD;
2398 FetchStmt *n = makeNode(FetchStmt);
2399 n->direction = FORWARD;
2406 | MOVE direction fetch_how_many from_in name
2408 FetchStmt *n = makeNode(FetchStmt);
2412 $2 = (($2 == FORWARD)? BACKWARD: FORWARD);
2420 | MOVE fetch_how_many from_in name
2422 FetchStmt *n = makeNode(FetchStmt);
2426 n->direction = BACKWARD;
2430 n->direction = FORWARD;
2437 | MOVE direction from_in name
2439 FetchStmt *n = makeNode(FetchStmt);
2448 FetchStmt *n = makeNode(FetchStmt);
2449 n->direction = FORWARD;
2457 FetchStmt *n = makeNode(FetchStmt);
2458 n->direction = FORWARD;
2466 direction: FORWARD { $$ = FORWARD; }
2467 | BACKWARD { $$ = BACKWARD; }
2468 | RELATIVE { $$ = RELATIVE; }
2471 elog(NOTICE,"FETCH / ABSOLUTE not supported, using RELATIVE");
2476 fetch_how_many: Iconst { $$ = $1; }
2477 | '-' Iconst { $$ = - $2; }
2478 | ALL { $$ = 0; /* 0 means fetch all tuples*/ }
2480 | PRIOR { $$ = -1; }
2488 /*****************************************************************************
2490 * GRANT and REVOKE statements
2492 *****************************************************************************/
2494 GrantStmt: GRANT privileges ON privilege_target TO grantee_list opt_grant_grant_option
2496 GrantStmt *n = makeNode(GrantStmt);
2499 n->objtype = ($4)->objtype;
2500 n->objects = ($4)->objs;
2506 RevokeStmt: REVOKE opt_revoke_grant_option privileges ON privilege_target FROM grantee_list
2508 GrantStmt *n = makeNode(GrantStmt);
2509 n->is_grant = false;
2511 n->objtype = ($5)->objtype;
2512 n->objects = ($5)->objs;
2519 /* either ALL [PRIVILEGES] or a list of individual privileges */
2520 privileges: privilege_list { $$ = $1; }
2521 | ALL { $$ = makeListi1(ACL_ALL_RIGHTS); }
2522 | ALL PRIVILEGES { $$ = makeListi1(ACL_ALL_RIGHTS); }
2525 privilege_list: privilege { $$ = makeListi1($1); }
2526 | privilege_list ',' privilege { $$ = lappendi($1, $3); }
2529 /* Not all of these privilege types apply to all objects, but that
2530 * gets sorted out later.
2532 privilege: SELECT { $$ = ACL_SELECT; }
2533 | INSERT { $$ = ACL_INSERT; }
2534 | UPDATE { $$ = ACL_UPDATE; }
2535 | DELETE_P { $$ = ACL_DELETE; }
2536 | RULE { $$ = ACL_RULE; }
2537 | REFERENCES { $$ = ACL_REFERENCES; }
2538 | TRIGGER { $$ = ACL_TRIGGER; }
2539 | EXECUTE { $$ = ACL_EXECUTE; }
2540 | USAGE { $$ = ACL_USAGE; }
2541 | CREATE { $$ = ACL_CREATE; }
2542 | TEMPORARY { $$ = ACL_CREATE_TEMP; }
2543 | TEMP { $$ = ACL_CREATE_TEMP; }
2547 /* Don't bother trying to fold the first two rules into one using
2548 opt_table. You're going to get conflicts. */
2549 privilege_target: qualified_name_list
2551 PrivTarget *n = makeNode(PrivTarget);
2552 n->objtype = ACL_OBJECT_RELATION;
2556 | TABLE qualified_name_list
2558 PrivTarget *n = makeNode(PrivTarget);
2559 n->objtype = ACL_OBJECT_RELATION;
2563 | FUNCTION function_with_argtypes_list
2565 PrivTarget *n = makeNode(PrivTarget);
2566 n->objtype = ACL_OBJECT_FUNCTION;
2570 | DATABASE name_list
2572 PrivTarget *n = makeNode(PrivTarget);
2573 n->objtype = ACL_OBJECT_DATABASE;
2577 | LANGUAGE name_list
2579 PrivTarget *n = makeNode(PrivTarget);
2580 n->objtype = ACL_OBJECT_LANGUAGE;
2586 PrivTarget *n = makeNode(PrivTarget);
2587 n->objtype = ACL_OBJECT_NAMESPACE;
2594 grantee_list: grantee { $$ = makeList1($1); }
2595 | grantee_list ',' grantee { $$ = lappend($1, $3); }
2600 PrivGrantee *n = makeNode(PrivGrantee);
2601 /* This hack lets us avoid reserving PUBLIC as a keyword */
2602 if (strcmp($1, "public") == 0)
2606 n->groupname = NULL;
2611 PrivGrantee *n = makeNode(PrivGrantee);
2612 /* Treat GROUP PUBLIC as a synonym for PUBLIC */
2613 if (strcmp($2, "public") == 0)
2614 n->groupname = NULL;
2623 opt_grant_grant_option: WITH GRANT OPTION
2625 elog(ERROR, "grant options are not implemented");
2630 opt_revoke_grant_option: GRANT OPTION FOR
2632 elog(ERROR, "grant options are not implemented");
2638 function_with_argtypes_list: function_with_argtypes
2639 { $$ = makeList1($1); }
2640 | function_with_argtypes_list ',' function_with_argtypes
2641 { $$ = lappend($1, $3); }
2644 function_with_argtypes: func_name func_args
2646 FuncWithArgs *n = makeNode(FuncWithArgs);
2654 /*****************************************************************************
2657 * create index <indexname> on <relname>
2658 * [ using <access> ] "(" (<col> with <op>)+ ")"
2659 * [ where <predicate> ]
2661 *****************************************************************************/
2663 IndexStmt: CREATE index_opt_unique INDEX index_name ON qualified_name
2664 access_method_clause '(' index_params ')' where_clause
2666 IndexStmt *n = makeNode(IndexStmt);
2670 n->accessMethod = $7;
2671 n->indexParams = $9;
2672 n->whereClause = $11;
2677 index_opt_unique: UNIQUE { $$ = TRUE; }
2678 | /*EMPTY*/ { $$ = FALSE; }
2681 access_method_clause: USING access_method { $$ = $2; }
2682 /* If btree changes as our default, update pg_get_indexdef() */
2683 | /*EMPTY*/ { $$ = DEFAULT_INDEX_TYPE; }
2686 index_params: index_list { $$ = $1; }
2687 | func_index { $$ = makeList1($1); }
2690 index_list: index_list ',' index_elem { $$ = lappend($1, $3); }
2691 | index_elem { $$ = makeList1($1); }
2694 func_index: func_name '(' name_list ')' opt_class
2696 $$ = makeNode(IndexElem);
2704 index_elem: attr_name opt_class
2706 $$ = makeNode(IndexElem);
2717 * Release 7.0 removed network_ops, timespan_ops, and
2718 * datetime_ops, so we suppress it from being passed to
2719 * the parser so the default *_ops is used. This can be
2720 * removed in some later release. bjm 2000/02/07
2722 * Release 7.1 removes lztext_ops, so suppress that too
2723 * for a while. tgl 2000/07/30
2725 * Release 7.2 renames timestamp_ops to timestamptz_ops,
2726 * so suppress that too for awhile. I'm starting to
2727 * think we need a better approach. tgl 2000/10/01
2729 if (length($1) == 1)
2731 char *claname = strVal(lfirst($1));
2733 if (strcmp(claname, "network_ops") != 0 &&
2734 strcmp(claname, "timespan_ops") != 0 &&
2735 strcmp(claname, "datetime_ops") != 0 &&
2736 strcmp(claname, "lztext_ops") != 0 &&
2737 strcmp(claname, "timestamp_ops") != 0)
2745 | USING any_name { $$ = $2; }
2746 | /*EMPTY*/ { $$ = NIL; }
2749 /*****************************************************************************
2752 * execute recipe <recipeName>
2754 *****************************************************************************/
2757 RecipeStmt: EXECUTE RECIPE recipe_name
2759 RecipeStmt *n = makeNode(RecipeStmt);
2766 /*****************************************************************************
2769 * create [or replace] function <fname>
2770 * [(<type-1> { , <type-n>})]
2772 * as <filename or code in language as appropriate>
2773 * language <lang> [with parameters]
2775 *****************************************************************************/
2777 CreateFunctionStmt: CREATE opt_or_replace FUNCTION func_name func_args
2778 RETURNS func_return createfunc_opt_list opt_with
2780 CreateFunctionStmt *n = makeNode(CreateFunctionStmt);
2790 opt_or_replace: OR REPLACE { $$ = TRUE; }
2791 | /*EMPTY*/ { $$ = FALSE; }
2794 func_args: '(' func_args_list ')' { $$ = $2; }
2795 | '(' ')' { $$ = NIL; }
2798 func_args_list: func_arg
2799 { $$ = makeList1($1); }
2800 | func_args_list ',' func_arg
2801 { $$ = lappend($1, $3); }
2804 func_arg: opt_arg func_type
2806 /* We can catch over-specified arguments here if we want to,
2807 * but for now better to silently swallow typmod, etc.
2808 * - thomas 2000-03-22
2824 elog(ERROR, "CREATE FUNCTION / OUT parameters are not supported");
2829 elog(ERROR, "CREATE FUNCTION / INOUT parameters are not supported");
2834 func_return: func_type
2836 /* We can catch over-specified arguments here if we want to,
2837 * but for now better to silently swallow typmod, etc.
2838 * - thomas 2000-03-22
2845 * We would like to make the second production here be ColId attrs etc,
2846 * but that causes reduce/reduce conflicts. type_name is next best choice.
2852 | type_name attrs '%' TYPE_P
2854 $$ = makeNode(TypeName);
2855 $$->names = lcons(makeString($1), $2);
2856 $$->pct_type = true;
2862 createfunc_opt_list: createfunc_opt_item
2863 { $$ = makeList1($1); }
2864 | createfunc_opt_list createfunc_opt_item
2865 { $$ = lappend($1, $2); }
2868 createfunc_opt_item: AS func_as
2870 $$ = makeNode(DefElem);
2872 $$->arg = (Node *)$2;
2874 | LANGUAGE ColId_or_Sconst
2876 $$ = makeNode(DefElem);
2877 $$->defname = "language";
2878 $$->arg = (Node *)makeString($2);
2882 $$ = makeNode(DefElem);
2883 $$->defname = "volatility";
2884 $$->arg = (Node *)makeString("immutable");
2888 $$ = makeNode(DefElem);
2889 $$->defname = "volatility";
2890 $$->arg = (Node *)makeString("stable");
2894 $$ = makeNode(DefElem);
2895 $$->defname = "volatility";
2896 $$->arg = (Node *)makeString("volatile");
2898 | CALLED ON NULL_P INPUT
2900 $$ = makeNode(DefElem);
2901 $$->defname = "strict";
2902 $$->arg = (Node *)makeInteger(FALSE);
2904 | RETURNS NULL_P ON NULL_P INPUT
2906 $$ = makeNode(DefElem);
2907 $$->defname = "strict";
2908 $$->arg = (Node *)makeInteger(TRUE);
2912 $$ = makeNode(DefElem);
2913 $$->defname = "strict";
2914 $$->arg = (Node *)makeInteger(TRUE);
2916 | EXTERNAL SECURITY DEFINER
2918 $$ = makeNode(DefElem);
2919 $$->defname = "security";
2920 $$->arg = (Node *)makeInteger(TRUE);
2922 | EXTERNAL SECURITY INVOKER
2924 $$ = makeNode(DefElem);
2925 $$->defname = "security";
2926 $$->arg = (Node *)makeInteger(FALSE);
2930 $$ = makeNode(DefElem);
2931 $$->defname = "security";
2932 $$->arg = (Node *)makeInteger(TRUE);
2936 $$ = makeNode(DefElem);
2937 $$->defname = "security";
2938 $$->arg = (Node *)makeInteger(FALSE);
2942 $$ = makeNode(DefElem);
2943 $$->defname = "implicit";
2944 $$->arg = (Node *)makeInteger(TRUE);
2949 { $$ = makeList1(makeString($1)); }
2951 { $$ = makeList2(makeString($1), makeString($3)); }
2954 opt_with: WITH definition { $$ = $2; }
2955 | /*EMPTY*/ { $$ = NIL; }
2959 /*****************************************************************************
2963 * DROP FUNCTION funcname (arg1, arg2, ...)
2964 * DROP AGGREGATE aggname (aggtype)
2965 * DROP OPERATOR opname (leftoperand_typ rightoperand_typ)
2967 *****************************************************************************/
2969 RemoveFuncStmt: DROP FUNCTION func_name func_args
2971 RemoveFuncStmt *n = makeNode(RemoveFuncStmt);
2978 RemoveAggrStmt: DROP AGGREGATE func_name '(' aggr_argtype ')'
2980 RemoveAggrStmt *n = makeNode(RemoveAggrStmt);
2987 aggr_argtype: Typename { $$ = $1; }
2988 | '*' { $$ = NULL; }
2991 RemoveOperStmt: DROP OPERATOR any_operator '(' oper_argtypes ')'
2993 RemoveOperStmt *n = makeNode(RemoveOperStmt);
3000 oper_argtypes: Typename
3002 elog(ERROR,"parser: argument type missing (use NONE for unary operators)");
3004 | Typename ',' Typename
3005 { $$ = makeList2($1, $3); }
3006 | NONE ',' Typename /* left unary */
3007 { $$ = makeList2(NULL, $3); }
3008 | Typename ',' NONE /* right unary */
3009 { $$ = makeList2($1, NULL); }
3012 any_operator: all_Op
3013 { $$ = makeList1(makeString($1)); }
3014 | ColId '.' any_operator
3015 { $$ = lcons(makeString($1), $3); }
3019 /*****************************************************************************
3023 * REINDEX type <typename> [FORCE] [ALL]
3025 *****************************************************************************/
3027 ReindexStmt: REINDEX reindex_type qualified_name opt_force
3029 ReindexStmt *n = makeNode(ReindexStmt);
3030 n->reindexType = $2;
3036 | REINDEX DATABASE name opt_force
3038 ReindexStmt *n = makeNode(ReindexStmt);
3039 n->reindexType = DATABASE;
3047 reindex_type: INDEX { $$ = INDEX; }
3048 | TABLE { $$ = TABLE; }
3051 opt_force: FORCE { $$ = TRUE; }
3052 | /* EMPTY */ { $$ = FALSE; }
3056 /*****************************************************************************
3059 * rename <attrname1> in <relname> [*] to <attrname2>
3060 * rename <relname1> to <relname2>
3062 *****************************************************************************/
3064 RenameStmt: ALTER TABLE relation_expr RENAME opt_column opt_name TO name
3066 RenameStmt *n = makeNode(RenameStmt);
3071 n->renameType = RENAME_TABLE;
3073 n->renameType = RENAME_COLUMN;
3076 | ALTER TRIGGER name ON relation_expr RENAME TO name
3078 RenameStmt *n = makeNode(RenameStmt);
3082 n->renameType = RENAME_TRIGGER;
3087 opt_name: name { $$ = $1; }
3088 | /*EMPTY*/ { $$ = NULL; }
3091 opt_column: COLUMN { $$ = COLUMN; }
3092 | /*EMPTY*/ { $$ = 0; }
3096 /*****************************************************************************
3098 * QUERY: Define Rewrite Rule
3100 *****************************************************************************/
3102 RuleStmt: CREATE RULE name AS
3103 { QueryIsRule=TRUE; }
3104 ON event TO qualified_name where_clause
3105 DO opt_instead RuleActionList
3107 RuleStmt *n = makeNode(RuleStmt);
3110 n->whereClause = $10;
3119 RuleActionList: NOTHING { $$ = NIL; }
3120 | RuleActionStmt { $$ = makeList1($1); }
3121 | '(' RuleActionMulti ')' { $$ = $2; }
3124 /* the thrashing around here is to discard "empty" statements... */
3125 RuleActionMulti: RuleActionMulti ';' RuleActionStmtOrEmpty
3126 { if ($3 != (Node *) NULL)
3127 $$ = lappend($1, $3);
3131 | RuleActionStmtOrEmpty
3132 { if ($1 != (Node *) NULL)
3139 RuleActionStmt: SelectStmt
3146 RuleActionStmtOrEmpty: RuleActionStmt
3148 { $$ = (Node *)NULL; }
3151 /* change me to select, update, etc. some day */
3152 event: SELECT { $$ = CMD_SELECT; }
3153 | UPDATE { $$ = CMD_UPDATE; }
3154 | DELETE_P { $$ = CMD_DELETE; }
3155 | INSERT { $$ = CMD_INSERT; }
3158 opt_instead: INSTEAD { $$ = TRUE; }
3159 | /*EMPTY*/ { $$ = FALSE; }
3163 DropRuleStmt: DROP RULE name ON qualified_name
3165 DropPropertyStmt *n = makeNode(DropPropertyStmt);
3168 n->removeType = DROP_RULE;
3174 /*****************************************************************************
3177 * NOTIFY <qualified_name> can appear both in rule bodies and
3178 * as a query-level command
3180 *****************************************************************************/
3182 NotifyStmt: NOTIFY qualified_name
3184 NotifyStmt *n = makeNode(NotifyStmt);
3190 ListenStmt: LISTEN qualified_name
3192 ListenStmt *n = makeNode(ListenStmt);
3198 UnlistenStmt: UNLISTEN qualified_name
3200 UnlistenStmt *n = makeNode(UnlistenStmt);
3206 UnlistenStmt *n = makeNode(UnlistenStmt);
3207 n->relation = makeNode(RangeVar);
3208 n->relation->relname = "*";
3209 n->relation->schemaname = NULL;
3215 /*****************************************************************************
3219 * BEGIN / COMMIT / ROLLBACK
3220 * (also older versions END / ABORT)
3222 *****************************************************************************/
3224 TransactionStmt: ABORT_TRANS opt_trans
3226 TransactionStmt *n = makeNode(TransactionStmt);
3227 n->command = ROLLBACK;
3230 | BEGIN_TRANS opt_trans
3232 TransactionStmt *n = makeNode(TransactionStmt);
3233 n->command = BEGIN_TRANS;
3238 TransactionStmt *n = makeNode(TransactionStmt);
3239 n->command = COMMIT;
3242 | COMMIT opt_trans opt_chain
3244 TransactionStmt *n = makeNode(TransactionStmt);
3245 n->command = COMMIT;
3248 | END_TRANS opt_trans
3250 TransactionStmt *n = makeNode(TransactionStmt);
3251 n->command = COMMIT;
3254 | ROLLBACK opt_trans
3256 TransactionStmt *n = makeNode(TransactionStmt);
3257 n->command = ROLLBACK;
3260 | ROLLBACK opt_trans opt_chain
3262 TransactionStmt *n = makeNode(TransactionStmt);
3263 n->command = ROLLBACK;
3268 opt_trans: WORK { $$ = TRUE; }
3269 | TRANSACTION { $$ = TRUE; }
3270 | /*EMPTY*/ { $$ = TRUE; }
3273 opt_chain: AND NO CHAIN
3277 /* SQL99 asks that conforming dbs reject AND CHAIN
3278 * if they don't support it. So we can't just ignore it.
3279 * - thomas 2000-08-06
3281 elog(ERROR, "COMMIT / CHAIN not yet supported");
3287 /*****************************************************************************
3290 * define view <viewname> '('target-list ')' [where <quals> ]
3292 *****************************************************************************/
3294 ViewStmt: CREATE VIEW qualified_name opt_column_list AS SelectStmt
3296 ViewStmt *n = makeNode(ViewStmt);
3299 n->query = (Query *) $6;
3305 /*****************************************************************************
3310 *****************************************************************************/
3312 LoadStmt: LOAD file_name
3314 LoadStmt *n = makeNode(LoadStmt);
3321 /*****************************************************************************
3325 *****************************************************************************/
3327 CreatedbStmt: CREATE DATABASE database_name WITH createdb_opt_list
3329 CreatedbStmt *n = makeNode(CreatedbStmt);
3333 /* set default options */
3336 n->dbtemplate = NULL;
3338 /* process additional options */
3341 List *optitem = (List *) lfirst(l);
3343 switch (lfirsti(optitem))
3346 n->dbpath = (char *) lsecond(optitem);
3349 n->dbtemplate = (char *) lsecond(optitem);
3352 n->encoding = lfirsti(lnext(optitem));
3355 n->dbowner = (char *) lsecond(optitem);
3361 | CREATE DATABASE database_name
3363 CreatedbStmt *n = makeNode(CreatedbStmt);
3367 n->dbtemplate = NULL;
3373 createdb_opt_list: createdb_opt_item
3374 { $$ = makeList1($1); }
3375 | createdb_opt_list createdb_opt_item
3376 { $$ = lappend($1, $2); }
3380 * createdb_opt_item returns 2-element lists, with the first element
3381 * being an integer code to indicate which item was specified.
3383 createdb_opt_item: LOCATION opt_equal Sconst
3385 $$ = lconsi(1, makeList1($3));
3387 | LOCATION opt_equal DEFAULT
3389 $$ = lconsi(1, makeList1(NULL));
3391 | TEMPLATE opt_equal name
3393 $$ = lconsi(2, makeList1($3));
3395 | TEMPLATE opt_equal DEFAULT
3397 $$ = lconsi(2, makeList1(NULL));
3399 | ENCODING opt_equal Sconst
3403 encoding = pg_char_to_encoding($3);
3405 elog(ERROR, "%s is not a valid encoding name", $3);
3407 if (strcasecmp($3, GetStandardEncodingName()) != 0)
3408 elog(ERROR, "Multi-byte support is not enabled");
3409 encoding = GetStandardEncoding();
3411 $$ = lconsi(3, makeListi1(encoding));
3413 | ENCODING opt_equal Iconst
3416 if (!pg_get_enconv_by_encoding($3))
3417 elog(ERROR, "%d is not a valid encoding code", $3);
3419 if ($3 != GetStandardEncoding())
3420 elog(ERROR, "Multi-byte support is not enabled");
3422 $$ = lconsi(3, makeListi1($3));
3424 | ENCODING opt_equal DEFAULT
3426 $$ = lconsi(3, makeListi1(-1));
3428 | OWNER opt_equal name
3430 $$ = lconsi(4, makeList1($3));
3432 | OWNER opt_equal DEFAULT
3434 $$ = lconsi(4, makeList1(NULL));
3439 * Though the equals sign doesn't match other WITH options, pg_dump uses
3440 * equals for backward compability, and it doesn't seem worth remove it.
3442 opt_equal: '=' { $$ = TRUE; }
3443 | /*EMPTY*/ { $$ = FALSE; }
3447 /*****************************************************************************
3451 *****************************************************************************/
3453 AlterDatabaseSetStmt: ALTER DATABASE database_name SET set_rest
3455 AlterDatabaseSetStmt *n = makeNode(AlterDatabaseSetStmt);
3457 n->variable = $5->name;
3458 n->value = $5->args;
3461 | ALTER DATABASE database_name VariableResetStmt
3463 AlterDatabaseSetStmt *n = makeNode(AlterDatabaseSetStmt);
3465 n->variable = ((VariableResetStmt *)$4)->name;
3472 /*****************************************************************************
3476 *****************************************************************************/
3478 DropdbStmt: DROP DATABASE database_name
3480 DropdbStmt *n = makeNode(DropdbStmt);
3487 /*****************************************************************************
3489 * Manipulate a domain
3491 *****************************************************************************/
3493 CreateDomainStmt: CREATE DOMAIN_P any_name opt_as Typename ColQualList opt_collate
3495 CreateDomainStmt *n = makeNode(CreateDomainStmt);
3498 n->constraints = $6;
3501 elog(NOTICE,"CREATE DOMAIN / COLLATE %s not yet "
3502 "implemented; clause ignored", $7);
3507 opt_as: AS {$$ = TRUE; }
3508 | /* EMPTY */ {$$ = FALSE; }
3512 /*****************************************************************************
3515 * cluster <index_name> on <qualified_name>
3517 *****************************************************************************/
3519 ClusterStmt: CLUSTER index_name ON qualified_name
3521 ClusterStmt *n = makeNode(ClusterStmt);
3528 /*****************************************************************************
3534 *****************************************************************************/
3536 VacuumStmt: VACUUM opt_full opt_freeze opt_verbose
3538 VacuumStmt *n = makeNode(VacuumStmt);
3548 | VACUUM opt_full opt_freeze opt_verbose qualified_name
3550 VacuumStmt *n = makeNode(VacuumStmt);
3560 | VACUUM opt_full opt_freeze opt_verbose AnalyzeStmt
3562 VacuumStmt *n = (VacuumStmt *) $5;
3571 AnalyzeStmt: analyze_keyword opt_verbose
3573 VacuumStmt *n = makeNode(VacuumStmt);
3583 | analyze_keyword opt_verbose qualified_name opt_name_list
3585 VacuumStmt *n = makeNode(VacuumStmt);
3597 analyze_keyword: ANALYZE { $$ = TRUE; }
3598 | ANALYSE /* British */ { $$ = TRUE; }
3601 opt_verbose: VERBOSE { $$ = TRUE; }
3602 | /*EMPTY*/ { $$ = FALSE; }
3605 opt_full: FULL { $$ = TRUE; }
3606 | /*EMPTY*/ { $$ = FALSE; }
3609 opt_freeze: FREEZE { $$ = TRUE; }
3610 | /*EMPTY*/ { $$ = FALSE; }
3613 opt_name_list: '(' name_list ')' { $$ = $2; }
3614 | /*EMPTY*/ { $$ = NIL; }
3618 /*****************************************************************************
3622 * EXPLAIN ANALYZE query
3624 *****************************************************************************/
3626 ExplainStmt: EXPLAIN opt_verbose OptimizableStmt
3628 ExplainStmt *n = makeNode(ExplainStmt);
3631 n->query = (Query*)$3;
3634 | EXPLAIN analyze_keyword opt_verbose OptimizableStmt
3636 ExplainStmt *n = makeNode(ExplainStmt);
3639 n->query = (Query*)$4;
3645 /*****************************************************************************
3647 * Optimizable Stmts: *
3649 * one of the five queries processed by the planner *
3651 * [ultimately] produces query-trees as specified *
3652 * in the query-spec document in ~postgres/ref *
3654 *****************************************************************************/
3656 OptimizableStmt: SelectStmt
3660 | DeleteStmt /* by default all are $$=$1 */
3664 /*****************************************************************************
3669 *****************************************************************************/
3671 InsertStmt: INSERT INTO qualified_name insert_rest
3678 insert_rest: VALUES '(' insert_target_list ')'
3680 $$ = makeNode(InsertStmt);
3682 $$->targetList = $3;
3683 $$->selectStmt = NULL;
3687 $$ = makeNode(InsertStmt);
3689 $$->targetList = NIL;
3690 $$->selectStmt = NULL;
3694 $$ = makeNode(InsertStmt);
3696 $$->targetList = NIL;
3697 $$->selectStmt = $1;
3699 | '(' insert_column_list ')' VALUES '(' insert_target_list ')'
3701 $$ = makeNode(InsertStmt);
3703 $$->targetList = $6;
3704 $$->selectStmt = NULL;
3706 | '(' insert_column_list ')' SelectStmt
3708 $$ = makeNode(InsertStmt);
3710 $$->targetList = NIL;
3711 $$->selectStmt = $4;
3715 insert_column_list: insert_column_list ',' insert_column_item
3716 { $$ = lappend($1, $3); }
3717 | insert_column_item
3718 { $$ = makeList1($1); }
3721 insert_column_item: ColId opt_indirection
3723 ResTarget *n = makeNode(ResTarget);
3725 n->indirection = $2;
3732 /*****************************************************************************
3737 *****************************************************************************/
3739 DeleteStmt: DELETE_P FROM relation_expr where_clause
3741 DeleteStmt *n = makeNode(DeleteStmt);
3743 n->whereClause = $4;
3748 LockStmt: LOCK_P opt_table qualified_name_list opt_lock
3750 LockStmt *n = makeNode(LockStmt);
3758 opt_lock: IN_P lock_type MODE { $$ = $2; }
3759 | /*EMPTY*/ { $$ = AccessExclusiveLock; }
3762 lock_type: ACCESS SHARE { $$ = AccessShareLock; }
3763 | ROW SHARE { $$ = RowShareLock; }
3764 | ROW EXCLUSIVE { $$ = RowExclusiveLock; }
3765 | SHARE UPDATE EXCLUSIVE { $$ = ShareUpdateExclusiveLock; }
3766 | SHARE { $$ = ShareLock; }
3767 | SHARE ROW EXCLUSIVE { $$ = ShareRowExclusiveLock; }
3768 | EXCLUSIVE { $$ = ExclusiveLock; }
3769 | ACCESS EXCLUSIVE { $$ = AccessExclusiveLock; }
3773 /*****************************************************************************
3776 * UpdateStmt (UPDATE)
3778 *****************************************************************************/
3780 UpdateStmt: UPDATE relation_expr
3781 SET update_target_list
3785 UpdateStmt *n = makeNode(UpdateStmt);
3789 n->whereClause = $6;
3795 /*****************************************************************************
3800 *****************************************************************************/
3801 CursorStmt: DECLARE name opt_cursor CURSOR FOR SelectStmt
3803 SelectStmt *n = (SelectStmt *)$6;
3810 opt_cursor: BINARY { $$ = TRUE; }
3811 | INSENSITIVE { $$ = FALSE; }
3812 | SCROLL { $$ = FALSE; }
3813 | INSENSITIVE SCROLL { $$ = FALSE; }
3814 | /*EMPTY*/ { $$ = FALSE; }
3817 /*****************************************************************************
3822 *****************************************************************************/
3824 /* A complete SELECT statement looks like this.
3826 * The rule returns either a single SelectStmt node or a tree of them,
3827 * representing a set-operation tree.
3829 * There is an ambiguity when a sub-SELECT is within an a_expr and there
3830 * are excess parentheses: do the parentheses belong to the sub-SELECT or
3831 * to the surrounding a_expr? We don't really care, but yacc wants to know.
3832 * To resolve the ambiguity, we are careful to define the grammar so that
3833 * the decision is staved off as long as possible: as long as we can keep
3834 * absorbing parentheses into the sub-SELECT, we will do so, and only when
3835 * it's no longer possible to do that will we decide that parens belong to
3836 * the expression. For example, in "SELECT (((SELECT 2)) + 3)" the extra
3837 * parentheses are treated as part of the sub-select. The necessity of doing
3838 * it that way is shown by "SELECT (((SELECT 2)) UNION SELECT 2)". Had we
3839 * parsed "((SELECT 2))" as an a_expr, it'd be too late to go back to the
3840 * SELECT viewpoint when we see the UNION.
3842 * This approach is implemented by defining a nonterminal select_with_parens,
3843 * which represents a SELECT with at least one outer layer of parentheses,
3844 * and being careful to use select_with_parens, never '(' SelectStmt ')',
3845 * in the expression grammar. We will then have shift-reduce conflicts
3846 * which we can resolve in favor of always treating '(' <select> ')' as
3847 * a select_with_parens. To resolve the conflicts, the productions that
3848 * conflict with the select_with_parens productions are manually given
3849 * precedences lower than the precedence of ')', thereby ensuring that we
3850 * shift ')' (and then reduce to select_with_parens) rather than trying to
3851 * reduce the inner <select> nonterminal to something else. We use UMINUS
3852 * precedence for this, which is a fairly arbitrary choice.
3854 * To be able to define select_with_parens itself without ambiguity, we need
3855 * a nonterminal select_no_parens that represents a SELECT structure with no
3856 * outermost parentheses. This is a little bit tedious, but it works.
3858 * In non-expression contexts, we use SelectStmt which can represent a SELECT
3859 * with or without outer parentheses.
3862 SelectStmt: select_no_parens %prec UMINUS
3863 | select_with_parens %prec UMINUS
3866 select_with_parens: '(' select_no_parens ')'
3870 | '(' select_with_parens ')'
3876 select_no_parens: simple_select
3880 | select_clause sort_clause opt_for_update_clause opt_select_limit
3882 insertSelectOptions((SelectStmt *) $1, $2, $3,
3883 nth(0, $4), nth(1, $4));
3886 | select_clause for_update_clause opt_select_limit
3888 insertSelectOptions((SelectStmt *) $1, NIL, $2,
3889 nth(0, $3), nth(1, $3));
3892 | select_clause select_limit
3894 insertSelectOptions((SelectStmt *) $1, NIL, NIL,
3895 nth(0, $2), nth(1, $2));
3900 select_clause: simple_select
3901 | select_with_parens
3905 * This rule parses SELECT statements that can appear within set operations,
3906 * including UNION, INTERSECT and EXCEPT. '(' and ')' can be used to specify
3907 * the ordering of the set operations. Without '(' and ')' we want the
3908 * operations to be ordered per the precedence specs at the head of this file.
3910 * As with select_no_parens, simple_select cannot have outer parentheses,
3911 * but can have parenthesized subclauses.
3913 * Note that sort clauses cannot be included at this level --- SQL92 requires
3914 * SELECT foo UNION SELECT bar ORDER BY baz
3916 * (SELECT foo UNION SELECT bar) ORDER BY baz
3918 * SELECT foo UNION (SELECT bar ORDER BY baz)
3919 * Likewise FOR UPDATE and LIMIT. Therefore, those clauses are described
3920 * as part of the select_no_parens production, not simple_select.
3921 * This does not limit functionality, because you can reintroduce sort and
3922 * limit clauses inside parentheses.
3924 * NOTE: only the leftmost component SelectStmt should have INTO.
3925 * However, this is not checked by the grammar; parse analysis must check it.
3927 simple_select: SELECT opt_distinct target_list
3928 into_clause from_clause where_clause
3929 group_clause having_clause
3931 SelectStmt *n = makeNode(SelectStmt);
3932 n->distinctClause = $2;
3935 n->intoColNames = NIL;
3937 n->whereClause = $6;
3938 n->groupClause = $7;
3939 n->havingClause = $8;
3942 | select_clause UNION opt_all select_clause
3944 $$ = makeSetOp(SETOP_UNION, $3, $1, $4);
3946 | select_clause INTERSECT opt_all select_clause
3948 $$ = makeSetOp(SETOP_INTERSECT, $3, $1, $4);
3950 | select_clause EXCEPT opt_all select_clause
3952 $$ = makeSetOp(SETOP_EXCEPT, $3, $1, $4);
3956 into_clause: INTO OptTempTableName { $$ = $2; }
3957 | /*EMPTY*/ { $$ = NULL; }
3961 * Redundancy here is needed to avoid shift/reduce conflicts,
3962 * since TEMP is not a reserved word. See also OptTemp.
3964 OptTempTableName: TEMPORARY opt_table qualified_name
3969 | TEMP opt_table qualified_name
3974 | LOCAL TEMPORARY opt_table qualified_name
3979 | LOCAL TEMP opt_table qualified_name
3984 | GLOBAL TEMPORARY opt_table qualified_name
3986 elog(ERROR, "GLOBAL TEMPORARY TABLE is not currently supported");
3990 | GLOBAL TEMP opt_table qualified_name
3992 elog(ERROR, "GLOBAL TEMPORARY TABLE is not currently supported");
3996 | TABLE qualified_name
4008 opt_table: TABLE { $$ = TRUE; }
4009 | /*EMPTY*/ { $$ = FALSE; }
4012 opt_all: ALL { $$ = TRUE; }
4013 | /*EMPTY*/ { $$ = FALSE; }
4016 /* We use (NIL) as a placeholder to indicate that all target expressions
4017 * should be placed in the DISTINCT list during parsetree analysis.
4019 opt_distinct: DISTINCT { $$ = makeList1(NIL); }
4020 | DISTINCT ON '(' expr_list ')' { $$ = $4; }
4022 | /*EMPTY*/ { $$ = NIL; }
4025 sort_clause: ORDER BY sortby_list { $$ = $3; }
4028 sortby_list: sortby { $$ = makeList1($1); }
4029 | sortby_list ',' sortby { $$ = lappend($1, $3); }
4032 sortby: a_expr OptUseOp
4034 $$ = makeNode(SortGroupBy);
4040 OptUseOp: USING qual_all_Op
4043 { $$ = makeList1(makeString("<")); }
4045 { $$ = makeList1(makeString(">")); }
4047 { $$ = makeList1(makeString("<")); /*default*/ }
4051 select_limit: LIMIT select_limit_value OFFSET select_offset_value
4052 { $$ = makeList2($4, $2); }
4053 | OFFSET select_offset_value LIMIT select_limit_value
4054 { $$ = makeList2($2, $4); }
4055 | LIMIT select_limit_value
4056 { $$ = makeList2(NULL, $2); }
4057 | OFFSET select_offset_value
4058 { $$ = makeList2($2, NULL); }
4059 | LIMIT select_limit_value ',' select_offset_value
4060 /* Disabled because it was too confusing, bjm 2002-02-18 */
4061 { elog(ERROR, "LIMIT #,# syntax not supported.\n\tUse separate LIMIT and OFFSET clauses."); }
4065 opt_select_limit: select_limit { $$ = $1; }
4066 | /* EMPTY */ { $$ = makeList2(NULL,NULL); }
4069 select_limit_value: Iconst
4071 Const *n = makeNode(Const);
4074 elog(ERROR, "LIMIT must not be negative");
4076 n->consttype = INT4OID;
4077 n->constlen = sizeof(int4);
4078 n->constvalue = Int32GetDatum($1);
4079 n->constisnull = FALSE;
4080 n->constbyval = TRUE;
4081 n->constisset = FALSE;
4082 n->constiscast = FALSE;
4087 /* LIMIT ALL is represented as a NULL constant */
4088 Const *n = makeNode(Const);
4090 n->consttype = INT4OID;
4091 n->constlen = sizeof(int4);
4092 n->constvalue = (Datum) 0;
4093 n->constisnull = TRUE;
4094 n->constbyval = TRUE;
4095 n->constisset = FALSE;
4096 n->constiscast = FALSE;
4101 Param *n = makeNode(Param);
4103 n->paramkind = PARAM_NUM;
4105 n->paramtype = INT4OID;
4110 select_offset_value: Iconst
4112 Const *n = makeNode(Const);
4115 elog(ERROR, "OFFSET must not be negative");
4117 n->consttype = INT4OID;
4118 n->constlen = sizeof(int4);
4119 n->constvalue = Int32GetDatum($1);
4120 n->constisnull = FALSE;
4121 n->constbyval = TRUE;
4122 n->constisset = FALSE;
4123 n->constiscast = FALSE;
4128 Param *n = makeNode(Param);
4130 n->paramkind = PARAM_NUM;
4132 n->paramtype = INT4OID;
4138 * jimmy bell-style recursive queries aren't supported in the
4141 * ...however, recursive addattr and rename supported. make special
4145 group_clause: GROUP_P BY expr_list { $$ = $3; }
4146 | /*EMPTY*/ { $$ = NIL; }
4149 having_clause: HAVING a_expr
4153 | /*EMPTY*/ { $$ = NULL; }
4156 for_update_clause: FOR UPDATE update_list { $$ = $3; }
4157 | FOR READ ONLY { $$ = NULL; }
4160 opt_for_update_clause: for_update_clause { $$ = $1; }
4161 | /* EMPTY */ { $$ = NULL; }
4164 update_list: OF name_list { $$ = $2; }
4165 | /* EMPTY */ { $$ = makeList1(NULL); }
4168 /*****************************************************************************
4170 * clauses common to all Optimizable Stmts:
4171 * from_clause - allow list of both JOIN expressions and table names
4172 * where_clause - qualifications for joins or restrictions
4174 *****************************************************************************/
4176 from_clause: FROM from_list { $$ = $2; }
4177 | /*EMPTY*/ { $$ = NIL; }
4180 from_list: from_list ',' table_ref { $$ = lappend($1, $3); }
4181 | table_ref { $$ = makeList1($1); }
4185 * table_ref is where an alias clause can be attached. Note we cannot make
4186 * alias_clause have an empty production because that causes parse conflicts
4187 * between table_ref := '(' joined_table ')' alias_clause
4188 * and joined_table := '(' joined_table ')'. So, we must have the
4189 * redundant-looking productions here instead.
4191 table_ref: relation_expr
4195 | relation_expr alias_clause
4202 RangeFunction *n = makeNode(RangeFunction);
4203 n->funccallnode = $1;
4206 | func_table alias_clause
4208 RangeFunction *n = makeNode(RangeFunction);
4209 n->funccallnode = $1;
4213 | select_with_parens
4216 * The SQL spec does not permit a subselect
4217 * (<derived_table>) without an alias clause,
4218 * so we don't either. This avoids the problem
4219 * of needing to invent a unique refname for it.
4220 * That could be surmounted if there's sufficient
4221 * popular demand, but for now let's just implement
4222 * the spec and see if anyone complains.
4223 * However, it does seem like a good idea to emit
4224 * an error message that's better than "parse error".
4226 elog(ERROR, "sub-SELECT in FROM must have an alias"
4227 "\n\tFor example, FROM (SELECT ...) [AS] foo");
4230 | select_with_parens alias_clause
4232 RangeSubselect *n = makeNode(RangeSubselect);
4241 | '(' joined_table ')' alias_clause
4250 * It may seem silly to separate joined_table from table_ref, but there is
4251 * method in SQL92's madness: if you don't do it this way you get reduce-
4252 * reduce conflicts, because it's not clear to the parser generator whether
4253 * to expect alias_clause after ')' or not. For the same reason we must
4254 * treat 'JOIN' and 'join_type JOIN' separately, rather than allowing
4255 * join_type to expand to empty; if we try it, the parser generator can't
4256 * figure out when to reduce an empty join_type right after table_ref.
4258 * Note that a CROSS JOIN is the same as an unqualified
4259 * INNER JOIN, and an INNER JOIN/ON has the same shape
4260 * but a qualification expression to limit membership.
4261 * A NATURAL JOIN implicitly matches column names between
4262 * tables and the shape is determined by which columns are
4263 * in common. We'll collect columns during the later transformations.
4266 joined_table: '(' joined_table ')'
4270 | table_ref CROSS JOIN table_ref
4272 /* CROSS JOIN is same as unqualified inner join */
4273 JoinExpr *n = makeNode(JoinExpr);
4274 n->jointype = JOIN_INNER;
4275 n->isNatural = FALSE;
4282 | table_ref UNIONJOIN table_ref
4284 /* UNION JOIN is made into 1 token to avoid shift/reduce
4285 * conflict against regular UNION keyword.
4287 JoinExpr *n = makeNode(JoinExpr);
4288 n->jointype = JOIN_UNION;
4289 n->isNatural = FALSE;
4296 | table_ref join_type JOIN table_ref join_qual
4298 JoinExpr *n = makeNode(JoinExpr);
4300 n->isNatural = FALSE;
4303 if ($5 != NULL && IsA($5, List))
4304 n->using = (List *) $5; /* USING clause */
4306 n->quals = $5; /* ON clause */
4309 | table_ref JOIN table_ref join_qual
4311 /* letting join_type reduce to empty doesn't work */
4312 JoinExpr *n = makeNode(JoinExpr);
4313 n->jointype = JOIN_INNER;
4314 n->isNatural = FALSE;
4317 if ($4 != NULL && IsA($4, List))
4318 n->using = (List *) $4; /* USING clause */
4320 n->quals = $4; /* ON clause */
4323 | table_ref NATURAL join_type JOIN table_ref
4325 JoinExpr *n = makeNode(JoinExpr);
4327 n->isNatural = TRUE;
4330 n->using = NIL; /* figure out which columns later... */
4331 n->quals = NULL; /* fill later */
4334 | table_ref NATURAL JOIN table_ref
4336 /* letting join_type reduce to empty doesn't work */
4337 JoinExpr *n = makeNode(JoinExpr);
4338 n->jointype = JOIN_INNER;
4339 n->isNatural = TRUE;
4342 n->using = NIL; /* figure out which columns later... */
4343 n->quals = NULL; /* fill later */
4348 alias_clause: AS ColId '(' name_list ')'
4350 $$ = makeNode(Alias);
4356 $$ = makeNode(Alias);
4359 | ColId '(' name_list ')'
4361 $$ = makeNode(Alias);
4367 $$ = makeNode(Alias);
4372 join_type: FULL join_outer { $$ = JOIN_FULL; }
4373 | LEFT join_outer { $$ = JOIN_LEFT; }
4374 | RIGHT join_outer { $$ = JOIN_RIGHT; }
4375 | INNER_P { $$ = JOIN_INNER; }
4378 /* OUTER is just noise... */
4379 join_outer: OUTER_P { $$ = NULL; }
4380 | /*EMPTY*/ { $$ = NULL; }
4383 /* JOIN qualification clauses
4384 * Possibilities are:
4385 * USING ( column list ) allows only unqualified column names,
4386 * which must match between tables.
4387 * ON expr allows more general qualifications.
4389 * We return USING as a List node, while an ON-expr will not be a List.
4392 join_qual: USING '(' name_list ')' { $$ = (Node *) $3; }
4393 | ON a_expr { $$ = $2; }
4397 relation_expr: qualified_name
4399 /* default inheritance */
4401 $$->inhOpt = INH_DEFAULT;
4404 | qualified_name '*'
4406 /* inheritance query */
4408 $$->inhOpt = INH_YES;
4411 | ONLY qualified_name
4413 /* no inheritance */
4415 $$->inhOpt = INH_NO;
4421 func_table: func_name '(' ')'
4423 FuncCall *n = makeNode(FuncCall);
4426 n->agg_star = FALSE;
4427 n->agg_distinct = FALSE;
4430 | func_name '(' expr_list ')'
4432 FuncCall *n = makeNode(FuncCall);
4435 n->agg_star = FALSE;
4436 n->agg_distinct = FALSE;
4442 where_clause: WHERE a_expr { $$ = $2; }
4443 | /*EMPTY*/ { $$ = NULL; /* no qualifiers */ }
4447 /*****************************************************************************
4450 * SQL92 introduces a large amount of type-specific syntax.
4451 * Define individual clauses to handle these cases, and use
4452 * the generic case to handle regular type-extensible Postgres syntax.
4453 * - thomas 1997-10-10
4455 *****************************************************************************/
4457 Typename: SimpleTypename opt_array_bounds
4460 $$->arrayBounds = $2;
4462 | SETOF SimpleTypename
4469 opt_array_bounds: opt_array_bounds '[' ']'
4470 { $$ = lappend($1, makeInteger(-1)); }
4471 | opt_array_bounds '[' Iconst ']'
4472 { $$ = lappend($1, makeInteger($3)); }
4478 * XXX ideally, the production for a qualified typename should be ColId attrs
4479 * (there's no obvious reason why the first name should need to be restricted)
4480 * and should be an alternative of GenericType (so that it can be used to
4481 * specify a type for a literal in AExprConst). However doing either causes
4482 * reduce/reduce conflicts that I haven't been able to find a workaround
4485 SimpleTypename: ConstTypename
4486 | ConstInterval opt_interval
4490 $$->typmod = ((($2 & 0x7FFF) << 16) | 0xFFFF);
4492 | ConstInterval '(' Iconst ')' opt_interval
4495 if (($3 < 0) || ($3 > MAX_INTERVAL_PRECISION))
4496 elog(ERROR, "INTERVAL(%d) precision must be between %d and %d",
4497 $3, 0, MAX_INTERVAL_PRECISION);
4498 $$->typmod = ((($5 & 0x7FFF) << 16) | $3);
4502 $$ = makeNode(TypeName);
4503 $$->names = lcons(makeString($1), $2);
4508 ConstTypename: GenericType
4515 GenericType: type_name
4517 $$ = makeTypeName($1);
4521 /* SQL92 numeric data types
4522 * Check FLOAT() precision limits assuming IEEE floating types.
4523 * Provide real DECIMAL() and NUMERIC() implementations now - Jan 1998-12-30
4524 * - thomas 1997-09-18
4528 $$ = SystemTypeName("int4");
4532 $$ = SystemTypeName("int4");
4536 $$ = SystemTypeName("int2");
4540 $$ = SystemTypeName("int8");
4544 $$ = SystemTypeName("float4");
4552 $$ = SystemTypeName("float8");
4554 | DECIMAL opt_decimal
4556 $$ = SystemTypeName("numeric");
4561 $$ = SystemTypeName("numeric");
4564 | NUMERIC opt_numeric
4566 $$ = SystemTypeName("numeric");
4571 $$ = SystemTypeName("bool");
4575 opt_float: '(' Iconst ')'
4578 elog(ERROR, "precision for FLOAT must be at least 1");
4580 $$ = SystemTypeName("float4");
4582 $$ = SystemTypeName("float8");
4584 elog(ERROR, "precision for FLOAT must be less than 16");
4588 $$ = SystemTypeName("float8");
4592 opt_numeric: '(' Iconst ',' Iconst ')'
4594 if ($2 < 1 || $2 > NUMERIC_MAX_PRECISION)
4595 elog(ERROR, "NUMERIC precision %d must be between 1 and %d",
4596 $2, NUMERIC_MAX_PRECISION);
4597 if ($4 < 0 || $4 > $2)
4598 elog(ERROR, "NUMERIC scale %d must be between 0 and precision %d",
4601 $$ = (($2 << 16) | $4) + VARHDRSZ;
4605 if ($2 < 1 || $2 > NUMERIC_MAX_PRECISION)
4606 elog(ERROR, "NUMERIC precision %d must be between 1 and %d",
4607 $2, NUMERIC_MAX_PRECISION);
4609 $$ = ($2 << 16) + VARHDRSZ;
4613 /* Insert "-1" meaning "no limit" */
4618 opt_decimal: '(' Iconst ',' Iconst ')'
4620 if ($2 < 1 || $2 > NUMERIC_MAX_PRECISION)
4621 elog(ERROR, "DECIMAL precision %d must be between 1 and %d",
4622 $2, NUMERIC_MAX_PRECISION);
4623 if ($4 < 0 || $4 > $2)
4624 elog(ERROR, "DECIMAL scale %d must be between 0 and precision %d",
4627 $$ = (($2 << 16) | $4) + VARHDRSZ;
4631 if ($2 < 1 || $2 > NUMERIC_MAX_PRECISION)
4632 elog(ERROR, "DECIMAL precision %d must be between 1 and %d",
4633 $2, NUMERIC_MAX_PRECISION);
4635 $$ = ($2 << 16) + VARHDRSZ;
4639 /* Insert "-1" meaning "no limit" */
4646 * SQL92 bit-field data types
4647 * The following implements BIT() and BIT VARYING().
4649 Bit: BIT opt_varying '(' Iconst ')'
4653 typname = $2 ? "varbit" : "bit";
4654 $$ = SystemTypeName(typname);
4656 elog(ERROR, "length for type '%s' must be at least 1",
4658 else if ($4 > (MaxAttrSize * BITS_PER_BYTE))
4659 elog(ERROR, "length for type '%s' cannot exceed %d",
4660 typname, (MaxAttrSize * BITS_PER_BYTE));
4665 /* bit defaults to bit(1), varbit to no limit */
4668 $$ = SystemTypeName("varbit");
4673 $$ = SystemTypeName("bit");
4681 * SQL92 character data types
4682 * The following implements CHAR() and VARCHAR().
4684 Character: character '(' Iconst ')' opt_charset
4686 if (($5 != NULL) && (strcmp($5, "sql_text") != 0))
4690 type = palloc(strlen($1) + 1 + strlen($5) + 1);
4697 $$ = SystemTypeName($1);
4700 elog(ERROR, "length for type '%s' must be at least 1",
4702 else if ($3 > MaxAttrSize)
4703 elog(ERROR, "length for type '%s' cannot exceed %d",
4706 /* we actually implement these like a varlen, so
4707 * the first 4 bytes is the length. (the difference
4708 * between these and "text" is that we blank-pad and
4709 * truncate where necessary)
4711 $$->typmod = VARHDRSZ + $3;
4713 | character opt_charset
4715 if (($2 != NULL) && (strcmp($2, "sql_text") != 0))
4719 type = palloc(strlen($1) + 1 + strlen($2) + 1);
4726 $$ = SystemTypeName($1);
4728 /* char defaults to char(1), varchar to no limit */
4729 if (strcmp($1, "bpchar") == 0)
4730 $$->typmod = VARHDRSZ + 1;
4736 character: CHARACTER opt_varying { $$ = $2 ? "varchar": "bpchar"; }
4737 | CHAR_P opt_varying { $$ = $2 ? "varchar": "bpchar"; }
4738 | VARCHAR { $$ = "varchar"; }
4739 | NATIONAL CHARACTER opt_varying { $$ = $3 ? "varchar": "bpchar"; }
4740 | NATIONAL CHAR_P opt_varying { $$ = $3 ? "varchar": "bpchar"; }
4741 | NCHAR opt_varying { $$ = $2 ? "varchar": "bpchar"; }
4744 opt_varying: VARYING { $$ = TRUE; }
4745 | /*EMPTY*/ { $$ = FALSE; }
4748 opt_charset: CHARACTER SET ColId { $$ = $3; }
4749 | /*EMPTY*/ { $$ = NULL; }
4752 opt_collate: COLLATE ColId { $$ = $2; }
4753 | /*EMPTY*/ { $$ = NULL; }
4756 ConstDatetime: TIMESTAMP '(' Iconst ')' opt_timezone
4759 $$ = SystemTypeName("timestamptz");
4761 $$ = SystemTypeName("timestamp");
4762 /* XXX the timezone field seems to be unused
4763 * - thomas 2001-09-06
4766 if (($3 < 0) || ($3 > MAX_TIMESTAMP_PRECISION))
4767 elog(ERROR, "TIMESTAMP(%d)%s precision must be between %d and %d",
4768 $3, ($5 ? " WITH TIME ZONE": ""), 0, MAX_TIMESTAMP_PRECISION);
4771 | TIMESTAMP opt_timezone
4774 $$ = SystemTypeName("timestamptz");
4776 $$ = SystemTypeName("timestamp");
4777 /* XXX the timezone field seems to be unused
4778 * - thomas 2001-09-06
4781 /* SQL99 specified a default precision of six
4782 * for schema definitions. But for timestamp
4783 * literals we don't want to throw away precision
4784 * so leave this as unspecified for now.
4785 * Later, we may want a different production
4786 * for schemas. - thomas 2001-12-07
4790 | TIME '(' Iconst ')' opt_timezone
4793 $$ = SystemTypeName("timetz");
4795 $$ = SystemTypeName("time");
4796 if (($3 < 0) || ($3 > MAX_TIME_PRECISION))
4797 elog(ERROR, "TIME(%d)%s precision must be between %d and %d",
4798 $3, ($5 ? " WITH TIME ZONE": ""), 0, MAX_TIME_PRECISION);
4804 $$ = SystemTypeName("timetz");
4806 $$ = SystemTypeName("time");
4807 /* SQL99 specified a default precision of zero.
4808 * See comments for timestamp above on why we will
4809 * leave this unspecified for now. - thomas 2001-12-07
4815 ConstInterval: INTERVAL
4817 $$ = SystemTypeName("interval");
4821 opt_timezone: WITH TIME ZONE { $$ = TRUE; }
4822 | WITHOUT TIME ZONE { $$ = FALSE; }
4823 | /*EMPTY*/ { $$ = FALSE; }
4826 opt_interval: YEAR_P { $$ = MASK(YEAR); }
4827 | MONTH_P { $$ = MASK(MONTH); }
4828 | DAY_P { $$ = MASK(DAY); }
4829 | HOUR_P { $$ = MASK(HOUR); }
4830 | MINUTE_P { $$ = MASK(MINUTE); }
4831 | SECOND_P { $$ = MASK(SECOND); }
4832 | YEAR_P TO MONTH_P { $$ = MASK(YEAR) | MASK(MONTH); }
4833 | DAY_P TO HOUR_P { $$ = MASK(DAY) | MASK(HOUR); }
4834 | DAY_P TO MINUTE_P { $$ = MASK(DAY) | MASK(HOUR) | MASK(MINUTE); }
4835 | DAY_P TO SECOND_P { $$ = MASK(DAY) | MASK(HOUR) | MASK(MINUTE) | MASK(SECOND); }
4836 | HOUR_P TO MINUTE_P { $$ = MASK(HOUR) | MASK(MINUTE); }
4837 | HOUR_P TO SECOND_P { $$ = MASK(HOUR) | MASK(MINUTE) | MASK(SECOND); }
4838 | MINUTE_P TO SECOND_P { $$ = MASK(MINUTE) | MASK(SECOND); }
4839 | /*EMPTY*/ { $$ = -1; }
4843 /*****************************************************************************
4845 * expression grammar
4847 *****************************************************************************/
4849 /* Expressions using row descriptors
4850 * Define row_descriptor to allow yacc to break the reduce/reduce conflict
4851 * with singleton expressions.
4853 row_expr: '(' row_descriptor ')' IN_P select_with_parens
4855 SubLink *n = makeNode(SubLink);
4857 n->oper = (List *) makeSimpleA_Expr(OP, "=", NULL, NULL);
4859 n->subLinkType = ANY_SUBLINK;
4863 | '(' row_descriptor ')' NOT IN_P select_with_parens
4865 SubLink *n = makeNode(SubLink);
4867 n->oper = (List *) makeSimpleA_Expr(OP, "<>", NULL, NULL);
4869 n->subLinkType = ALL_SUBLINK;
4873 | '(' row_descriptor ')' qual_all_Op sub_type select_with_parens %prec Op
4875 SubLink *n = makeNode(SubLink);
4877 n->oper = (List *) makeA_Expr(OP, $4, NULL, NULL);
4878 if (strcmp(strVal(llast($4)), "<>") == 0)
4882 n->subLinkType = $5;
4886 | '(' row_descriptor ')' qual_all_Op select_with_parens %prec Op
4888 SubLink *n = makeNode(SubLink);
4890 n->oper = (List *) makeA_Expr(OP, $4, NULL, NULL);
4891 if (strcmp(strVal(llast($4)), "<>") == 0)
4895 n->subLinkType = MULTIEXPR_SUBLINK;
4899 | '(' row_descriptor ')' qual_all_Op '(' row_descriptor ')' %prec Op
4901 $$ = makeRowExpr($4, $2, $6);
4903 | '(' row_descriptor ')' OVERLAPS '(' row_descriptor ')'
4905 FuncCall *n = makeNode(FuncCall);
4908 n->funcname = SystemFuncName("overlaps");
4909 if (length(largs) == 1)
4910 largs = lappend(largs, $2);
4911 else if (length(largs) != 2)
4912 elog(ERROR, "Wrong number of parameters"
4913 " on left side of OVERLAPS expression");
4914 if (length(rargs) == 1)
4915 rargs = lappend(rargs, $6);
4916 else if (length(rargs) != 2)
4917 elog(ERROR, "Wrong number of parameters"
4918 " on right side of OVERLAPS expression");
4919 n->args = nconc(largs, rargs);
4920 n->agg_star = FALSE;
4921 n->agg_distinct = FALSE;
4926 row_descriptor: row_list ',' a_expr
4928 $$ = lappend($1, $3);
4932 row_list: row_list ',' a_expr
4934 $$ = lappend($1, $3);
4942 sub_type: ANY { $$ = ANY_SUBLINK; }
4943 | SOME { $$ = ANY_SUBLINK; }
4944 | ALL { $$ = ALL_SUBLINK; }
4947 all_Op: Op | MathOp;
4949 MathOp: '+' { $$ = "+"; }
4961 { $$ = makeList1(makeString($1)); }
4962 | OPERATOR '(' any_operator ')'
4967 { $$ = makeList1(makeString($1)); }
4968 | OPERATOR '(' any_operator ')'
4973 * General expressions
4974 * This is the heart of the expression syntax.
4976 * We have two expression types: a_expr is the unrestricted kind, and
4977 * b_expr is a subset that must be used in some places to avoid shift/reduce
4978 * conflicts. For example, we can't do BETWEEN as "BETWEEN a_expr AND a_expr"
4979 * because that use of AND conflicts with AND as a boolean operator. So,
4980 * b_expr is used in BETWEEN and we remove boolean keywords from b_expr.
4982 * Note that '(' a_expr ')' is a b_expr, so an unrestricted expression can
4983 * always be used by surrounding it with parens.
4985 * c_expr is all the productions that are common to a_expr and b_expr;
4986 * it's factored out just to eliminate redundant coding.
4990 | a_expr TYPECAST Typename
4991 { $$ = makeTypeCast($1, $3); }
4992 | a_expr COLLATE ColId
4994 FuncCall *n = makeNode(FuncCall);
4995 n->funcname = SystemFuncName($3);
4996 n->args = makeList1($1);
4997 n->agg_star = FALSE;
4998 n->agg_distinct = FALSE;
5001 | a_expr AT TIME ZONE c_expr
5003 FuncCall *n = makeNode(FuncCall);
5004 n->funcname = SystemFuncName("timezone");
5005 n->args = makeList2($5, $1);
5006 n->agg_star = FALSE;
5007 n->agg_distinct = FALSE;
5011 * These operators must be called out explicitly in order to make use
5012 * of yacc/bison's automatic operator-precedence handling. All other
5013 * operator names are handled by the generic productions using "Op",
5014 * below; and all those operators will have the same precedence.
5016 * If you add more explicitly-known operators, be sure to add them
5017 * also to b_expr and to the MathOp list above.
5019 | '+' a_expr %prec UMINUS
5020 { $$ = (Node *) makeSimpleA_Expr(OP, "+", NULL, $2); }
5021 | '-' a_expr %prec UMINUS
5022 { $$ = doNegate($2); }
5024 { $$ = (Node *) makeSimpleA_Expr(OP, "%", NULL, $2); }
5026 { $$ = (Node *) makeSimpleA_Expr(OP, "^", NULL, $2); }
5028 { $$ = (Node *) makeSimpleA_Expr(OP, "%", $1, NULL); }
5030 { $$ = (Node *) makeSimpleA_Expr(OP, "^", $1, NULL); }
5032 { $$ = (Node *) makeSimpleA_Expr(OP, "+", $1, $3); }
5034 { $$ = (Node *) makeSimpleA_Expr(OP, "-", $1, $3); }
5036 { $$ = (Node *) makeSimpleA_Expr(OP, "*", $1, $3); }
5038 { $$ = (Node *) makeSimpleA_Expr(OP, "/", $1, $3); }
5040 { $$ = (Node *) makeSimpleA_Expr(OP, "%", $1, $3); }
5042 { $$ = (Node *) makeSimpleA_Expr(OP, "^", $1, $3); }
5044 { $$ = (Node *) makeSimpleA_Expr(OP, "<", $1, $3); }
5046 { $$ = (Node *) makeSimpleA_Expr(OP, ">", $1, $3); }
5048 { $$ = (Node *) makeSimpleA_Expr(OP, "=", $1, $3); }
5050 | a_expr qual_Op a_expr %prec Op
5051 { $$ = (Node *) makeA_Expr(OP, $2, $1, $3); }
5052 | qual_Op a_expr %prec Op
5053 { $$ = (Node *) makeA_Expr(OP, $1, NULL, $2); }
5054 | a_expr qual_Op %prec POSTFIXOP
5055 { $$ = (Node *) makeA_Expr(OP, $2, $1, NULL); }
5058 { $$ = (Node *) makeA_Expr(AND, NIL, $1, $3); }
5060 { $$ = (Node *) makeA_Expr(OR, NIL, $1, $3); }
5062 { $$ = (Node *) makeA_Expr(NOT, NIL, NULL, $2); }
5064 | a_expr LIKE a_expr
5065 { $$ = (Node *) makeSimpleA_Expr(OP, "~~", $1, $3); }
5066 | a_expr LIKE a_expr ESCAPE a_expr
5068 FuncCall *n = makeNode(FuncCall);
5069 n->funcname = SystemFuncName("like_escape");
5070 n->args = makeList2($3, $5);
5071 n->agg_star = FALSE;
5072 n->agg_distinct = FALSE;
5073 $$ = (Node *) makeSimpleA_Expr(OP, "~~", $1, (Node *) n);
5075 | a_expr NOT LIKE a_expr
5076 { $$ = (Node *) makeSimpleA_Expr(OP, "!~~", $1, $4); }
5077 | a_expr NOT LIKE a_expr ESCAPE a_expr
5079 FuncCall *n = makeNode(FuncCall);
5080 n->funcname = SystemFuncName("like_escape");
5081 n->args = makeList2($4, $6);
5082 n->agg_star = FALSE;
5083 n->agg_distinct = FALSE;
5084 $$ = (Node *) makeSimpleA_Expr(OP, "!~~", $1, (Node *) n);
5086 | a_expr ILIKE a_expr
5087 { $$ = (Node *) makeSimpleA_Expr(OP, "~~*", $1, $3); }
5088 | a_expr ILIKE a_expr ESCAPE a_expr
5090 FuncCall *n = makeNode(FuncCall);
5091 n->funcname = SystemFuncName("like_escape");
5092 n->args = makeList2($3, $5);
5093 n->agg_star = FALSE;
5094 n->agg_distinct = FALSE;
5095 $$ = (Node *) makeSimpleA_Expr(OP, "~~*", $1, (Node *) n);
5097 | a_expr NOT ILIKE a_expr
5098 { $$ = (Node *) makeSimpleA_Expr(OP, "!~~*", $1, $4); }
5099 | a_expr NOT ILIKE a_expr ESCAPE a_expr
5101 FuncCall *n = makeNode(FuncCall);
5102 n->funcname = SystemFuncName("like_escape");
5103 n->args = makeList2($4, $6);
5104 n->agg_star = FALSE;
5105 n->agg_distinct = FALSE;
5106 $$ = (Node *) makeSimpleA_Expr(OP, "!~~*", $1, (Node *) n);
5109 | a_expr SIMILAR TO a_expr %prec SIMILAR
5110 { $$ = (Node *) makeSimpleA_Expr(OP, "~", $1, $4); }
5111 | a_expr SIMILAR TO a_expr ESCAPE a_expr
5113 FuncCall *n = makeNode(FuncCall);
5114 n->funcname = SystemFuncName("like_escape");
5115 n->args = makeList2($4, $6);
5116 n->agg_star = FALSE;
5117 n->agg_distinct = FALSE;
5118 $$ = (Node *) makeSimpleA_Expr(OP, "~", $1, (Node *) n);
5120 | a_expr NOT SIMILAR TO a_expr %prec SIMILAR
5121 { $$ = (Node *) makeSimpleA_Expr(OP, "!~", $1, $5); }
5122 | a_expr NOT SIMILAR TO a_expr ESCAPE a_expr
5124 FuncCall *n = makeNode(FuncCall);
5125 n->funcname = SystemFuncName("like_escape");
5126 n->args = makeList2($5, $7);
5127 n->agg_star = FALSE;
5128 n->agg_distinct = FALSE;
5129 $$ = (Node *) makeSimpleA_Expr(OP, "!~", $1, (Node *) n);
5133 * Define SQL92-style Null test clause.
5134 * Allow two forms described in the standard:
5137 * Allow two SQL extensions
5140 * NOTE: this is not yet fully SQL-compatible, since SQL92
5141 * allows a row constructor as argument, not just a scalar.
5145 NullTest *n = makeNode(NullTest);
5147 n->nulltesttype = IS_NULL;
5152 NullTest *n = makeNode(NullTest);
5154 n->nulltesttype = IS_NULL;
5159 NullTest *n = makeNode(NullTest);
5161 n->nulltesttype = IS_NOT_NULL;
5164 | a_expr IS NOT NULL_P
5166 NullTest *n = makeNode(NullTest);
5168 n->nulltesttype = IS_NOT_NULL;
5171 /* IS TRUE, IS FALSE, etc used to be function calls
5172 * but let's make them expressions to allow the optimizer
5173 * a chance to eliminate them if a_expr is a constant string.
5174 * - thomas 1997-12-22
5176 * Created BooleanTest Node type, and changed handling
5182 BooleanTest *b = makeNode(BooleanTest);
5184 b->booltesttype = IS_TRUE;
5187 | a_expr IS NOT TRUE_P
5189 BooleanTest *b = makeNode(BooleanTest);
5191 b->booltesttype = IS_NOT_TRUE;
5196 BooleanTest *b = makeNode(BooleanTest);
5198 b->booltesttype = IS_FALSE;
5201 | a_expr IS NOT FALSE_P
5203 BooleanTest *b = makeNode(BooleanTest);
5205 b->booltesttype = IS_NOT_FALSE;
5210 BooleanTest *b = makeNode(BooleanTest);
5212 b->booltesttype = IS_UNKNOWN;
5215 | a_expr IS NOT UNKNOWN
5217 BooleanTest *b = makeNode(BooleanTest);
5219 b->booltesttype = IS_NOT_UNKNOWN;
5222 | a_expr BETWEEN b_expr AND b_expr %prec BETWEEN
5224 $$ = (Node *) makeA_Expr(AND, NIL,
5225 (Node *) makeSimpleA_Expr(OP, ">=", $1, $3),
5226 (Node *) makeSimpleA_Expr(OP, "<=", $1, $5));
5228 | a_expr NOT BETWEEN b_expr AND b_expr %prec BETWEEN
5230 $$ = (Node *) makeA_Expr(OR, NIL,
5231 (Node *) makeSimpleA_Expr(OP, "<", $1, $4),
5232 (Node *) makeSimpleA_Expr(OP, ">", $1, $6));
5234 | a_expr IN_P in_expr
5236 /* in_expr returns a SubLink or a list of a_exprs */
5237 if (IsA($3, SubLink))
5239 SubLink *n = (SubLink *)$3;
5240 n->lefthand = makeList1($1);
5241 n->oper = (List *) makeSimpleA_Expr(OP, "=",
5244 n->subLinkType = ANY_SUBLINK;
5251 foreach(l, (List *) $3)
5254 cmp = (Node *) makeSimpleA_Expr(OP, "=",
5259 n = (Node *) makeA_Expr(OR, NIL, n, cmp);
5264 | a_expr NOT IN_P in_expr
5266 /* in_expr returns a SubLink or a list of a_exprs */
5267 if (IsA($4, SubLink))
5269 SubLink *n = (SubLink *)$4;
5270 n->lefthand = makeList1($1);
5271 n->oper = (List *) makeSimpleA_Expr(OP, "<>",
5274 n->subLinkType = ALL_SUBLINK;
5281 foreach(l, (List *) $4)
5284 cmp = (Node *) makeSimpleA_Expr(OP, "<>",
5289 n = (Node *) makeA_Expr(AND, NIL, n, cmp);
5294 | a_expr qual_all_Op sub_type select_with_parens %prec Op
5296 SubLink *n = makeNode(SubLink);
5297 n->lefthand = makeList1($1);
5298 n->oper = (List *) makeA_Expr(OP, $2, NULL, NULL);
5299 n->useor = FALSE; /* doesn't matter since only one col */
5300 n->subLinkType = $3;
5309 * Restricted expressions
5311 * b_expr is a subset of the complete expression syntax defined by a_expr.
5313 * Presently, AND, NOT, IS, and IN are the a_expr keywords that would
5314 * cause trouble in the places where b_expr is used. For simplicity, we
5315 * just eliminate all the boolean-keyword-operator productions from b_expr.
5319 | b_expr TYPECAST Typename
5320 { $$ = makeTypeCast($1, $3); }
5321 | '+' b_expr %prec UMINUS
5322 { $$ = (Node *) makeSimpleA_Expr(OP, "+", NULL, $2); }
5323 | '-' b_expr %prec UMINUS
5324 { $$ = doNegate($2); }
5326 { $$ = (Node *) makeSimpleA_Expr(OP, "%", NULL, $2); }
5328 { $$ = (Node *) makeSimpleA_Expr(OP, "^", NULL, $2); }
5330 { $$ = (Node *) makeSimpleA_Expr(OP, "%", $1, NULL); }
5332 { $$ = (Node *) makeSimpleA_Expr(OP, "^", $1, NULL); }
5334 { $$ = (Node *) makeSimpleA_Expr(OP, "+", $1, $3); }
5336 { $$ = (Node *) makeSimpleA_Expr(OP, "-", $1, $3); }
5338 { $$ = (Node *) makeSimpleA_Expr(OP, "*", $1, $3); }
5340 { $$ = (Node *) makeSimpleA_Expr(OP, "/", $1, $3); }
5342 { $$ = (Node *) makeSimpleA_Expr(OP, "%", $1, $3); }
5344 { $$ = (Node *) makeSimpleA_Expr(OP, "^", $1, $3); }
5346 { $$ = (Node *) makeSimpleA_Expr(OP, "<", $1, $3); }
5348 { $$ = (Node *) makeSimpleA_Expr(OP, ">", $1, $3); }
5350 { $$ = (Node *) makeSimpleA_Expr(OP, "=", $1, $3); }
5352 | b_expr qual_Op b_expr %prec Op
5353 { $$ = (Node *) makeA_Expr(OP, $2, $1, $3); }
5354 | qual_Op b_expr %prec Op
5355 { $$ = (Node *) makeA_Expr(OP, $1, NULL, $2); }
5356 | b_expr qual_Op %prec POSTFIXOP
5357 { $$ = (Node *) makeA_Expr(OP, $2, $1, NULL); }
5361 * Productions that can be used in both a_expr and b_expr.
5363 * Note: productions that refer recursively to a_expr or b_expr mostly
5364 * cannot appear here. However, it's OK to refer to a_exprs that occur
5365 * inside parentheses, such as function arguments; that cannot introduce
5366 * ambiguity to the b_expr syntax.
5369 { $$ = (Node *) $1; }
5372 | PARAM attrs opt_indirection
5375 * PARAM without field names is considered a constant,
5376 * but with 'em, it is not. Not very consistent ...
5378 ParamRef *n = makeNode(ParamRef);
5381 n->indirection = $3;
5386 | '(' a_expr ')' attrs opt_indirection
5388 ExprFieldSelect *n = makeNode(ExprFieldSelect);
5391 n->indirection = $5;
5394 | CAST '(' a_expr AS Typename ')'
5395 { $$ = makeTypeCast($3, $5); }
5400 FuncCall *n = makeNode(FuncCall);
5403 n->agg_star = FALSE;
5404 n->agg_distinct = FALSE;
5407 | func_name '(' expr_list ')'
5409 FuncCall *n = makeNode(FuncCall);
5412 n->agg_star = FALSE;
5413 n->agg_distinct = FALSE;
5416 | func_name '(' ALL expr_list ')'
5418 FuncCall *n = makeNode(FuncCall);
5421 n->agg_star = FALSE;
5422 n->agg_distinct = FALSE;
5423 /* Ideally we'd mark the FuncCall node to indicate
5424 * "must be an aggregate", but there's no provision
5425 * for that in FuncCall at the moment.
5429 | func_name '(' DISTINCT expr_list ')'
5431 FuncCall *n = makeNode(FuncCall);
5434 n->agg_star = FALSE;
5435 n->agg_distinct = TRUE;
5438 | func_name '(' '*' ')'
5441 * For now, we transform AGGREGATE(*) into AGGREGATE(1).
5443 * This does the right thing for COUNT(*) (in fact,
5444 * any certainly-non-null expression would do for COUNT),
5445 * and there are no other aggregates in SQL92 that accept
5448 * The FuncCall node is also marked agg_star = true,
5449 * so that later processing can detect what the argument
5452 FuncCall *n = makeNode(FuncCall);
5453 A_Const *star = makeNode(A_Const);
5455 star->val.type = T_Integer;
5456 star->val.val.ival = 1;
5458 n->args = makeList1(star);
5460 n->agg_distinct = FALSE;
5466 * Translate as "'now'::text::date".
5468 * We cannot use "'now'::date" because coerce_type() will
5469 * immediately reduce that to a constant representing
5470 * today's date. We need to delay the conversion until
5471 * runtime, else the wrong things will happen when
5472 * CURRENT_DATE is used in a column default value or rule.
5474 * This could be simplified if we had a way to generate
5475 * an expression tree representing runtime application
5476 * of type-input conversion functions...
5478 A_Const *s = makeNode(A_Const);
5481 s->val.type = T_String;
5482 s->val.val.str = "now";
5483 s->typename = SystemTypeName("text");
5485 d = SystemTypeName("date");
5487 $$ = (Node *)makeTypeCast((Node *)s, d);
5492 * Translate as "'now'::text::timetz".
5493 * See comments for CURRENT_DATE.
5495 A_Const *s = makeNode(A_Const);
5498 s->val.type = T_String;
5499 s->val.val.str = "now";
5500 s->typename = SystemTypeName("text");
5502 d = SystemTypeName("timetz");
5503 /* SQL99 mandates a default precision of zero for TIME
5504 * fields in schemas. However, for CURRENT_TIME
5505 * let's preserve the microsecond precision we
5506 * might see from the system clock. - thomas 2001-12-07
5510 $$ = (Node *)makeTypeCast((Node *)s, d);
5512 | CURRENT_TIME '(' Iconst ')'
5515 * Translate as "'now'::text::timetz(n)".
5516 * See comments for CURRENT_DATE.
5518 A_Const *s = makeNode(A_Const);
5521 s->val.type = T_String;
5522 s->val.val.str = "now";
5523 s->typename = SystemTypeName("text");
5524 d = SystemTypeName("timetz");
5525 if (($3 < 0) || ($3 > MAX_TIME_PRECISION))
5526 elog(ERROR, "CURRENT_TIME(%d) precision must be between %d and %d",
5527 $3, 0, MAX_TIME_PRECISION);
5530 $$ = (Node *)makeTypeCast((Node *)s, d);
5535 * Translate as "'now'::text::timestamptz".
5536 * See comments for CURRENT_DATE.
5538 A_Const *s = makeNode(A_Const);
5541 s->val.type = T_String;
5542 s->val.val.str = "now";
5543 s->typename = SystemTypeName("text");
5545 d = SystemTypeName("timestamptz");
5546 /* SQL99 mandates a default precision of 6 for timestamp.
5547 * Also, that is about as precise as we will get since
5548 * we are using a microsecond time interface.
5549 * - thomas 2001-12-07
5553 $$ = (Node *)makeTypeCast((Node *)s, d);
5555 | CURRENT_TIMESTAMP '(' Iconst ')'
5558 * Translate as "'now'::text::timestamptz(n)".
5559 * See comments for CURRENT_DATE.
5561 A_Const *s = makeNode(A_Const);
5564 s->val.type = T_String;
5565 s->val.val.str = "now";
5566 s->typename = SystemTypeName("text");
5568 d = SystemTypeName("timestamptz");
5569 if (($3 < 0) || ($3 > MAX_TIMESTAMP_PRECISION))
5570 elog(ERROR, "CURRENT_TIMESTAMP(%d) precision must be between %d and %d",
5571 $3, 0, MAX_TIMESTAMP_PRECISION);
5574 $$ = (Node *)makeTypeCast((Node *)s, d);
5579 * Translate as "'now'::text::time".
5580 * See comments for CURRENT_DATE.
5582 A_Const *s = makeNode(A_Const);
5585 s->val.type = T_String;
5586 s->val.val.str = "now";
5587 s->typename = SystemTypeName("text");
5589 d = SystemTypeName("time");
5590 /* SQL99 mandates a default precision of zero for TIME
5591 * fields in schemas. However, for LOCALTIME
5592 * let's preserve the microsecond precision we
5593 * might see from the system clock. - thomas 2001-12-07
5597 $$ = (Node *)makeTypeCast((Node *)s, d);
5599 | LOCALTIME '(' Iconst ')'
5602 * Translate as "'now'::text::time(n)".
5603 * See comments for CURRENT_DATE.
5605 A_Const *s = makeNode(A_Const);
5608 s->val.type = T_String;
5609 s->val.val.str = "now";
5610 s->typename = SystemTypeName("text");
5611 d = SystemTypeName("time");
5612 if (($3 < 0) || ($3 > MAX_TIME_PRECISION))
5613 elog(ERROR, "LOCALTIME(%d) precision must be between %d and %d",
5614 $3, 0, MAX_TIME_PRECISION);
5617 $$ = (Node *)makeTypeCast((Node *)s, d);
5622 * Translate as "'now'::text::timestamp".
5623 * See comments for CURRENT_DATE.
5625 A_Const *s = makeNode(A_Const);
5628 s->val.type = T_String;
5629 s->val.val.str = "now";
5630 s->typename = SystemTypeName("text");
5632 d = SystemTypeName("timestamp");
5633 /* SQL99 mandates a default precision of 6 for timestamp.
5634 * Also, that is about as precise as we will get since
5635 * we are using a microsecond time interface.
5636 * - thomas 2001-12-07
5640 $$ = (Node *)makeTypeCast((Node *)s, d);
5642 | LOCALTIMESTAMP '(' Iconst ')'
5645 * Translate as "'now'::text::timestamp(n)".
5646 * See comments for CURRENT_DATE.
5648 A_Const *s = makeNode(A_Const);
5651 s->val.type = T_String;
5652 s->val.val.str = "now";
5653 s->typename = SystemTypeName("text");
5655 d = SystemTypeName("timestamp");
5656 if (($3 < 0) || ($3 > MAX_TIMESTAMP_PRECISION))
5657 elog(ERROR, "LOCALTIMESTAMP(%d) precision must be between %d and %d",
5658 $3, 0, MAX_TIMESTAMP_PRECISION);
5661 $$ = (Node *)makeTypeCast((Node *)s, d);
5665 FuncCall *n = makeNode(FuncCall);
5666 n->funcname = SystemFuncName("current_user");
5668 n->agg_star = FALSE;
5669 n->agg_distinct = FALSE;
5674 FuncCall *n = makeNode(FuncCall);
5675 n->funcname = SystemFuncName("session_user");
5677 n->agg_star = FALSE;
5678 n->agg_distinct = FALSE;
5683 FuncCall *n = makeNode(FuncCall);
5684 n->funcname = SystemFuncName("current_user");
5686 n->agg_star = FALSE;
5687 n->agg_distinct = FALSE;
5690 | EXTRACT '(' extract_list ')'
5692 FuncCall *n = makeNode(FuncCall);
5693 n->funcname = SystemFuncName("date_part");
5695 n->agg_star = FALSE;
5696 n->agg_distinct = FALSE;
5699 | OVERLAY '(' overlay_list ')'
5701 /* overlay(A PLACING B FROM C FOR D) is converted to
5702 * substring(A, 1, C-1) || B || substring(A, C+1, C+D)
5703 * overlay(A PLACING B FROM C) is converted to
5704 * substring(A, 1, C-1) || B || substring(A, C+1, C+char_length(B))
5706 FuncCall *n = makeNode(FuncCall);
5707 n->funcname = SystemFuncName("overlay");
5709 n->agg_star = FALSE;
5710 n->agg_distinct = FALSE;
5713 | POSITION '(' position_list ')'
5715 /* position(A in B) is converted to position(B, A) */
5716 FuncCall *n = makeNode(FuncCall);
5717 n->funcname = SystemFuncName("position");
5719 n->agg_star = FALSE;
5720 n->agg_distinct = FALSE;
5723 | SUBSTRING '(' substr_list ')'
5725 /* substring(A from B for C) is converted to
5726 * substring(A, B, C) - thomas 2000-11-28
5728 FuncCall *n = makeNode(FuncCall);
5729 n->funcname = SystemFuncName("substring");
5731 n->agg_star = FALSE;
5732 n->agg_distinct = FALSE;
5735 | TRIM '(' BOTH trim_list ')'
5737 /* various trim expressions are defined in SQL92
5738 * - thomas 1997-07-19
5740 FuncCall *n = makeNode(FuncCall);
5741 n->funcname = SystemFuncName("btrim");
5743 n->agg_star = FALSE;
5744 n->agg_distinct = FALSE;
5747 | TRIM '(' LEADING trim_list ')'
5749 FuncCall *n = makeNode(FuncCall);
5750 n->funcname = SystemFuncName("ltrim");
5752 n->agg_star = FALSE;
5753 n->agg_distinct = FALSE;
5756 | TRIM '(' TRAILING trim_list ')'
5758 FuncCall *n = makeNode(FuncCall);
5759 n->funcname = SystemFuncName("rtrim");
5761 n->agg_star = FALSE;
5762 n->agg_distinct = FALSE;
5765 | TRIM '(' trim_list ')'
5767 FuncCall *n = makeNode(FuncCall);
5768 n->funcname = SystemFuncName("btrim");
5770 n->agg_star = FALSE;
5771 n->agg_distinct = FALSE;
5774 | select_with_parens %prec UMINUS
5776 SubLink *n = makeNode(SubLink);
5780 n->subLinkType = EXPR_SUBLINK;
5784 | EXISTS select_with_parens
5786 SubLink *n = makeNode(SubLink);
5790 n->subLinkType = EXISTS_SUBLINK;
5797 * Supporting nonterminals for expressions.
5800 opt_indirection: opt_indirection '[' a_expr ']'
5802 A_Indices *ai = makeNode(A_Indices);
5805 $$ = lappend($1, ai);
5807 | opt_indirection '[' a_expr ':' a_expr ']'
5809 A_Indices *ai = makeNode(A_Indices);
5812 $$ = lappend($1, ai);
5819 { $$ = makeList1($1); }
5820 | expr_list ',' a_expr
5821 { $$ = lappend($1, $3); }
5822 | expr_list USING a_expr
5823 { $$ = lappend($1, $3); }
5826 extract_list: extract_arg FROM a_expr
5828 A_Const *n = makeNode(A_Const);
5829 n->val.type = T_String;
5830 n->val.val.str = $1;
5831 $$ = makeList2((Node *) n, $3);
5837 /* Allow delimited string SCONST in extract_arg as an SQL extension.
5838 * - thomas 2001-04-12
5841 extract_arg: IDENT { $$ = $1; }
5842 | YEAR_P { $$ = "year"; }
5843 | MONTH_P { $$ = "month"; }
5844 | DAY_P { $$ = "day"; }
5845 | HOUR_P { $$ = "hour"; }
5846 | MINUTE_P { $$ = "minute"; }
5847 | SECOND_P { $$ = "second"; }
5848 | SCONST { $$ = $1; }
5851 /* OVERLAY() arguments
5852 * SQL99 defines the OVERLAY() function:
5853 * o overlay(text placing text from int for int)
5854 * o overlay(text placing text from int)
5856 overlay_list: a_expr overlay_placing substr_from substr_for
5858 $$ = makeList4($1, $2, $3, $4);
5860 | a_expr overlay_placing substr_from
5862 $$ = makeList3($1, $2, $3);
5866 overlay_placing: PLACING a_expr
5870 /* position_list uses b_expr not a_expr to avoid conflict with general IN */
5872 position_list: b_expr IN_P b_expr
5873 { $$ = makeList2($3, $1); }
5878 /* SUBSTRING() arguments
5879 * SQL9x defines a specific syntax for arguments to SUBSTRING():
5880 * o substring(text from int for int)
5881 * o substring(text from int) get entire string from starting point "int"
5882 * o substring(text for int) get first "int" characters of string
5883 * We also want to implement generic substring functions which accept
5884 * the usual generic list of arguments. So we will accept both styles
5885 * here, and convert the SQL9x style to the generic list for further
5886 * processing. - thomas 2000-11-28
5888 substr_list: a_expr substr_from substr_for
5890 $$ = makeList3($1, $2, $3);
5892 | a_expr substr_for substr_from
5894 $$ = makeList3($1, $3, $2);
5896 | a_expr substr_from
5898 $$ = makeList2($1, $2);
5902 A_Const *n = makeNode(A_Const);
5903 n->val.type = T_Integer;
5904 n->val.val.ival = 1;
5905 $$ = makeList3($1, (Node *)n, $2);
5915 substr_from: FROM a_expr
5919 substr_for: FOR a_expr
5923 trim_list: a_expr FROM expr_list
5924 { $$ = lappend($3, $1); }
5931 in_expr: select_with_parens
5933 SubLink *n = makeNode(SubLink);
5937 | '(' in_expr_nodes ')'
5938 { $$ = (Node *)$2; }
5941 in_expr_nodes: a_expr
5942 { $$ = makeList1($1); }
5943 | in_expr_nodes ',' a_expr
5944 { $$ = lappend($1, $3); }
5948 * Define SQL92-style case clause.
5949 * Allow all four forms described in the standard:
5950 * - Full specification
5951 * CASE WHEN a = b THEN c ... ELSE d END
5952 * - Implicit argument
5953 * CASE a WHEN b THEN c ... ELSE d END
5954 * - Conditional NULL
5956 * same as CASE WHEN x = y THEN NULL ELSE x END
5957 * - Conditional substitution from list, use first non-null argument
5959 * same as CASE WHEN a IS NOT NULL THEN a WHEN b IS NOT NULL THEN b ... END
5960 * - thomas 1998-11-09
5962 case_expr: CASE case_arg when_clause_list case_default END_TRANS
5964 CaseExpr *c = makeNode(CaseExpr);
5970 | NULLIF '(' a_expr ',' a_expr ')'
5972 CaseExpr *c = makeNode(CaseExpr);
5973 CaseWhen *w = makeNode(CaseWhen);
5975 w->expr = (Node *) makeSimpleA_Expr(OP, "=", $3, $5);
5976 /* w->result is left NULL */
5977 c->args = makeList1(w);
5981 | COALESCE '(' expr_list ')'
5983 CaseExpr *c = makeNode(CaseExpr);
5987 CaseWhen *w = makeNode(CaseWhen);
5988 NullTest *n = makeNode(NullTest);
5990 n->nulltesttype = IS_NOT_NULL;
5991 w->expr = (Node *) n;
5992 w->result = lfirst(l);
5993 c->args = lappend(c->args, w);
5999 when_clause_list: when_clause_list when_clause
6000 { $$ = lappend($1, $2); }
6002 { $$ = makeList1($1); }
6005 when_clause: WHEN a_expr THEN a_expr
6007 CaseWhen *w = makeNode(CaseWhen);
6014 case_default: ELSE a_expr { $$ = $2; }
6015 | /*EMPTY*/ { $$ = NULL; }
6025 * columnref starts with relation_name not ColId, so that OLD and NEW
6026 * references can be accepted. Note that when there are more than two
6027 * dotted names, the first name is not actually a relation name...
6029 columnref: relation_name opt_indirection
6031 $$ = makeNode(ColumnRef);
6032 $$->fields = makeList1(makeString($1));
6033 $$->indirection = $2;
6035 | dotted_name opt_indirection
6037 $$ = makeNode(ColumnRef);
6039 $$->indirection = $2;
6043 dotted_name: relation_name attrs
6044 { $$ = lcons(makeString($1), $2); }
6047 attrs: '.' attr_name
6048 { $$ = makeList1(makeString($2)); }
6050 { $$ = makeList1(makeString("*")); }
6051 | '.' attr_name attrs
6052 { $$ = lcons(makeString($2), $3); }
6056 /*****************************************************************************
6060 *****************************************************************************/
6062 /* Target lists as found in SELECT ... and INSERT VALUES ( ... ) */
6064 target_list: target_list ',' target_el
6065 { $$ = lappend($1, $3); }
6067 { $$ = makeList1($1); }
6070 /* AS is not optional because shift/red conflict with unary ops */
6071 target_el: a_expr AS ColLabel
6073 $$ = makeNode(ResTarget);
6075 $$->indirection = NIL;
6076 $$->val = (Node *)$1;
6080 $$ = makeNode(ResTarget);
6082 $$->indirection = NIL;
6083 $$->val = (Node *)$1;
6087 ColumnRef *n = makeNode(ColumnRef);
6088 n->fields = makeList1(makeString("*"));
6089 n->indirection = NIL;
6090 $$ = makeNode(ResTarget);
6092 $$->indirection = NIL;
6093 $$->val = (Node *)n;
6097 /* Target list as found in UPDATE table SET ...
6098 | '(' row_ ')' = '(' row_ ')'
6103 update_target_list: update_target_list ',' update_target_el
6104 { $$ = lappend($1,$3); }
6106 { $$ = makeList1($1); }
6109 update_target_el: ColId opt_indirection '=' a_expr
6111 $$ = makeNode(ResTarget);
6113 $$->indirection = $2;
6114 $$->val = (Node *)$4;
6118 insert_target_list: insert_target_list ',' insert_target_el
6119 { $$ = lappend($1, $3); }
6121 { $$ = makeList1($1); }
6124 insert_target_el: target_el { $$ = $1; }
6126 InsertDefault *def = makeNode(InsertDefault);
6127 $$ = makeNode(ResTarget);
6129 $$->indirection = NULL;
6130 $$->val = (Node *)def;
6135 /*****************************************************************************
6137 * Names and constants
6139 *****************************************************************************/
6141 relation_name: SpecialRuleRelation
6151 qualified_name_list: qualified_name
6152 { $$ = makeList1($1); }
6153 | qualified_name_list ',' qualified_name
6154 { $$ = lappend($1, $3); }
6157 qualified_name: relation_name
6159 $$ = makeNode(RangeVar);
6160 $$->catalogname = NULL;
6161 $$->schemaname = NULL;
6166 $$ = makeNode(RangeVar);
6170 $$->catalogname = NULL;
6171 $$->schemaname = strVal(lfirst($1));
6172 $$->relname = strVal(lsecond($1));
6175 $$->catalogname = strVal(lfirst($1));
6176 $$->schemaname = strVal(lsecond($1));
6177 $$->relname = strVal(lfirst(lnext(lnext($1))));
6180 elog(ERROR, "Improper qualified name (too many dotted names): %s",
6181 NameListToString($1));
6188 { $$ = makeList1(makeString($1)); }
6189 | name_list ',' name
6190 { $$ = lappend($1, makeString($3)); }
6194 name: ColId { $$ = $1; };
6195 database_name: ColId { $$ = $1; };
6196 access_method: ColId { $$ = $1; };
6197 attr_name: ColId { $$ = $1; };
6198 index_name: ColId { $$ = $1; };
6199 file_name: Sconst { $$ = $1; };
6201 func_name: function_name
6202 { $$ = makeList1(makeString($1)); }
6209 * Include TRUE/FALSE for SQL3 support. - thomas 1997-10-24
6213 A_Const *n = makeNode(A_Const);
6214 n->val.type = T_Integer;
6215 n->val.val.ival = $1;
6220 A_Const *n = makeNode(A_Const);
6221 n->val.type = T_Float;
6222 n->val.val.str = $1;
6227 A_Const *n = makeNode(A_Const);
6228 n->val.type = T_String;
6229 n->val.val.str = $1;
6234 A_Const *n = makeNode(A_Const);
6235 n->val.type = T_BitString;
6236 n->val.val.str = $1;
6239 /* This rule formerly used Typename,
6240 * but that causes reduce conflicts with subscripted column names.
6241 * Now, separate into ConstTypename and ConstInterval,
6242 * to allow implementing the SQL92 syntax for INTERVAL literals.
6243 * - thomas 2000-06-24
6245 | ConstTypename Sconst
6247 A_Const *n = makeNode(A_Const);
6249 n->val.type = T_String;
6250 n->val.val.str = $2;
6253 | ConstInterval Sconst opt_interval
6255 A_Const *n = makeNode(A_Const);
6257 n->val.type = T_String;
6258 n->val.val.str = $2;
6259 /* precision is not specified, but fields may be... */
6261 n->typename->typmod = ((($3 & 0x7FFF) << 16) | 0xFFFF);
6264 | ConstInterval '(' Iconst ')' Sconst opt_interval
6266 A_Const *n = makeNode(A_Const);
6268 n->val.type = T_String;
6269 n->val.val.str = $5;
6270 /* precision specified, and fields may be... */
6271 if (($3 < 0) || ($3 > MAX_INTERVAL_PRECISION))
6272 elog(ERROR, "INTERVAL(%d) precision must be between %d and %d",
6273 $3, 0, MAX_INTERVAL_PRECISION);
6274 n->typename->typmod = ((($6 & 0x7FFF) << 16) | $3);
6277 | PARAM opt_indirection
6279 ParamRef *n = makeNode(ParamRef);
6282 n->indirection = $2;
6287 A_Const *n = makeNode(A_Const);
6288 n->val.type = T_String;
6289 n->val.val.str = "t";
6290 n->typename = SystemTypeName("bool");
6295 A_Const *n = makeNode(A_Const);
6296 n->val.type = T_String;
6297 n->val.val.str = "f";
6298 n->typename = SystemTypeName("bool");
6303 A_Const *n = makeNode(A_Const);
6304 n->val.type = T_Null;
6309 Iconst: ICONST { $$ = $1; };
6310 Sconst: SCONST { $$ = $1; };
6311 UserId: ColId { $$ = $1; };
6314 * Name classification hierarchy.
6316 * IDENT is the lexeme returned by the lexer for identifiers that match
6317 * no known keyword. In most cases, we can accept certain keywords as
6318 * names, not only IDENTs. We prefer to accept as many such keywords
6319 * as possible to minimize the impact of "reserved words" on programmers.
6320 * So, we divide names into several possible classes. The classification
6321 * is chosen in part to make keywords acceptable as names wherever possible.
6324 /* Column identifier --- names that can be column, table, etc names.
6326 ColId: IDENT { $$ = $1; }
6327 | unreserved_keyword { $$ = pstrdup($1); }
6328 | col_name_keyword { $$ = pstrdup($1); }
6331 /* Type identifier --- names that can be type names.
6333 type_name: IDENT { $$ = $1; }
6334 | unreserved_keyword { $$ = pstrdup($1); }
6337 /* Function identifier --- names that can be function names.
6339 function_name: IDENT { $$ = $1; }
6340 | unreserved_keyword { $$ = pstrdup($1); }
6341 | func_name_keyword { $$ = pstrdup($1); }
6344 /* Column label --- allowed labels in "AS" clauses.
6345 * This presently includes *all* Postgres keywords.
6347 ColLabel: IDENT { $$ = $1; }
6348 | unreserved_keyword { $$ = pstrdup($1); }
6349 | col_name_keyword { $$ = pstrdup($1); }
6350 | func_name_keyword { $$ = pstrdup($1); }
6351 | reserved_keyword { $$ = pstrdup($1); }
6356 * Keyword classification lists. Generally, every keyword present in
6357 * the Postgres grammar should appear in exactly one of these lists.
6359 * Put a new keyword into the first list that it can go into without causing
6360 * shift or reduce conflicts. The earlier lists define "less reserved"
6361 * categories of keywords.
6364 /* "Unreserved" keywords --- available for use as any kind of name.
6537 /* Column identifier --- keywords that can be column, table, etc names.
6539 * Many of these keywords will in fact be recognized as type or function
6540 * names too; but they have special productions for the purpose, and so
6541 * can't be treated as "generic" type or function names.
6543 * The type names appearing here are not usable as function names
6544 * because they can be followed by '(' in typename productions, which
6545 * looks too much like a function call for an LR(1) parser.
6578 /* Function identifier --- keywords that can be function names.
6580 * Most of these are keywords that are used as operators in expressions;
6581 * in general such keywords can't be column names because they would be
6582 * ambiguous with variables, but they are unambiguous as function identifiers.
6584 * Do not include POSITION, SUBSTRING, etc here since they have explicit
6585 * productions in a_expr to support the goofy SQL9x argument syntax.
6586 * - thomas 2000-11-28
6612 /* Reserved keyword --- these keywords are usable only as a ColLabel.
6614 * Keywords appear here if they could not be distinguished from variable,
6615 * type, or function names in some contexts. Don't put things here unless
6690 SpecialRuleRelation: OLD
6695 elog(ERROR, "OLD used in non-rule query");
6702 elog(ERROR, "NEW used in non-rule query");
6709 makeTypeCast(Node *arg, TypeName *typename)
6712 * If arg is an A_Const, just stick the typename into the
6713 * field reserved for it --- unless there's something there already!
6714 * (We don't want to collapse x::type1::type2 into just x::type2.)
6715 * Otherwise, generate a TypeCast node.
6717 if (IsA(arg, A_Const) &&
6718 ((A_Const *) arg)->typename == NULL)
6720 ((A_Const *) arg)->typename = typename;
6725 TypeCast *n = makeNode(TypeCast);
6727 n->typename = typename;
6733 makeStringConst(char *str, TypeName *typename)
6735 A_Const *n = makeNode(A_Const);
6737 n->val.type = T_String;
6738 n->val.val.str = str;
6739 n->typename = typename;
6745 makeIntConst(int val)
6747 A_Const *n = makeNode(A_Const);
6748 n->val.type = T_Integer;
6749 n->val.val.ival = val;
6750 n->typename = SystemTypeName("int4");
6756 makeFloatConst(char *str)
6758 A_Const *n = makeNode(A_Const);
6760 n->val.type = T_Float;
6761 n->val.val.str = str;
6762 n->typename = SystemTypeName("float8");
6768 makeAConst(Value *v)
6775 n = makeFloatConst(v->val.str);
6779 n = makeIntConst(v->val.ival);
6784 n = makeStringConst(v->val.str, NULL);
6792 * Generate separate operator nodes for a single row descriptor expression.
6793 * Perhaps this should go deeper in the parser someday...
6794 * - thomas 1997-12-22
6797 makeRowExpr(List *opr, List *largs, List *rargs)
6803 if (length(largs) != length(rargs))
6804 elog(ERROR, "Unequal number of entries in row expression");
6806 if (lnext(largs) != NIL)
6807 expr = makeRowExpr(opr, lnext(largs), lnext(rargs));
6809 larg = lfirst(largs);
6810 rarg = lfirst(rargs);
6812 oprname = strVal(llast(opr));
6814 if ((strcmp(oprname, "=") == 0) ||
6815 (strcmp(oprname, "<") == 0) ||
6816 (strcmp(oprname, "<=") == 0) ||
6817 (strcmp(oprname, ">") == 0) ||
6818 (strcmp(oprname, ">=") == 0))
6821 expr = (Node *) makeA_Expr(OP, opr, larg, rarg);
6823 expr = (Node *) makeA_Expr(AND, NIL, expr,
6824 (Node *) makeA_Expr(OP, opr,
6827 else if (strcmp(oprname, "<>") == 0)
6830 expr = (Node *) makeA_Expr(OP, opr, larg, rarg);
6832 expr = (Node *) makeA_Expr(OR, NIL, expr,
6833 (Node *) makeA_Expr(OP, opr,
6838 elog(ERROR, "Operator '%s' not implemented for row expressions",
6845 /* findLeftmostSelect()
6846 * Find the leftmost component SelectStmt in a set-operation parsetree.
6849 findLeftmostSelect(SelectStmt *node)
6851 while (node && node->op != SETOP_NONE)
6853 Assert(node && IsA(node, SelectStmt) && node->larg == NULL);
6857 /* insertSelectOptions()
6858 * Insert ORDER BY, etc into an already-constructed SelectStmt.
6860 * This routine is just to avoid duplicating code in SelectStmt productions.
6863 insertSelectOptions(SelectStmt *stmt,
6864 List *sortClause, List *forUpdate,
6865 Node *limitOffset, Node *limitCount)
6868 * Tests here are to reject constructs like
6869 * (SELECT foo ORDER BY bar) ORDER BY baz
6873 if (stmt->sortClause)
6874 elog(ERROR, "Multiple ORDER BY clauses not allowed");
6875 stmt->sortClause = sortClause;
6879 if (stmt->forUpdate)
6880 elog(ERROR, "Multiple FOR UPDATE clauses not allowed");
6881 stmt->forUpdate = forUpdate;
6885 if (stmt->limitOffset)
6886 elog(ERROR, "Multiple OFFSET clauses not allowed");
6887 stmt->limitOffset = limitOffset;
6891 if (stmt->limitCount)
6892 elog(ERROR, "Multiple LIMIT clauses not allowed");
6893 stmt->limitCount = limitCount;
6898 makeSetOp(SetOperation op, bool all, Node *larg, Node *rarg)
6900 SelectStmt *n = makeNode(SelectStmt);
6904 n->larg = (SelectStmt *) larg;
6905 n->rarg = (SelectStmt *) rarg;
6910 * Build a properly-qualified reference to a built-in function.
6913 SystemFuncName(char *name)
6915 return makeList2(makeString("pg_catalog"), makeString(name));
6919 * Build a properly-qualified reference to a built-in type.
6921 * typmod is defaulted, but may be changed afterwards by caller.
6924 SystemTypeName(char *name)
6926 TypeName *n = makeNode(TypeName);
6928 n->names = makeList2(makeString("pg_catalog"), makeString(name));
6934 * Initialize to parse one query string
6937 parser_init(Oid *typev, int nargs)
6939 QueryIsRule = FALSE;
6941 * Keep enough information around to fill out the type of param nodes
6942 * used in postquel functions
6944 param_type_info = typev;
6945 pfunc_num_args = nargs;
6949 * Fetch a parameter type previously passed to parser_init
6954 if ((t > pfunc_num_args) || (t <= 0))
6956 return param_type_info[t - 1];
6960 * Test whether an a_expr is a plain NULL constant or not.
6963 exprIsNullConstant(Node *arg)
6965 if (arg && IsA(arg, A_Const))
6967 A_Const *con = (A_Const *) arg;
6969 if (con->val.type == T_Null &&
6970 con->typename == NULL)
6977 * doNegate --- handle negation of a numeric constant.
6979 * Formerly, we did this here because the optimizer couldn't cope with
6980 * indexquals that looked like "var = -4" --- it wants "var = const"
6981 * and a unary minus operator applied to a constant didn't qualify.
6982 * As of Postgres 7.0, that problem doesn't exist anymore because there
6983 * is a constant-subexpression simplifier in the optimizer. However,
6984 * there's still a good reason for doing this here, which is that we can
6985 * postpone committing to a particular internal representation for simple
6986 * negative constants. It's better to leave "-123.456" in string form
6987 * until we know what the desired type is.
6992 if (IsA(n, A_Const))
6994 A_Const *con = (A_Const *)n;
6996 if (con->val.type == T_Integer)
6998 con->val.val.ival = -con->val.val.ival;
7001 if (con->val.type == T_Float)
7003 doNegateFloat(&con->val);
7008 return (Node *) makeSimpleA_Expr(OP, "-", NULL, n);
7012 doNegateFloat(Value *v)
7014 char *oldval = v->val.str;
7016 Assert(IsA(v, Float));
7020 v->val.str = oldval+1; /* just strip the '-' */
7023 char *newval = (char *) palloc(strlen(oldval) + 2);
7026 strcpy(newval+1, oldval);
7027 v->val.str = newval;