📄 gram.y
字号:
%{/*#define YYDEBUG 1*//*------------------------------------------------------------------------- * * gram.y * POSTGRES SQL YACC rules/actions * * Portions Copyright (c) 1996-2003, PostgreSQL Global Development Group * Portions Copyright (c) 1994, Regents of the University of California * * * IDENTIFICATION * $Header: /cvsroot/pgsql/src/backend/parser/gram.y,v 2.436.2.1 2003/11/24 16:54:15 tgl Exp $ * * HISTORY * AUTHOR DATE MAJOR EVENT * Andrew Yu Sept, 1994 POSTQUEL to SQL conversion * Andrew Yu Oct, 1994 lispy code conversion * * NOTES * CAPITALS are used to represent terminal symbols. * non-capitals are used to represent non-terminals. * SQL92-specific syntax is separated from plain SQL/Postgres syntax * to help isolate the non-extensible portions of the parser. * * In general, nothing in this file should initiate database accesses * nor depend on changeable state (such as SET variables). If you do * database accesses, your code will fail when we have aborted the * current transaction and are just parsing commands to find the next * ROLLBACK or COMMIT. If you make use of SET variables, then you * will do the wrong thing in multi-query strings like this: * SET SQL_inheritance TO off; SELECT * FROM foo; * because the entire string is parsed by gram.y before the SET gets * executed. Anything that depends on the database or changeable state * should be handled inside parse_analyze() so that it happens at the * right time not the wrong time. The handling of SQL_inheritance is * a good example. * * WARNINGS * If you use a list, make sure the datum is a node so that the printing * routines work. * * Sometimes we assign constants to makeStrings. Make sure we don't free * those. * *------------------------------------------------------------------------- */#include "postgres.h"#include <ctype.h>#include <limits.h>#include "access/htup.h"#include "catalog/index.h"#include "catalog/namespace.h"#include "catalog/pg_type.h"#include "nodes/makefuncs.h"#include "nodes/params.h"#include "nodes/parsenodes.h"#include "parser/gramparse.h"#include "storage/lmgr.h"#include "utils/numeric.h"#include "utils/datetime.h"#include "utils/date.h"extern List *parsetree; /* final parse result is delivered here */static bool QueryIsRule = FALSE;/* * If you need access to certain yacc-generated variables and find that * they're static by default, uncomment the next line. (this is not a * problem, yet.) *//*#define __YYSCLASS*/static Node *makeTypeCast(Node *arg, TypeName *typename);static Node *makeStringConst(char *str, TypeName *typename);static Node *makeIntConst(int val);static Node *makeFloatConst(char *str);static Node *makeAConst(Value *v);static Node *makeRowExpr(List *opr, List *largs, List *rargs);static Node *makeDistinctExpr(List *largs, List *rargs);static Node *makeRowNullTest(NullTestType test, List *args);static DefElem *makeDefElem(char *name, Node *arg);static A_Const *makeBoolConst(bool state);static FuncCall *makeOverlaps(List *largs, List *rargs);static SelectStmt *findLeftmostSelect(SelectStmt *node);static void insertSelectOptions(SelectStmt *stmt, List *sortClause, List *forUpdate, Node *limitOffset, Node *limitCount);static Node *makeSetOp(SetOperation op, bool all, Node *larg, Node *rarg);static Node *doNegate(Node *n);static void doNegateFloat(Value *v);%}%union{ int ival; char chr; char *str; const char *keyword; bool boolean; JoinType jtype; DropBehavior dbehavior; OnCommitAction oncommit; List *list; FastList fastlist; Node *node; Value *value; ColumnRef *columnref; ObjectType objtype; TypeName *typnam; DefElem *defelt; SortBy *sortby; JoinExpr *jexpr; IndexElem *ielem; Alias *alias; RangeVar *range; A_Indices *aind; ResTarget *target; PrivTarget *privtarget; InsertStmt *istmt; VariableSetStmt *vsetstmt;}%type <node> stmt schema_stmt AlterDatabaseSetStmt AlterDomainStmt AlterGroupStmt AlterSeqStmt AlterTableStmt AlterUserStmt AlterUserSetStmt AnalyzeStmt ClosePortalStmt ClusterStmt CommentStmt ConstraintsSetStmt CopyStmt CreateAsStmt CreateCastStmt CreateDomainStmt CreateGroupStmt CreateOpClassStmt CreatePLangStmt CreateSchemaStmt CreateSeqStmt CreateStmt CreateAssertStmt CreateTrigStmt CreateUserStmt CreatedbStmt DeclareCursorStmt DefineStmt DeleteStmt DropGroupStmt DropOpClassStmt DropPLangStmt DropStmt DropAssertStmt DropTrigStmt DropRuleStmt DropCastStmt DropUserStmt DropdbStmt ExplainStmt FetchStmt GrantStmt IndexStmt InsertStmt ListenStmt LoadStmt LockStmt NotifyStmt ExplainableStmt PreparableStmt CreateFunctionStmt ReindexStmt RemoveAggrStmt RemoveFuncStmt RemoveOperStmt RenameStmt RevokeStmt RuleActionStmt RuleActionStmtOrEmpty RuleStmt SelectStmt TransactionStmt TruncateStmt UnlistenStmt UpdateStmt VacuumStmt VariableResetStmt VariableSetStmt VariableShowStmt ViewStmt CheckPointStmt CreateConversionStmt DeallocateStmt PrepareStmt ExecuteStmt%type <node> select_no_parens select_with_parens select_clause simple_select%type <node> alter_column_default opclass_item%type <ival> add_drop%type <dbehavior> opt_drop_behavior%type <list> createdb_opt_list copy_opt_list%type <defelt> createdb_opt_item copy_opt_item%type <ival> opt_lock lock_type cast_context%type <boolean> opt_force opt_or_replace transaction_access_mode opt_grant_grant_option opt_revoke_grant_option%type <boolean> like_including_defaults%type <list> user_list%type <list> OptGroupList%type <defelt> OptGroupElem%type <list> OptUserList%type <defelt> OptUserElem%type <str> OptSchemaName%type <list> OptSchemaEltList%type <boolean> TriggerActionTime TriggerForSpec opt_trusted%type <str> opt_lancompiler%type <str> TriggerEvents%type <value> TriggerFuncArg%type <str> relation_name copy_file_name database_name access_method_clause access_method attr_name index_name name function_name file_name%type <list> func_name handler_name qual_Op qual_all_Op opt_class opt_validator%type <range> qualified_name OptConstrFromTable%type <str> all_Op MathOp opt_name SpecialRuleRelation%type <str> iso_level opt_encoding%type <node> grantee%type <list> grantee_list%type <ival> privilege%type <list> privileges privilege_list%type <privtarget> privilege_target%type <node> function_with_argtypes%type <list> function_with_argtypes_list%type <chr> TriggerOneEvent%type <list> stmtblock stmtmulti OptTableElementList TableElementList OptInherit definition opt_distinct opt_definition func_args func_args_list func_as createfunc_opt_list oper_argtypes RuleActionList RuleActionMulti opt_column_list columnList opt_name_list sort_clause opt_sort_clause sortby_list index_params name_list from_clause from_list opt_array_bounds qualified_name_list any_name any_name_list any_operator expr_list dotted_name attrs target_list update_target_list insert_column_list insert_target_list def_list opt_indirection group_clause TriggerFuncArgs select_limit opt_select_limit opclass_item_list transaction_mode_list transaction_mode_list_or_empty TableFuncElementList prep_type_clause prep_type_list execute_param_clause%type <range> into_clause OptTempTableName%type <defelt> createfunc_opt_item%type <typnam> func_arg func_return func_type aggr_argtype%type <boolean> opt_arg TriggerForType OptTemp OptWithOids%type <oncommit> OnCommitOption%type <list> for_update_clause opt_for_update_clause update_list%type <boolean> opt_all%type <node> join_outer join_qual%type <jtype> join_type%type <list> extract_list overlay_list position_list%type <list> substr_list trim_list%type <ival> opt_interval%type <node> overlay_placing substr_from substr_for%type <boolean> opt_instead opt_analyze%type <boolean> index_opt_unique opt_verbose opt_full%type <boolean> opt_freeze opt_default opt_recheck%type <defelt> opt_binary opt_oids copy_delimiter%type <boolean> copy_from opt_hold%type <ival> fetch_count opt_column event cursor_options%type <objtype> reindex_type drop_type comment_type%type <node> fetch_direction select_limit_value select_offset_value%type <list> OptSeqList%type <defelt> OptSeqElem%type <istmt> insert_rest%type <vsetstmt> set_rest%type <node> TableElement ConstraintElem TableFuncElement%type <node> columnDef%type <defelt> def_elem%type <node> def_arg columnElem where_clause insert_column_item a_expr b_expr c_expr r_expr AexprConst in_expr having_clause func_table array_expr%type <list> row row_descriptor type_list array_expr_list%type <node> case_expr case_arg when_clause case_default%type <list> when_clause_list%type <ival> sub_type%type <list> OptCreateAs CreateAsList%type <node> CreateAsElement%type <value> NumericOnly FloatOnly IntegerOnly%type <columnref> columnref%type <alias> alias_clause%type <sortby> sortby%type <ielem> index_elem%type <node> table_ref%type <jexpr> joined_table%type <range> relation_expr%type <target> target_el insert_target_el update_target_el%type <typnam> Typename SimpleTypename ConstTypename GenericType Numeric opt_float Character ConstCharacter CharacterWithLength CharacterWithoutLength ConstDatetime ConstInterval Bit ConstBit BitWithLength BitWithoutLength%type <str> character%type <str> extract_arg%type <str> opt_charset%type <ival> opt_numeric opt_decimal%type <boolean> opt_varying opt_timezone%type <ival> Iconst%type <str> Sconst comment_text%type <str> UserId opt_boolean ColId_or_Sconst%type <list> var_list var_list_or_default%type <str> ColId ColLabel type_name%type <node> var_value zone_value%type <keyword> unreserved_keyword func_name_keyword%type <keyword> col_name_keyword reserved_keyword%type <node> TableConstraint TableLikeClause%type <list> ColQualList%type <node> ColConstraint ColConstraintElem ConstraintAttr%type <ival> key_actions key_delete key_match key_update key_action%type <ival> ConstraintAttributeSpec ConstraintDeferrabilitySpec ConstraintTimeSpec%type <list> constraints_set_list%type <boolean> constraints_set_mode/* * If you make any token changes, update the keyword table in * parser/keywords.c and add new keywords to the appropriate one of * the reserved-or-not-so-reserved keyword lists, below. *//* ordinary key words in alphabetical order */%token <keyword> ABORT_P ABSOLUTE_P ACCESS ACTION ADD AFTER AGGREGATE ALL ALTER ANALYSE ANALYZE AND ANY ARRAY AS ASC ASSERTION ASSIGNMENT AT AUTHORIZATION BACKWARD BEFORE BEGIN_P BETWEEN BIGINT BINARY BIT BOOLEAN_P BOTH BY CACHE CALLED CASCADE CASE CAST CHAIN CHAR_P CHARACTER CHARACTERISTICS CHECK CHECKPOINT CLASS CLOSE CLUSTER COALESCE COLLATE COLUMN COMMENT COMMIT COMMITTED CONSTRAINT CONSTRAINTS CONVERSION_P CONVERT COPY CREATE CREATEDB CREATEUSER CROSS CURRENT_DATE CURRENT_TIME CURRENT_TIMESTAMP CURRENT_USER CURSOR CYCLE DATABASE DAY_P DEALLOCATE DEC DECIMAL_P DECLARE DEFAULT DEFAULTS DEFERRABLE DEFERRED DEFINER DELETE_P DELIMITER DELIMITERS DESC DISTINCT DO DOMAIN_P DOUBLE_P DROP EACH ELSE ENCODING ENCRYPTED END_P ESCAPE EXCEPT EXCLUDING EXCLUSIVE EXECUTE EXISTS EXPLAIN EXTERNAL EXTRACT FALSE_P FETCH FIRST_P FLOAT_P FOR FORCE FOREIGN FORWARD FREEZE FROM FULL FUNCTION GLOBAL GRANT GROUP_P HANDLER HAVING HOLD HOUR_P ILIKE IMMEDIATE IMMUTABLE IMPLICIT_P IN_P INCLUDING INCREMENT INDEX INHERITS INITIALLY INNER_P INOUT INPUT_P INSENSITIVE INSERT INSTEAD INT_P INTEGER INTERSECT INTERVAL INTO INVOKER IS ISNULL ISOLATION JOIN KEY LANCOMPILER LANGUAGE LAST_P LEADING LEFT LEVEL LIKE LIMIT LISTEN LOAD LOCAL LOCALTIME LOCALTIMESTAMP LOCATION LOCK_P MATCH MAXVALUE MINUTE_P MINVALUE MODE MONTH_P MOVE NAMES NATIONAL NATURAL NCHAR NEW NEXT NO NOCREATEDB NOCREATEUSER NONE NOT NOTHING NOTIFY NOTNULL NULL_P NULLIF NUMERIC OF OFF OFFSET OIDS OLD ON ONLY OPERATOR OPTION OR ORDER OUT_P OUTER_P OVERLAPS OVERLAY OWNER PARTIAL PASSWORD PATH_P PENDANT PLACING POSITION PRECISION PRESERVE PREPARE PRIMARY PRIOR PRIVILEGES PROCEDURAL PROCEDURE READ REAL RECHECK REFERENCES REINDEX RELATIVE_P RENAME REPLACE RESET RESTART RESTRICT RETURNS REVOKE RIGHT ROLLBACK ROW ROWS RULE SCHEMA SCROLL SECOND_P SECURITY SELECT SEQUENCE SERIALIZABLE SESSION SESSION_USER SET SETOF SHARE SHOW SIMILAR SIMPLE SMALLINT SOME STABLE START STATEMENT STATISTICS STDIN STDOUT STORAGE STRICT_P SUBSTRING SYSID TABLE TEMP TEMPLATE TEMPORARY THEN TIME TIMESTAMP TO TOAST TRAILING TRANSACTION TREAT TRIGGER TRIM TRUE_P TRUNCATE TRUSTED TYPE_P UNENCRYPTED UNION UNIQUE UNKNOWN UNLISTEN UNTIL UPDATE USAGE USER USING VACUUM VALID VALIDATOR VALUES VARCHAR VARYING VERBOSE VERSION VIEW VOLATILE WHEN WHERE WITH WITHOUT WORK WRITE YEAR_P ZONE/* The grammar thinks these are keywords, but they are not in the keywords.c * list and so can never be entered directly. The filter in parser.c * creates these tokens when required. */%token UNIONJOIN/* Special keywords, not in the query language - see the "lex" file */%token <str> IDENT FCONST SCONST BCONST XCONST Op%token <ival> ICONST PARAM/* precedence: lowest to highest */%left UNION EXCEPT%left INTERSECT%left OR%left AND%right NOT%right '='%nonassoc '<' '>'%nonassoc LIKE ILIKE SIMILAR%nonassoc ESCAPE%nonassoc OVERLAPS%nonassoc BETWEEN%nonassoc IN_P%left POSTFIXOP /* dummy for postfix Op rules */%left Op OPERATOR /* multi-character ops and user-defined operators */%nonassoc NOTNULL%nonassoc ISNULL%nonassoc IS NULL_P TRUE_P FALSE_P UNKNOWN /* sets precedence for IS NULL, etc */%left '+' '-'%left '*' '/' '%'%left '^'/* Unary Operators */%left AT ZONE /* sets precedence for AT TIME ZONE */%right UMINUS%left '[' ']'%left '(' ')'%left TYPECAST%left '.'/* * These might seem to be low-precedence, but actually they are not part * of the arithmetic hierarchy at all in their use as JOIN operators. * We make them high-precedence to support their use as function names. * They wouldn't be given a precedence at all, were it not that we need * left-associativity among the JOIN rules themselves. */%left JOIN UNIONJOIN CROSS LEFT FULL RIGHT INNER_P NATURAL%%/* * Handle comment-only lines, and ;; SELECT * FROM pg_class ;;; * psql already handles such cases, but other interfaces don't. * bjm 1999/10/05 */stmtblock: stmtmulti { parsetree = $1; } ;/* the thrashing around here is to discard "empty" statements... */stmtmulti: stmtmulti ';' stmt { if ($3 != (Node *)NULL) $$ = lappend($1, $3); else $$ = $1; } | stmt { if ($1 != (Node *)NULL) $$ = makeList1($1); else $$ = NIL; } ;stmt : AlterDatabaseSetStmt | AlterDomainStmt | AlterGroupStmt | AlterSeqStmt | AlterTableStmt | AlterUserSetStmt | AlterUserStmt | AnalyzeStmt | CheckPointStmt | ClosePortalStmt | ClusterStmt | CommentStmt | ConstraintsSetStmt | CopyStmt | CreateAsStmt | CreateAssertStmt | CreateCastStmt | CreateConversionStmt | CreateDomainStmt | CreateFunctionStmt | CreateGroupStmt | CreateOpClassStmt | CreatePLangStmt | CreateSchemaStmt | CreateSeqStmt | CreateStmt | CreateTrigStmt | CreateUserStmt | CreatedbStmt | DeallocateStmt | DeclareCursorStmt | DefineStmt | DeleteStmt | DropAssertStmt | DropCastStmt | DropGroupStmt | DropOpClassStmt | DropPLangStmt
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -