📄 gram.y
字号:
%{/*#define YYDEBUG 1*//*------------------------------------------------------------------------- * * gram.y * POSTGRES SQL YACC rules/actions * * Portions Copyright (c) 1996-2005, PostgreSQL Global Development Group * Portions Copyright (c) 1994, Regents of the University of California * * * IDENTIFICATION * $PostgreSQL: pgsql/src/backend/parser/gram.y,v 2.511.2.2 2006/01/31 22:40:12 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 "catalog/index.h"#include "catalog/namespace.h"#include "nodes/makefuncs.h"#include "parser/gramparse.h"#include "storage/lmgr.h"#include "utils/date.h"#include "utils/datetime.h"#include "utils/numeric.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 *makeColumnRef(char *relname, List *indirection);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 *makeRowNullTest(NullTestType test, RowExpr *row);static DefElem *makeDefElem(char *name, Node *arg);static A_Const *makeBoolAConst(bool state);static FuncCall *makeOverlaps(List *largs, List *rargs);static void check_qualified_name(List *names);static List *check_func_name(List *names);static List *extractArgTypes(List *parameters);static SelectStmt *findLeftmostSelect(SelectStmt *node);static void insertSelectOptions(SelectStmt *stmt, List *sortClause, Node *lockingClause, 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; ContainsOids withoids; List *list; Node *node; Value *value; ObjectType objtype; TypeName *typnam; FunctionParameter *fun_param; FunctionParameterMode fun_param_mode; FuncWithArgs *funwithargs; 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 AlterDatabaseStmt AlterDatabaseSetStmt AlterDomainStmt AlterGroupStmt AlterObjectSchemaStmt AlterOwnerStmt AlterSeqStmt AlterTableStmt AlterUserStmt AlterUserSetStmt AlterRoleStmt AlterRoleSetStmt AnalyzeStmt ClosePortalStmt ClusterStmt CommentStmt ConstraintsSetStmt CopyStmt CreateAsStmt CreateCastStmt CreateDomainStmt CreateGroupStmt CreateOpClassStmt CreatePLangStmt CreateSchemaStmt CreateSeqStmt CreateStmt CreateTableSpaceStmt CreateAssertStmt CreateTrigStmt CreateUserStmt CreateRoleStmt CreatedbStmt DeclareCursorStmt DefineStmt DeleteStmt DropGroupStmt DropOpClassStmt DropPLangStmt DropStmt DropAssertStmt DropTrigStmt DropRuleStmt DropCastStmt DropRoleStmt DropUserStmt DropdbStmt DropTableSpaceStmt ExplainStmt FetchStmt GrantStmt GrantRoleStmt IndexStmt InsertStmt ListenStmt LoadStmt LockStmt NotifyStmt ExplainableStmt PreparableStmt CreateFunctionStmt AlterFunctionStmt ReindexStmt RemoveAggrStmt RemoveFuncStmt RemoveOperStmt RenameStmt RevokeStmt RevokeRoleStmt 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 alter_using%type <ival> add_drop%type <node> alter_table_cmd alter_rel_cmd%type <list> alter_table_cmds alter_rel_cmds%type <dbehavior> opt_drop_behavior%type <list> createdb_opt_list alterdb_opt_list copy_opt_list transaction_mode_list%type <defelt> createdb_opt_item alterdb_opt_item copy_opt_item transaction_mode_item%type <ival> opt_lock lock_type cast_context%type <boolean> opt_force opt_or_replace opt_grant_grant_option opt_grant_admin_option opt_nowait%type <boolean> like_including_defaults%type <list> OptRoleList%type <defelt> OptRoleElem%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 subquery_Op opt_class opt_validator%type <range> qualified_name OptConstrFromTable%type <str> all_Op MathOp SpecialRuleRelation%type <str> iso_level opt_encoding%type <node> grantee%type <list> grantee_list%type <str> privilege%type <list> privileges privilege_list%type <privtarget> privilege_target%type <funwithargs> 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 alterfunc_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 attrs target_list update_target_list insert_column_list insert_target_list def_list indirection opt_indirection group_clause TriggerFuncArgs select_limit opt_select_limit opclass_item_list transaction_mode_list_or_empty TableFuncElementList prep_type_clause prep_type_list execute_param_clause using_clause%type <range> into_clause OptTempTableName%type <defelt> createfunc_opt_item common_func_opt_item%type <fun_param> func_arg%type <fun_param_mode> arg_class%type <typnam> func_return func_type aggr_argtype%type <boolean> TriggerForType OptTemp%type <oncommit> OnCommitOption%type <withoids> OptWithOids WithOidsAs%type <node> for_locking_clause opt_for_locking_clause%type <list> locked_rels_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> 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 a_expr b_expr c_expr func_expr AexprConst indirection_el columnref in_expr having_clause func_table array_expr%type <list> row 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 <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 insert_column_item%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 SignedIconst%type <str> Sconst comment_text%type <str> RoleId opt_granted_by opt_boolean ColId_or_Sconst%type <list> var_list var_list_or_default%type <str> ColId ColLabel var_name type_name param_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%type <str> OptTableSpace OptConsTableSpace OptTableSpaceOwner/* * 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; search * this file for "Name classification hierarchy". *//* ordinary key words in alphabetical order */%token <keyword> ABORT_P ABSOLUTE_P ACCESS ACTION ADD ADMIN AFTER AGGREGATE ALL ALSO ALTER ANALYSE ANALYZE AND ANY ARRAY AS ASC ASSERTION ASSIGNMENT ASYMMETRIC 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 CONNECTION CONSTRAINT CONSTRAINTS CONVERSION_P CONVERT COPY CREATE CREATEDB CREATEROLE CREATEUSER CROSS CSV CURRENT_DATE CURRENT_ROLE 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 DISABLE_P DISTINCT DO DOMAIN_P DOUBLE_P DROP EACH ELSE ENABLE_P 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 GRANTED GREATEST GROUP_P HANDLER HAVING HEADER HOLD HOUR_P ILIKE IMMEDIATE IMMUTABLE IMPLICIT_P IN_P INCLUDING INCREMENT INDEX INHERIT INHERITS INITIALLY INNER_P INOUT INPUT_P INSENSITIVE INSERT INSTEAD INT_P INTEGER INTERSECT INTERVAL INTO INVOKER IS ISNULL ISOLATION JOIN KEY LANCOMPILER LANGUAGE LARGE_P LAST_P LEADING LEAST LEFT LEVEL LIKE LIMIT LISTEN LOAD LOCAL LOCALTIME LOCALTIMESTAMP LOCATION LOCK_P LOGIN_P MATCH MAXVALUE MINUTE_P MINVALUE MODE MONTH_P MOVE NAMES NATIONAL NATURAL NCHAR NEW NEXT NO NOCREATEDB NOCREATEROLE NOCREATEUSER NOINHERIT NOLOGIN_P NONE NOSUPERUSER NOT NOTHING NOTIFY NOTNULL NOWAIT NULL_P NULLIF NUMERIC OBJECT_P OF OFF OFFSET OIDS OLD ON ONLY OPERATOR OPTION OR ORDER OUT_P OUTER_P OVERLAPS OVERLAY OWNER PARTIAL PASSWORD PLACING POSITION PRECISION PRESERVE PREPARE PREPARED PRIMARY PRIOR PRIVILEGES PROCEDURAL PROCEDURE QUOTE READ REAL RECHECK REFERENCES REINDEX RELATIVE_P RELEASE RENAME REPEATABLE REPLACE RESET RESTART RESTRICT RETURNS REVOKE RIGHT ROLE ROLLBACK ROW ROWS RULE SAVEPOINT 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 SUPERUSER_P SYMMETRIC SYSID SYSTEM_P TABLE TABLESPACE TEMP TEMPLATE TEMPORARY THEN TIME TIMESTAMP TO TOAST TRAILING TRANSACTION TREAT TRIGGER TRIM TRUE_P TRUNCATE TRUSTED TYPE_P UNCOMMITTED UNENCRYPTED UNION UNIQUE UNKNOWN UNLISTEN UNTIL UPDATE USER USING VACUUM VALID VALIDATOR VALUES VARCHAR VARYING VERBOSE 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 token types, not actually keywords - 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 != NULL) $$ = lappend($1, $3); else $$ = $1; } | stmt { if ($1 != NULL) $$ = list_make1($1); else $$ = NIL; } ;stmt : AlterDatabaseStmt | AlterDatabaseSetStmt | AlterDomainStmt | AlterFunctionStmt | AlterGroupStmt | AlterObjectSchemaStmt | AlterOwnerStmt | AlterSeqStmt | AlterTableStmt | AlterRoleSetStmt | AlterRoleStmt | AlterUserSetStmt | AlterUserStmt | AnalyzeStmt | CheckPointStmt | ClosePortalStmt | ClusterStmt | CommentStmt
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -