Documentation
¶
Overview ¶
PostgreSQL Database Management System (also known as Postgres, formerly known as Postgres95)
Portions Copyright (c) 2025, Supabase, Inc Portions Copyright (c) 1996-2025, PostgreSQL Global Development Group Portions Copyright (c) 1994, The Regents of the University of California
Permission to use, copy, modify, and distribute this software and its documentation for any purpose, without fee, and without a written agreement is hereby granted, provided that the above copyright notice and this paragraph and the following two paragraphs appear in all copies.
IN NO EVENT SHALL THE UNIVERSITY OF CALIFORNIA BE LIABLE TO ANY PARTY FOR DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES, INCLUDING LOST PROFITS, ARISING OUT OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF THE UNIVERSITY OF CALIFORNIA HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
THE UNIVERSITY OF CALIFORNIA SPECIFICALLY DISCLAIMS ANY WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE SOFTWARE PROVIDED HEREUNDER IS ON AN "AS IS" BASIS, AND THE UNIVERSITY OF CALIFORNIA HAS NO OBLIGATIONS TO PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.
PostgreSQL Database Management System (also known as Postgres, formerly known as Postgres95)
Portions Copyright (c) 2025, Supabase, Inc Portions Copyright (c) 1996-2025, PostgreSQL Global Development Group Portions Copyright (c) 1994, The Regents of the University of California
Permission to use, copy, modify, and distribute this software and its documentation for any purpose, without fee, and without a written agreement is hereby granted, provided that the above copyright notice and this paragraph and the following two paragraphs appear in all copies.
IN NO EVENT SHALL THE UNIVERSITY OF CALIFORNIA BE LIABLE TO ANY PARTY FOR DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES, INCLUDING LOST PROFITS, ARISING OUT OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF THE UNIVERSITY OF CALIFORNIA HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
THE UNIVERSITY OF CALIFORNIA SPECIFICALLY DISCLAIMS ANY WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE SOFTWARE PROVIDED HEREUNDER IS ON AN "AS IS" BASIS, AND THE UNIVERSITY OF CALIFORNIA HAS NO OBLIGATIONS TO PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.
PostgreSQL Database Management System (also known as Postgres, formerly known as Postgres95)
Portions Copyright (c) 2025, Supabase, Inc Portions Copyright (c) 1996-2025, PostgreSQL Global Development Group Portions Copyright (c) 1994, The Regents of the University of California
Permission to use, copy, modify, and distribute this software and its documentation for any purpose, without fee, and without a written agreement is hereby granted, provided that the above copyright notice and this paragraph and the following two paragraphs appear in all copies.
IN NO EVENT SHALL THE UNIVERSITY OF CALIFORNIA BE LIABLE TO ANY PARTY FOR DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES, INCLUDING LOST PROFITS, ARISING OUT OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF THE UNIVERSITY OF CALIFORNIA HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
THE UNIVERSITY OF CALIFORNIA SPECIFICALLY DISCLAIMS ANY WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE SOFTWARE PROVIDED HEREUNDER IS ON AN "AS IS" BASIS, AND THE UNIVERSITY OF CALIFORNIA HAS NO OBLIGATIONS TO PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.
PostgreSQL Database Management System (also known as Postgres, formerly known as Postgres95)
Portions Copyright (c) 2025, Supabase, Inc Portions Copyright (c) 1996-2025, PostgreSQL Global Development Group Portions Copyright (c) 1994, The Regents of the University of California
Permission to use, copy, modify, and distribute this software and its documentation for any purpose, without fee, and without a written agreement is hereby granted, provided that the above copyright notice and this paragraph and the following two paragraphs appear in all copies.
IN NO EVENT SHALL THE UNIVERSITY OF CALIFORNIA BE LIABLE TO ANY PARTY FOR DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES, INCLUDING LOST PROFITS, ARISING OUT OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF THE UNIVERSITY OF CALIFORNIA HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
THE UNIVERSITY OF CALIFORNIA SPECIFICALLY DISCLAIMS ANY WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE SOFTWARE PROVIDED HEREUNDER IS ON AN "AS IS" BASIS, AND THE UNIVERSITY OF CALIFORNIA HAS NO OBLIGATIONS TO PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.
Index ¶
- Constants
- Variables
- func AssertLexerContextError(t *testing.T, lexer *Lexer, expectedErrorType LexerErrorType)
- func AssertLexerHasErrors(t *testing.T, lexer *Lexer)
- func AssertNoLexerErrors(t *testing.T, lexer *Lexer)
- func AssertParseSQL(t *testing.T, sql string, expectedStmtCount int) []ast.Stmt
- func AssertRoundTripSQL(t *testing.T, sql string, expectedSQL string)
- func AssertTokenPosition(t *testing.T, token *Token, expectedPosition int)
- func AssertTokenSequence(t *testing.T, input string, expectedTypes []TokenType)
- func AssertTokenTypes(t *testing.T, tokens []Token, expectedTypes []TokenType)
- func AssertTokenTypesAndValues(t *testing.T, tokens []Token, expected []struct{ ... })
- func AssertTokenValues(t *testing.T, tokens []Token, expectedValues []string)
- func CalculateLineColumn(input []byte, pos int) (line, column int)
- func CalculateUnicodePosition(input []byte, bytePos int) int
- func GetKeywordNames() []string
- func HasCharClass(b byte, class CharClass) bool
- func IsAlpha(b byte) bool
- func IsAlphaNumeric(b byte) bool
- func IsBinaryDigit(b byte) bool
- func IsDigit(b byte) bool
- func IsHexDigit(b byte) bool
- func IsHighBit(b byte) bool
- func IsIdentCont(b byte) bool
- func IsIdentStart(b byte) bool
- func IsKeyword(name string) bool
- func IsOctalDigit(b byte) bool
- func IsOpChar(b byte) bool
- func IsReservedKeyword(name string) bool
- func IsSelfChar(b byte) bool
- func IsWhitespace(b byte) bool
- func ParseSQL(input string) ([]ast.Stmt, error)
- func ParseSQLWithStandardConformingStrings(input string, standardConformingStrings bool) ([]ast.Stmt, error)
- func SanitizeNearText(text string, maxLen int) string
- func SplitColQualList(qualList *ast.NodeList) (*ast.NodeList, *ast.CollateClause)
- type BackslashQuoteMode
- type CharClass
- type ErrorRecovery
- type ErrorSeverity
- type ImportQual
- type KeywordCategory
- type KeywordInfo
- type Lexer
- func (l *Lexer) Error(s string)
- func (l *Lexer) ErrorWithHint(msg, hint string)
- func (l *Lexer) ErrorWithHintState(msg, hint, sqlState string)
- func (l *Lexer) FirstError() *ParseSyntaxError
- func (l *Lexer) GetContext() *ParseContext
- func (l *Lexer) GetErrors() []error
- func (l *Lexer) GetParseTree() []ast.Stmt
- func (l *Lexer) GetPosition() int
- func (l *Lexer) HasErrors() bool
- func (l *Lexer) Lex(lval *yySymType) int
- func (l *Lexer) NextToken() *Token
- func (l *Lexer) RecordError(err error)
- func (l *Lexer) SetParseTree(tree []ast.Stmt)
- func (l *Lexer) String() string
- type LexerError
- type LexerErrorType
- type LexerInterface
- type LexerState
- type ParseContext
- func (ctx *ParseContext) AddError(message string, location int) *ParseError
- func (ctx *ParseContext) AddErrorWithType(errorType LexerErrorType, message string) *ParseError
- func (ctx *ParseContext) AddLexerErrorAt(message, hint string, location int) *ParseError
- func (ctx *ParseContext) AddLexerErrorAtDetailState(message, detail, hint, sqlState string, location int) *ParseError
- func (ctx *ParseContext) AddLexerErrorAtState(message, hint, sqlState string, location int) *ParseError
- func (ctx *ParseContext) AddLexerErrorNear(errorType LexerErrorType, message, lexeme string, location int) *ParseError
- func (ctx *ParseContext) AddLiteral(text string)
- func (ctx *ParseContext) AddLiteralByte(b byte)
- func (ctx *ParseContext) AddSyntaxError(message string) *ParseError
- func (ctx *ParseContext) AddSyntaxErrorHint(message, hint string) *ParseError
- func (ctx *ParseContext) AddSyntaxErrorHintState(message, hint, sqlState string) *ParseError
- func (ctx *ParseContext) AddWarning(message string, location int) *ParseError
- func (ctx *ParseContext) AdvanceBy(n int)
- func (ctx *ParseContext) AdvanceRune() rune
- func (ctx *ParseContext) AtEOF() bool
- func (ctx *ParseContext) ClearErrors()
- func (ctx *ParseContext) Clone() *ParseContext
- func (ctx *ParseContext) ColumnNumber() int
- func (ctx *ParseContext) CurrentByte() (byte, bool)
- func (ctx *ParseContext) CurrentChar() rune
- func (ctx *ParseContext) CurrentPosition() int
- func (ctx *ParseContext) CurrentRune() (rune, int)
- func (ctx *ParseContext) DecrementDepth()
- func (ctx *ParseContext) DolQStart() string
- func (ctx *ParseContext) Errors() []ParseError
- func (ctx *ParseContext) GetContextID() string
- func (ctx *ParseContext) GetCurrentPos() int
- func (ctx *ParseContext) GetCurrentPosition() (pos int, line int, col int)
- func (ctx *ParseContext) GetCurrentText(startPos int) string
- func (ctx *ParseContext) GetDepth() int
- func (ctx *ParseContext) GetErrors() []ParseError
- func (ctx *ParseContext) GetLiteral() string
- func (ctx *ParseContext) GetOptions() *ParseOptions
- func (ctx *ParseContext) GetParseTree() ast.Node
- func (ctx *ParseContext) GetScanBuf() []byte
- func (ctx *ParseContext) GetScanBufLen() int
- func (ctx *ParseContext) GetScanPos() int
- func (ctx *ParseContext) GetSourceText() string
- func (ctx *ParseContext) GetState() LexerState
- func (ctx *ParseContext) GetState2() LexerState
- func (ctx *ParseContext) GetStatementBoundaries() (int, int)
- func (ctx *ParseContext) GetWarnings() []ParseError
- func (ctx *ParseContext) HasErrors() bool
- func (ctx *ParseContext) HasPrefixAtScanPos(needle string) bool
- func (ctx *ParseContext) HasWarnings() bool
- func (ctx *ParseContext) InMultiDotSequence() bool
- func (ctx *ParseContext) IncrementDepth() error
- func (ctx *ParseContext) LineNumber() int
- func (ctx *ParseContext) LiteralActive() bool
- func (ctx *ParseContext) NextByte() (byte, bool)
- func (ctx *ParseContext) PeekBytes(n int) []byte
- func (ctx *ParseContext) PeekChar() rune
- func (ctx *ParseContext) PeekRune() rune
- func (ctx *ParseContext) PeekToEnd() []byte
- func (ctx *ParseContext) PutBack(n int)
- func (ctx *ParseContext) RestoreSavedPosition()
- func (ctx *ParseContext) SaveCurrentPosition() int
- func (ctx *ParseContext) ScanBuf() []byte
- func (ctx *ParseContext) ScanBufLen() int
- func (ctx *ParseContext) ScanPos() int
- func (ctx *ParseContext) SetColumnNumber(col int)
- func (ctx *ParseContext) SetColumnNumber2(col int)
- func (ctx *ParseContext) SetCurrentPosition(pos int, line int, col int)
- func (ctx *ParseContext) SetCurrentPosition2(pos int)
- func (ctx *ParseContext) SetDolQStart(value string)
- func (ctx *ParseContext) SetInMultiDotSequence(value bool)
- func (ctx *ParseContext) SetLastToken(token *Token)
- func (ctx *ParseContext) SetLineNumber(line int)
- func (ctx *ParseContext) SetLineNumber2(line int)
- func (ctx *ParseContext) SetParseTree(tree ast.Node)
- func (ctx *ParseContext) SetScanPos(pos int)
- func (ctx *ParseContext) SetSourceText(sourceText string)
- func (ctx *ParseContext) SetState(state LexerState)
- func (ctx *ParseContext) SetStatementBoundaries(start int, end int)
- func (ctx *ParseContext) SetUTF16FirstPart(value int32)
- func (ctx *ParseContext) SetXCDepth(depth int)
- func (ctx *ParseContext) StandardConformingStrings() bool
- func (ctx *ParseContext) StartLiteral()
- func (ctx *ParseContext) State() LexerState
- func (ctx *ParseContext) String() string
- func (ctx *ParseContext) UTF16FirstPart() int32
- func (ctx *ParseContext) XCDepth() int
- type ParseError
- type ParseOptions
- type ParseSyntaxError
- type PrivTarget
- type Token
- func NewIntToken(value int, position int, text string) *Token
- func NewKeywordToken(tokenType int, keyword string, position int, text string) *Token
- func NewParamToken(paramNum int, position int, text string) *Token
- func NewStringToken(tokenType int, value string, position int, text string) *Token
- func NewToken(tokenType int, position int, text string) *Token
- func ScanAllTokens(t *testing.T, lexer *Lexer) []Token
- type TokenType
- type TokenValue
Constants ¶
const ( SQLStateFeatureNotSupported = "0A000" SQLStateInvalidEscapeSequence = "22025" )
SQLStateInvalidEscapeSequence is PostgreSQL's ERRCODE_INVALID_ESCAPE_SEQUENCE (22025). The parser deliberately does not depend on the mterrors package, so the few SQLSTATEs it must name are spelled out here; the serving layer maps ParseSyntaxError.SQLState onto its own diagnostic type.
const ( UnreservedKeyword = ast.UnreservedKeyword ColNameKeyword = ast.ColNameKeyword TypeFuncNameKeyword = ast.TypeFuncNameKeyword ReservedKeyword = ast.ReservedKeyword )
const ( IDENT = 57346 UIDENT = 57347 FCONST = 57348 SCONST = 57349 USCONST = 57350 BCONST = 57351 XCONST = 57352 Op = 57353 ICONST = 57354 PARAM = 57355 TYPECAST = 57356 DOT_DOT = 57357 COLON_EQUALS = 57358 EQUALS_GREATER = 57359 LESS_EQUALS = 57360 GREATER_EQUALS = 57361 NOT_EQUALS = 57362 ALL = 57363 ALTER = 57364 AS = 57365 CASCADE = 57366 CONCURRENTLY = 57367 CREATE = 57368 DROP = 57369 IF_P = 57370 EXISTS = 57371 AND = 57372 NOT = 57373 NULLS_P = 57374 OR = 57375 REPLACE = 57376 RESTRICT = 57377 WITH = 57378 MIGRATION = 57379 EXPORT = 57380 PHASE = 57381 BETWEEN = 57382 CASE = 57383 COLLATE = 57384 DEFAULT = 57385 DISTINCT = 57386 ESCAPE = 57387 FALSE_P = 57388 ILIKE = 57389 IN_P = 57390 LIKE = 57391 NULL_P = 57392 SIMILAR = 57393 TRUE_P = 57394 UNKNOWN = 57395 WHEN = 57396 IS = 57397 ISNULL = 57398 NOTNULL = 57399 AT = 57400 TIME = 57401 ZONE = 57402 LOCAL = 57403 SYMMETRIC = 57404 ASYMMETRIC = 57405 TO = 57406 OPERATOR = 57407 SELECT = 57408 FROM = 57409 WHERE = 57410 ONLY = 57411 TABLE = 57412 LIMIT = 57413 OFFSET = 57414 BY = 57415 GROUP_P = 57416 HAVING = 57417 INTO = 57418 ON = 57419 JOIN = 57420 INNER_P = 57421 LEFT = 57422 RIGHT = 57423 FULL = 57424 OUTER_P = 57425 CROSS = 57426 NATURAL = 57427 USING = 57428 RECURSIVE = 57429 MATERIALIZED = 57430 VALUES = 57431 SEARCH = 57432 BREADTH = 57433 DEPTH = 57434 CYCLE = 57435 FIRST_P = 57436 LAST_P = 57437 SET = 57438 ASC = 57439 DESC = 57440 INSERT = 57441 UPDATE = 57442 DELETE_P = 57443 MERGE = 57444 RETURNING = 57445 CONFLICT = 57446 OVERRIDING = 57447 USER = 57448 SYSTEM_P = 57449 MATCHED = 57450 THEN = 57451 SOURCE = 57452 TARGET = 57453 DO = 57454 NOTHING = 57455 COPY = 57456 PROGRAM = 57457 STDIN = 57458 STDOUT = 57459 BINARY = 57460 FREEZE = 57461 CONSTRAINT = 57462 VERBOSE = 57463 ANALYZE = 57464 CURRENT_P = 57465 CURSOR = 57466 OF = 57467 COLUMNS = 57468 ORDINALITY = 57469 XMLTABLE = 57470 JSON_TABLE = 57471 ROWS = 57472 PATH = 57473 PASSING = 57474 FOR = 57475 NESTED = 57476 REF_P = 57477 XMLNAMESPACES = 57478 ARRAY = 57479 ERROR = 57480 ERROR_P = 57481 EMPTY = 57482 EMPTY_P = 57483 OBJECT_P = 57484 WRAPPER = 57485 CONDITIONAL = 57486 UNCONDITIONAL = 57487 QUOTES = 57488 OMIT = 57489 KEEP = 57490 SCALAR = 57491 STRING_P = 57492 ENCODING = 57493 DELIMITER = 57494 DELIMITERS = 57495 HEADER_P = 57496 QUOTE = 57497 FORCE = 57498 CSV = 57499 VALUE_P = 57500 JSON_QUERY = 57501 JSON_VALUE = 57502 JSON_SERIALIZE = 57503 JSON_OBJECT = 57504 JSON_ARRAY = 57505 JSON_OBJECTAGG = 57506 JSON_ARRAYAGG = 57507 JSON_EXISTS = 57508 JSON_SCALAR = 57509 FORMAT = 57510 JSON = 57511 UTF8 = 57512 WITHOUT = 57513 BIT = 57514 NUMERIC = 57515 INTEGER = 57516 SMALLINT = 57517 BIGINT = 57518 REAL = 57519 FLOAT_P = 57520 DOUBLE_P = 57521 PRECISION = 57522 CHARACTER = 57523 CHAR_P = 57524 VARCHAR = 57525 NATIONAL = 57526 NCHAR = 57527 VARYING = 57528 TIMESTAMP = 57529 INTERVAL = 57530 INT_P = 57531 DECIMAL_P = 57532 DEC = 57533 BOOLEAN_P = 57534 VARIADIC = 57535 ABORT_P = 57536 ABSENT = 57537 ABSOLUTE_P = 57538 ACCESS = 57539 ACTION = 57540 ADD_P = 57541 ADMIN = 57542 AFTER = 57543 AGGREGATE = 57544 ALSO = 57545 ALWAYS = 57546 ASSERTION = 57547 ANALYSE = 57548 ASENSITIVE = 57549 ASSIGNMENT = 57550 ATOMIC = 57551 ATTACH = 57552 ATTRIBUTE = 57553 AUTHORIZATION = 57554 BACKWARD = 57555 BEFORE = 57556 BEGIN_P = 57557 CACHE = 57558 CALL = 57559 CALLED = 57560 CASCADED = 57561 CATALOG_P = 57562 CHAIN = 57563 CHARACTERISTICS = 57564 CHECKPOINT = 57565 CLASS = 57566 CLOSE = 57567 CLUSTER = 57568 COALESCE = 57569 COLLATION = 57570 COMMENT = 57571 COMMENTS = 57572 COMMIT = 57573 COMMITTED = 57574 COMPRESSION = 57575 CONFIGURATION = 57576 CONNECTION = 57577 CONSTRAINTS = 57578 CONTENT_P = 57579 CONTINUE_P = 57580 CONVERSION_P = 57581 COST = 57582 CUBE = 57583 CURRENT_CATALOG = 57584 CURRENT_DATE = 57585 CURRENT_ROLE = 57586 CURRENT_SCHEMA = 57587 CURRENT_TIME = 57588 CURRENT_TIMESTAMP = 57589 CURRENT_USER = 57590 DATA_P = 57591 DATABASE = 57592 DAY_P = 57593 DEALLOCATE = 57594 DECLARE = 57595 DEFAULTS = 57596 DEFERRABLE = 57597 DEFERRED = 57598 DEFINER = 57599 DEPENDS = 57600 DETACH = 57601 DICTIONARY = 57602 DISABLE_P = 57603 DISCARD = 57604 DOCUMENT_P = 57605 DOMAIN_P = 57606 EACH = 57607 ELSE = 57608 ENABLE_P = 57609 ENCRYPTED = 57610 END_P = 57611 ENUM_P = 57612 EVENT = 57613 EXCEPT = 57614 EXCLUDE = 57615 EXCLUDING = 57616 EXCLUSIVE = 57617 EXECUTE = 57618 EXPLAIN = 57619 EXPRESSION = 57620 EXTENSION = 57621 EXTERNAL = 57622 EXTRACT = 57623 FAMILY = 57624 FETCH = 57625 FILTER = 57626 FINALIZE = 57627 FOLLOWING = 57628 FOREIGN = 57629 FORWARD = 57630 FUNCTION = 57631 FUNCTIONS = 57632 GENERATED = 57633 GLOBAL = 57634 GRANT = 57635 GRANTED = 57636 GREATEST = 57637 GROUPING = 57638 GROUPS = 57639 HANDLER = 57640 HOLD = 57641 HOUR_P = 57642 IDENTITY_P = 57643 IMMEDIATE = 57644 IMMUTABLE = 57645 IMPLICIT_P = 57646 IMPORT_P = 57647 INCLUDE = 57648 INCLUDING = 57649 INCREMENT = 57650 INDENT = 57651 INDEX = 57652 INDEXES = 57653 INHERIT = 57654 INHERITS = 57655 INITIALLY = 57656 INLINE_P = 57657 INPUT_P = 57658 INSENSITIVE = 57659 INSTEAD = 57660 INTERSECT = 57661 INVOKER = 57662 ISOLATION = 57663 KEYS = 57664 LABEL = 57665 LANGUAGE = 57666 LARGE_P = 57667 LATERAL_P = 57668 LEAKPROOF = 57669 LEAST = 57670 LEADING = 57671 LEVEL = 57672 LISTEN = 57673 LOAD = 57674 LOCALTIME = 57675 LOCALTIMESTAMP = 57676 LOCATION = 57677 LOCK_P = 57678 LOCKED = 57679 LOGGED = 57680 MAPPING = 57681 MATCH = 57682 MAXVALUE = 57683 MERGE_ACTION = 57684 METHOD = 57685 MINUTE_P = 57686 MINVALUE = 57687 MODE = 57688 MONTH_P = 57689 MOVE = 57690 NAME_P = 57691 NAMES = 57692 NEW = 57693 NEXT = 57694 NFC = 57695 NFD = 57696 NFKC = 57697 NFKD = 57698 NO = 57699 NONE = 57700 NORMALIZE = 57701 NORMALIZED = 57702 NOTIFY = 57703 NOWAIT = 57704 NULLIF = 57705 OUT_P = 57706 OVERLAY = 57707 OVERLAPS = 57708 OWNED = 57709 OWNER = 57710 PARALLEL = 57711 PARAMETER = 57712 PARSER = 57713 PARTIAL = 57714 PARTITION = 57715 PASSWORD = 57716 PLACING = 57717 PLAN = 57718 PLANS = 57719 POLICY = 57720 POSITION = 57721 PRECEDING = 57722 PREPARE = 57723 PREPARED = 57724 PRESERVE = 57725 PRIMARY = 57726 PRIOR = 57727 PRIVILEGES = 57728 PROCEDURAL = 57729 PROCEDURE = 57730 PROCEDURES = 57731 PUBLICATION = 57732 RANGE = 57733 READ = 57734 REASSIGN = 57735 RECHECK = 57736 REFERENCES = 57737 REFERENCING = 57738 REFRESH = 57739 REINDEX = 57740 RELATIVE_P = 57741 RELEASE = 57742 RENAME = 57743 REPEATABLE = 57744 REPLICA = 57745 RESET = 57746 RESTART = 57747 RETURN = 57748 RETURNS = 57749 REVOKE = 57750 ROLE = 57751 ROLLBACK = 57752 ROLLUP = 57753 ROUTINE = 57754 ROUTINES = 57755 ROW = 57756 RULE = 57757 SAVEPOINT = 57758 SCHEMA = 57759 SCHEMAS = 57760 SCROLL = 57761 SECOND_P = 57762 SECURITY = 57763 SEQUENCE = 57764 SEQUENCES = 57765 SERIALIZABLE = 57766 SERVER = 57767 SESSION = 57768 SESSION_USER = 57769 SETS = 57770 SETOF = 57771 SHARE = 57772 SHOW = 57773 SIMPLE = 57774 SKIP = 57775 SNAPSHOT = 57776 SOME = 57777 SQL_P = 57778 STABLE = 57779 STANDALONE_P = 57780 START = 57781 STATEMENT = 57782 STATISTICS = 57783 STORAGE = 57784 STORED = 57785 STRICT_P = 57786 STRIP_P = 57787 SUBSCRIPTION = 57788 SUBSTRING = 57789 SUPPORT = 57790 SYSID = 57791 SYSTEM_USER = 57792 TABLES = 57793 TABLESPACE = 57794 TABLESAMPLE = 57795 TEMP = 57796 TEMPLATE = 57797 TEMPORARY = 57798 TEXT_P = 57799 TIES = 57800 TRAILING = 57801 TRANSACTION = 57802 TRANSFORM = 57803 TREAT = 57804 TRIGGER = 57805 TRIM = 57806 TRUNCATE = 57807 TRUSTED = 57808 TYPE_P = 57809 TYPES_P = 57810 UESCAPE = 57811 UNBOUNDED = 57812 UNCOMMITTED = 57813 UNENCRYPTED = 57814 UNION = 57815 UNIQUE = 57816 UNLISTEN = 57817 UNLOGGED = 57818 UNTIL = 57819 VACUUM = 57820 VALID = 57821 VALIDATE = 57822 VALIDATOR = 57823 VERSION_P = 57824 VIEW = 57825 VIEWS = 57826 VOLATILE = 57827 WHITESPACE_P = 57828 WINDOW = 57829 WITHIN = 57830 WORK = 57831 WRITE = 57832 XML_P = 57833 XMLATTRIBUTES = 57834 XMLCONCAT = 57835 XMLELEMENT = 57836 XMLEXISTS = 57837 XMLFOREST = 57838 XMLPARSE = 57839 XMLPI = 57840 XMLROOT = 57841 XMLSERIALIZE = 57842 YEAR_P = 57843 YES_P = 57844 INOUT = 57845 OTHERS = 57846 OLD = 57847 KEY = 57848 OFF = 57849 OIDS = 57850 OPTION = 57851 OPTIONS = 57852 OVER = 57853 ORDER = 57854 ANY = 57855 BOTH = 57856 CAST = 57857 CHECK = 57858 COLUMN = 57859 RESHARD = 57860 SHARDS = 57861 TABLEGROUP = 57862 FORMAT_LA = 57863 NOT_LA = 57864 NULLS_LA = 57865 WITH_LA = 57866 WITHOUT_LA = 57867 MODE_TYPE_NAME = 57868 MODE_PLPGSQL_EXPR = 57869 MODE_PLPGSQL_ASSIGN1 = 57870 MODE_PLPGSQL_ASSIGN2 = 57871 MODE_PLPGSQL_ASSIGN3 = 57872 UMINUS = 57873 )
const ( // Special tokens - internal to lexer only INVALID = -1 // Invalid token EOF = 0 // End of file (aligns with yacc EOF expectation) )
Special token constants not generated by the parser These are used for lexer-internal operations
const NAMEDATALEN = 64
NAMEDATALEN is the maximum length of names in PostgreSQL postgres/src/include/pg_config_manual.h:32
Variables ¶
var Keywords = []KeywordInfo{}/* 497 elements not displayed */
Keywords maps each PostgreSQL keyword to its goyacc token. Category and CanBareLabel are filled in by init from the ast classification.
Functions ¶
func AssertLexerContextError ¶
func AssertLexerContextError(t *testing.T, lexer *Lexer, expectedErrorType LexerErrorType)
AssertLexerContextError verifies specific error types in lexer context
func AssertLexerHasErrors ¶
AssertLexerHasErrors verifies that the lexer has errors
func AssertNoLexerErrors ¶
AssertNoLexerErrors verifies that the lexer has no errors
func AssertParseSQL ¶
AssertParseSQL tests that SQL parses without error and returns expected number of statements
func AssertRoundTripSQL ¶
AssertRoundTripSQL tests that SQL can be parsed and deparsed consistently
func AssertTokenPosition ¶
AssertTokenPosition verifies token position information
func AssertTokenSequence ¶
AssertTokenSequence tests that an input produces the expected sequence of token types
func AssertTokenTypes ¶
AssertTokenTypes verifies that tokens match expected types
func AssertTokenTypesAndValues ¶
func AssertTokenTypesAndValues(t *testing.T, tokens []Token, expected []struct { Type TokenType Value string }, )
AssertTokenTypesAndValues verifies both types and values
func AssertTokenValues ¶
AssertTokenValues verifies that tokens match expected string values
func CalculateLineColumn ¶
CalculateLineColumn calculates line and column numbers for a byte position Uses 1-based indexing like PostgreSQL
func CalculateUnicodePosition ¶
CalculateUnicodePosition converts byte position to Unicode character position Equivalent to PostgreSQL's pg_mbstrlen_with_len function postgres/src/backend/utils/mb/mbutils.c:1200
func GetKeywordNames ¶
func GetKeywordNames() []string
GetKeywordNames returns a sorted slice of all keyword names.
func HasCharClass ¶
HasCharClass checks if a byte has any of the specified character class flags
func IsAlphaNumeric ¶
IsAlphaNumeric checks if a byte is alphanumeric (for backward compatibility)
func IsBinaryDigit ¶
IsBinaryDigit checks if a byte is a binary digit (0-1)
func IsHexDigit ¶
IsHexDigit checks if a byte is a hexadecimal digit (0-9, a-f, A-F)
func IsIdentCont ¶
IsIdentCont checks if a byte can continue an identifier Equivalent to PostgreSQL's ident_cont: [A-Za-z\200-\377_0-9\$] - postgres/src/backend/parser/scan.l:347
func IsIdentStart ¶
IsIdentStart checks if a byte can start an identifier Equivalent to PostgreSQL's ident_start: [A-Za-z\200-\377_] - postgres/src/backend/parser/scan.l:346
func IsOctalDigit ¶
IsOctalDigit checks if a byte is an octal digit (0-7)
func IsOpChar ¶
IsOpChar checks if a byte can be part of a PostgreSQL operator Equivalent to PostgreSQL's op_chars: [\~\!\@\#\^\&\|\`\?\+\-\*\/\%\<\>\=] - postgres/src/backend/parser/scan.l:381
func IsReservedKeyword ¶
IsReservedKeyword returns true if the given name is a reserved keyword.
func IsSelfChar ¶
IsSelfChar checks if a byte is a PostgreSQL "self" character (single-char token) Equivalent to PostgreSQL's self: [,()\[\].;\:\+\-\*\/\%\^\<\>\=] - postgres/src/backend/parser/scan.l:380
func IsWhitespace ¶
IsWhitespace checks if a byte is whitespace Equivalent to PostgreSQL's space: [ \t\n\r\f\v] - postgres/src/backend/parser/scan.l:222
func ParseSQL ¶
ParseSQL parses SQL input and returns the AST, using the default parse options (standard_conforming_strings on, matching a fresh PostgreSQL session).
func ParseSQLWithStandardConformingStrings ¶
func ParseSQLWithStandardConformingStrings(input string, standardConformingStrings bool) ([]ast.Stmt, error)
ParseSQLWithStandardConformingStrings parses SQL with an explicit standard_conforming_strings setting. Callers that track the session GUC (e.g. the multigateway) must lex string literals the way the client's session would: with scs=false, an ordinary '...' literal processes backslash escapes, so parsing with the default scs=true would mis-lex the query. Behaves like ParseSQL in every other respect.
func SanitizeNearText ¶
SanitizeNearText sanitizes text for display in error messages Removes/replaces control characters and limits length
func SplitColQualList ¶
SplitColQualList separates a ColQualList (column qualifier list) into constraints and collate clauses. This mirrors PostgreSQL's SplitColQualList function which is used to process column qualifiers and domain qualifiers by separating them into appropriate lists.
PostgreSQL reference: src/backend/parser/gram.tab.c:SplitColQualList
Parameters:
- qualList: A NodeList containing Constraint and CollateClause nodes
Returns:
- constraints: A NodeList of Constraint nodes
- collClause: A single CollateClause (PostgreSQL allows only one COLLATE per column/domain)
Types ¶
type BackslashQuoteMode ¶
type BackslashQuoteMode int
BackslashQuoteMode represents the backslash_quote GUC setting Ported from postgres/src/backend/parser/scan.l:68 and postgres/src/include/utils/guc.h
const ( BackslashQuoteOff BackslashQuoteMode = 0 // postgres/src/include/utils/guc.h (BACKSLASH_QUOTE_OFF) BackslashQuoteOn BackslashQuoteMode = 1 // postgres/src/include/utils/guc.h (BACKSLASH_QUOTE_ON) BackslashQuoteSafeEncoding BackslashQuoteMode = 2 // postgres/src/include/utils/guc.h (BACKSLASH_QUOTE_SAFE_ENCODING) )
type CharClass ¶
type CharClass uint16
CharClass represents character classification flags using bit fields
const ( // Character class flags - can be combined with bitwise OR ClassDigit CharClass = 1 << iota // 0-9 ClassAlpha // a-z, A-Z ClassIdentStart // Characters that can start identifiers ClassIdentCont // Characters that can continue identifiers ClassWhitespace // Whitespace characters ClassHexDigit // 0-9, a-f, A-F ClassOctalDigit // 0-7 ClassBinaryDigit // 0-1 ClassSelfChar // PostgreSQL "self" characters (single-char tokens) ClassOpChar // Characters that can be part of operators ClassHighBit // Characters with high bit set (>= 0x80) )
func GetCharClass ¶
GetCharClass returns the character class flags for a byte This can be used for more complex character classification logic
type ErrorRecovery ¶
type ErrorRecovery struct {
CanContinue bool // Whether lexer can continue after this error
RecoveryHint string // Suggestion for fixing the error
SuggestedFix string // Possible correction
RecoveryAction string // What the lexer will do to recover
}
ErrorRecovery provides context-aware error recovery strategies
type ErrorSeverity ¶
type ErrorSeverity int
ErrorSeverity represents different levels of parsing errors Ported from postgres error severity concepts
const ( ErrorSeverityNotice ErrorSeverity = iota ErrorSeverityWarning ErrorSeverityError ErrorSeverityFatal ErrorSeverityPanic )
func (ErrorSeverity) String ¶
func (es ErrorSeverity) String() string
String returns the string representation of error severity
type ImportQual ¶
type ImportQual struct {
// contains filtered or unexported fields
}
ImportQual - Private struct for the result of import_qualification production Matches PostgreSQL's ImportQual from gram.y
type KeywordCategory ¶
type KeywordCategory = ast.KeywordCategory
KeywordCategory and its values are re-exported from the ast package (the single source of keyword classification) so existing parser-package callers keep working.
type KeywordInfo ¶
type KeywordInfo struct {
Name string // Keyword name (lowercase)
TokenType int // Token type from parser constants
Category KeywordCategory // Keyword category (filled from ast at init)
CanBareLabel bool // Can be used as a bare label (filled from ast at init)
}
KeywordInfo represents information about a SQL keyword. The Name/TokenType pair is defined in this package (the lexer needs the token); Category and CanBareLabel are populated from the ast classification at init.
func GetKeywordsByCategory ¶
func GetKeywordsByCategory(category KeywordCategory) []KeywordInfo
GetKeywordsByCategory returns all keywords in a specific category.
func LookupKeyword ¶
func LookupKeyword(name string) *KeywordInfo
LookupKeyword searches for a keyword by name (case-insensitive) with optimizations. Returns the keyword info if found, nil otherwise. Based on postgres/src/common/kwlookup.c:ScanKeywordLookup lines 37-85
type Lexer ¶
type Lexer struct {
// contains filtered or unexported fields
}
Lexer represents the main lexer instance Equivalent to PostgreSQL's scanner state management
func NewLexer ¶
NewLexer creates a new PostgreSQL-compatible lexer instance Equivalent to postgres/src/backend/parser/scan.l:1404 (scanner_init function)
func NewLexerWithOptions ¶
func NewLexerWithOptions(input string, options *ParseOptions) *Lexer
NewLexerWithOptions creates a lexer with explicit parse options (e.g. a non-default standard_conforming_strings), instead of the defaults NewLexer applies.
func (*Lexer) Error ¶
Error implements the error interface for goyacc. It shapes the message and position to match PostgreSQL's scanner_yyerror ("syntax error at or near \"<token>\"" / "at end of input", with the position pointing at the offending token).
func (*Lexer) ErrorWithHint ¶
ErrorWithHint records a parser error like Error, additionally attaching a PostgreSQL HINT to the diagnostic. Used by grammar actions that mirror PostgreSQL ereport(errmsg(...), errhint(...)) pairs.
func (*Lexer) ErrorWithHintState ¶
ErrorWithHintState records a grammar error with structured diagnostic fields.
func (*Lexer) FirstError ¶
func (l *Lexer) FirstError() *ParseSyntaxError
FirstError returns the first recorded error as a *ParseSyntaxError, or nil when there are none. It preserves the position information GetErrors discards.
func (*Lexer) GetContext ¶
func (l *Lexer) GetContext() *ParseContext
GetContext returns the lexer context (for testing and debugging)
func (*Lexer) GetErrors ¶
GetErrors returns all errors encountered.
These are plain parser errors carrying no SQLSTATE: go/common/parser is a standalone library and must not depend on the mterrors vocabulary (enforced by the parser-isolation lint rule). Callers that serve PostgreSQL clients map a parse failure to a 42601 syntax_error diagnostic via mterrors.NewParseError at the point they invoke the parser.
func (*Lexer) GetParseTree ¶
GetParseTree returns the parse tree result
func (*Lexer) GetPosition ¶
GetPosition returns the current position in the input
func (*Lexer) NextToken ¶
NextToken returns the next token from the input stream This is the main lexer interface, equivalent to PostgreSQL's base_yylex Implements the same token filtering logic as PostgreSQL's base_yylex function Equivalent to postgres/src/backend/parser/parser.c:110-324 (base_yylex function)
func (*Lexer) RecordError ¶
RecordError records a parsing error
func (*Lexer) SetParseTree ¶
SetParseTree sets the parse tree result
type LexerError ¶
type LexerError struct {
Type LexerErrorType // Error category (UnterminatedString, InvalidNumber, etc.)
Message string // Primary error message
Position int // Byte offset where error occurred
Line int // Line number where error occurred (1-based)
Column int // Column number where error occurred (1-based)
NearText string // Text near the error for context
AtEOF bool // True if error occurred at end of file
Context string // Additional context (e.g., "in string literal")
Hint string // Recovery suggestion
ErrorLength int // Length of the problematic text
}
LexerError represents a comprehensive lexical analysis error This combines all error information for PostgreSQL compatibility
func (*LexerError) DetailedError ¶
func (e *LexerError) DetailedError() string
DetailedError returns a detailed error message with context and hints
func (*LexerError) Error ¶
func (e *LexerError) Error() string
Error implements the error interface with PostgreSQL-compatible formatting Based on postgres/src/backend/parser/scan.l:1230 (scanner_yyerror)
func (*LexerError) GetRecoveryStrategy ¶
func (e *LexerError) GetRecoveryStrategy() ErrorRecovery
GetRecoveryStrategy returns appropriate recovery strategy for error type Based on PostgreSQL's error handling patterns and modern IDE practices
func (*LexerError) PostgreSQLErrorMessage ¶
func (e *LexerError) PostgreSQLErrorMessage() string
PostgreSQLErrorMessage formats error message exactly like PostgreSQL Based on PostgreSQL's ereport format patterns
type LexerErrorType ¶
type LexerErrorType int
LexerErrorType represents different categories of lexer errors Based on PostgreSQL error patterns in scan.l
const ( SyntaxError LexerErrorType = iota UnterminatedString // postgres/src/backend/parser/scan.l:756 ("unterminated quoted string") UnterminatedComment // postgres/src/backend/parser/scan.l:497 ("unterminated /* comment") UnterminatedBitString // postgres/src/backend/parser/scan.l:517 ("unterminated bit string literal") UnterminatedHexString // postgres/src/backend/parser/scan.l:531 ("unterminated hexadecimal string literal") UnterminatedDollarQuote // postgres/src/backend/parser/scan.l (unterminated dollar-quoted string) UnterminatedIdentifier // postgres/src/backend/parser/scan.l (unterminated quoted identifier) InvalidEscape // postgres/src/backend/parser/scan.l (invalid escape sequence) InvalidUnicode // postgres/src/backend/parser/scan.l (invalid Unicode escape) InvalidNumber // postgres/src/backend/parser/scan.l (various numeric errors) InvalidHexInteger // postgres/src/backend/parser/scan.l:1036 ("invalid hexadecimal integer") InvalidOctalInteger // postgres/src/backend/parser/scan.l:1040 ("invalid octal integer") InvalidBinaryInteger // postgres/src/backend/parser/scan.l:1044 ("invalid binary integer") TrailingJunk // postgres/src/backend/parser/scan.l (trailing junk after...) TrailingJunkAfterParameter // Specific for parameter junk (e.g., "$1abc") OperatorTooLong // postgres/src/backend/parser/scan.l (operator too long) ZeroLengthIdentifier // postgres/src/backend/parser/scan.l:818 ("zero-length delimited identifier") InvalidUnicodeEscape // postgres/src/backend/parser/scan.l (Unicode-specific errors) InvalidUnicodeSurrogatePair // postgres/src/backend/parser/scan.l (invalid Unicode surrogate pair) UnsupportedEscapeSequence // postgres/src/backend/parser/scan.l (unsupported escape patterns) )
type LexerInterface ¶
LexerInterface - implements the lexer interface expected by goyacc Note: The actual Lexer struct is defined in lexer.go
type LexerState ¶
type LexerState int
LexerState represents the current state of the lexer state machine Maps to PostgreSQL's exclusive states defined in postgres/src/backend/parser/scan.l:192-202
const ( StateInitial LexerState = iota // Default scanning mode (INITIAL) - postgres/src/backend/parser/scan.l:191 StateXB // Bit string literals (%x xb) - postgres/src/backend/parser/scan.l:192 StateXC // C-style comments (%x xc) - postgres/src/backend/parser/scan.l:193 StateXD // Delimited identifiers (%x xd) - postgres/src/backend/parser/scan.l:194 StateXH // Hexadecimal byte strings (%x xh) - postgres/src/backend/parser/scan.l:195 StateXQ // Standard quoted strings (%x xq) - postgres/src/backend/parser/scan.l:196 StateXQS // Quote stop detection (%x xqs) - postgres/src/backend/parser/scan.l:197 StateXE // Extended quoted strings (with escapes) (%x xe) - postgres/src/backend/parser/scan.l:198 StateXDolQ // Dollar-quoted strings (%x xdolq) - postgres/src/backend/parser/scan.l:199 StateXUI // Unicode identifier (%x xui) - postgres/src/backend/parser/scan.l:200 StateXUS // Unicode string (%x xus) - postgres/src/backend/parser/scan.l:201 StateXEU // Extended string with Unicode escapes (%x xeu) - postgres/src/backend/parser/scan.l:202 )
type ParseContext ¶
type ParseContext struct {
// contains filtered or unexported fields
}
ParseContext provides unified context for PostgreSQL parsing operations This eliminates all global state and combines both lexer and parser functionality Note: Each ParseContext instance is designed for single-threaded use. Multiple parsing threads should each have their own ParseContext instance.
func NewLexerContext ¶
func NewLexerContext(input string) *ParseContext
Compatibility function for tests
func NewParseContext ¶
func NewParseContext(input string, options *ParseOptions) *ParseContext
NewParseContext creates a new unified thread-safe parsing context This is the main entry point for creating parser instances
func (*ParseContext) AddError ¶
func (ctx *ParseContext) AddError(message string, location int) *ParseError
AddError adds a parsing error to the context
func (*ParseContext) AddErrorWithType ¶
func (ctx *ParseContext) AddErrorWithType(errorType LexerErrorType, message string) *ParseError
AddErrorWithType adds a lexer error with specific error type
func (*ParseContext) AddLexerErrorAt ¶
func (ctx *ParseContext) AddLexerErrorAt(message, hint string, location int) *ParseError
AddLexerErrorAt records a lexer error at an explicit 0-based source location, with an optional PostgreSQL HINT. Unlike AddErrorWithType it does not append the scanner `at or near "<lexeme>"` suffix or reposition to the lexeme start: it is for errors detected during post-scan token processing (e.g. U&” decoding) that PostgreSQL reports via ereport(errmsg, errhint, errposition) with a plain message and an exact error cursor.
func (*ParseContext) AddLexerErrorAtDetailState ¶
func (ctx *ParseContext) AddLexerErrorAtDetailState(message, detail, hint, sqlState string, location int) *ParseError
AddLexerErrorAtDetailState records an ereport-style scanner or grammar error with PostgreSQL-visible DETAIL/HINT fields and an exact cursor location.
func (*ParseContext) AddLexerErrorAtState ¶
func (ctx *ParseContext) AddLexerErrorAtState(message, hint, sqlState string, location int) *ParseError
AddLexerErrorAtState is AddLexerErrorAt with an explicit SQLSTATE, for the scanner errors PostgreSQL raises via ereport with their own errcode instead of through yyerror. A malformed E'...' Unicode escape is the case in point: it is invalid_escape_sequence (22025), not the syntax_error every yyerror-routed scanner failure carries.
func (*ParseContext) AddLexerErrorNear ¶
func (ctx *ParseContext) AddLexerErrorNear(errorType LexerErrorType, message, lexeme string, location int) *ParseError
AddLexerErrorNear records a lexer error at an explicit 0-based location, appending PostgreSQL's `at or near "<lexeme>"` for the supplied lexeme.
addLexerError derives both the reported position and the lexeme from the token being scanned, which matches PostgreSQL for failures that condemn the whole token. Failures *inside* a string literal differ: PostgreSQL's scanner moves the error cursor to the offending escape (SET_YYLLOC) and yyerror then reports only the text matched there — the escape itself, or the single character where an escape was expected — rather than the literal scanned so far.
func (*ParseContext) AddLiteral ¶
func (ctx *ParseContext) AddLiteral(text string)
AddLiteral adds text to the current literal being accumulated
func (*ParseContext) AddLiteralByte ¶
func (ctx *ParseContext) AddLiteralByte(b byte)
AddLiteralByte adds a single byte to the current literal
func (*ParseContext) AddSyntaxError ¶
func (ctx *ParseContext) AddSyntaxError(message string) *ParseError
AddSyntaxError records a parser (goyacc) error, shaping it like PostgreSQL.
The error location is the start of the token the parse failed at (or the end of input), mirroring PostgreSQL's scanner_yyerror, which reports the position via errposition and the offending token text via "%s at or near \"%s\"". The generic goyacc message "syntax error" is decorated with the same "at or near" / "at end of input" wording; messages raised explicitly by grammar actions (PostgreSQL emits these with their own errmsg + parser_errposition) are kept verbatim and only carry the position.
func (*ParseContext) AddSyntaxErrorHint ¶
func (ctx *ParseContext) AddSyntaxErrorHint(message, hint string) *ParseError
AddSyntaxErrorHint is AddSyntaxError with a PostgreSQL HINT attached, for grammar actions that mirror ereport(errmsg(...), errhint(...)) pairs.
func (*ParseContext) AddSyntaxErrorHintState ¶
func (ctx *ParseContext) AddSyntaxErrorHintState(message, hint, sqlState string) *ParseError
AddSyntaxErrorHintState also preserves an explicit PostgreSQL SQLSTATE.
func (*ParseContext) AddWarning ¶
func (ctx *ParseContext) AddWarning(message string, location int) *ParseError
AddWarning adds a parsing warning to the context.
func (*ParseContext) AdvanceBy ¶
func (ctx *ParseContext) AdvanceBy(n int)
AdvanceBy moves the scan position forward by n bytes
func (*ParseContext) AdvanceRune ¶
func (ctx *ParseContext) AdvanceRune() rune
AdvanceRune moves forward by one Unicode character (rune)
func (*ParseContext) AtEOF ¶
func (ctx *ParseContext) AtEOF() bool
AtEOF returns true if we're at the end of input
func (*ParseContext) ClearErrors ¶
func (ctx *ParseContext) ClearErrors()
ClearErrors clears all collected errors and warnings
func (*ParseContext) Clone ¶
func (ctx *ParseContext) Clone() *ParseContext
Clone creates a copy of the parser context for use in another goroutine
func (*ParseContext) ColumnNumber ¶
func (ctx *ParseContext) ColumnNumber() int
func (*ParseContext) CurrentByte ¶
func (ctx *ParseContext) CurrentByte() (byte, bool)
CurrentByte returns the byte at the current position without advancing
func (*ParseContext) CurrentChar ¶
func (ctx *ParseContext) CurrentChar() rune
CurrentChar returns the current character at ScanPos
func (*ParseContext) CurrentPosition ¶
func (ctx *ParseContext) CurrentPosition() int
Getters for private fields (for compatibility)
func (*ParseContext) CurrentRune ¶
func (ctx *ParseContext) CurrentRune() (rune, int)
CurrentRune returns the current character at ScanPos along with its byte length. Unlike CurrentChar + utf8.RuneLen, this preserves the size that utf8.DecodeRune actually consumed, so invalid UTF-8 sequences advance by exactly one byte instead of overshooting by re-encoding U+FFFD as 3 bytes.
func (*ParseContext) DecrementDepth ¶
func (ctx *ParseContext) DecrementDepth()
DecrementDepth decrements the expression nesting depth
func (*ParseContext) DolQStart ¶
func (ctx *ParseContext) DolQStart() string
func (*ParseContext) Errors ¶
func (ctx *ParseContext) Errors() []ParseError
Legacy getter for tests
func (*ParseContext) GetContextID ¶
func (ctx *ParseContext) GetContextID() string
GetContextID returns a unique identifier for this parser context
func (*ParseContext) GetCurrentPos ¶
func (ctx *ParseContext) GetCurrentPos() int
Legacy ParserContext compatibility method
func (*ParseContext) GetCurrentPosition ¶
func (ctx *ParseContext) GetCurrentPosition() (pos int, line int, col int)
GetCurrentPosition returns the current parsing position
func (*ParseContext) GetCurrentText ¶
func (ctx *ParseContext) GetCurrentText(startPos int) string
GetCurrentText returns the text from start position to current position
func (*ParseContext) GetDepth ¶
func (ctx *ParseContext) GetDepth() int
GetDepth returns the current expression nesting depth
func (*ParseContext) GetErrors ¶
func (ctx *ParseContext) GetErrors() []ParseError
GetErrors returns all collected parsing errors
func (*ParseContext) GetLiteral ¶
func (ctx *ParseContext) GetLiteral() string
GetLiteral returns the accumulated literal value and resets the buffer
func (*ParseContext) GetOptions ¶
func (ctx *ParseContext) GetOptions() *ParseOptions
GetOptions returns the parsing options (read-only)
func (*ParseContext) GetParseTree ¶
func (ctx *ParseContext) GetParseTree() ast.Node
GetParseTree returns the root of the parse tree
func (*ParseContext) GetScanBuf ¶
func (ctx *ParseContext) GetScanBuf() []byte
func (*ParseContext) GetScanBufLen ¶
func (ctx *ParseContext) GetScanBufLen() int
func (*ParseContext) GetScanPos ¶
func (ctx *ParseContext) GetScanPos() int
Legacy LexerContext compatibility methods
func (*ParseContext) GetSourceText ¶
func (ctx *ParseContext) GetSourceText() string
GetSourceText returns the current source text being parsed
func (*ParseContext) GetState ¶
func (ctx *ParseContext) GetState() LexerState
GetState returns the current lexer state
func (*ParseContext) GetState2 ¶
func (ctx *ParseContext) GetState2() LexerState
func (*ParseContext) GetStatementBoundaries ¶
func (ctx *ParseContext) GetStatementBoundaries() (int, int)
GetStatementBoundaries returns the boundaries of the current statement
func (*ParseContext) GetWarnings ¶
func (ctx *ParseContext) GetWarnings() []ParseError
GetWarnings returns all collected parsing warnings
func (*ParseContext) HasErrors ¶
func (ctx *ParseContext) HasErrors() bool
HasErrors returns true if there are any parsing errors
func (*ParseContext) HasPrefixAtScanPos ¶
func (ctx *ParseContext) HasPrefixAtScanPos(needle string) bool
HasPrefixAtScanPos reports whether scanBuf at the current scan position starts with needle. Avoids copying the entire buffer (as ScanBuf does) so repeated lookups inside hot scanning loops stay zero-alloc. needle is taken as a string so callers don't have to allocate a []byte: `string(byteSlice) == stringLit` lowers to a direct memcmp in the Go compiler with no heap allocation.
func (*ParseContext) HasWarnings ¶
func (ctx *ParseContext) HasWarnings() bool
HasWarnings returns true if there are any parsing warnings
func (*ParseContext) InMultiDotSequence ¶
func (ctx *ParseContext) InMultiDotSequence() bool
func (*ParseContext) IncrementDepth ¶
func (ctx *ParseContext) IncrementDepth() error
IncrementDepth increments the expression nesting depth
func (*ParseContext) LineNumber ¶
func (ctx *ParseContext) LineNumber() int
func (*ParseContext) LiteralActive ¶
func (ctx *ParseContext) LiteralActive() bool
func (*ParseContext) NextByte ¶
func (ctx *ParseContext) NextByte() (byte, bool)
NextByte returns the current byte and advances the position
func (*ParseContext) PeekBytes ¶
func (ctx *ParseContext) PeekBytes(n int) []byte
PeekBytes returns n bytes starting at the current position without advancing
func (*ParseContext) PeekChar ¶
func (ctx *ParseContext) PeekChar() rune
PeekChar returns the next character without advancing
func (*ParseContext) PeekRune ¶
func (ctx *ParseContext) PeekRune() rune
PeekRune returns the next rune without advancing position
func (*ParseContext) PeekToEnd ¶
func (ctx *ParseContext) PeekToEnd() []byte
PeekToEnd returns the remaining entire buffer.
func (*ParseContext) PutBack ¶
func (ctx *ParseContext) PutBack(n int)
PutBack moves the scan position back by n bytes
func (*ParseContext) RestoreSavedPosition ¶
func (ctx *ParseContext) RestoreSavedPosition()
RestoreSavedPosition restores a previously saved position Equivalent to PostgreSQL's POP_YYLLOC() macro postgres/src/backend/parser/scan.l:122
func (*ParseContext) SaveCurrentPosition ¶
func (ctx *ParseContext) SaveCurrentPosition() int
SaveCurrentPosition saves the current position for error recovery Equivalent to PostgreSQL's PUSH_YYLLOC() macro postgres/src/backend/parser/scan.l:121
func (*ParseContext) ScanBuf ¶
func (ctx *ParseContext) ScanBuf() []byte
func (*ParseContext) ScanBufLen ¶
func (ctx *ParseContext) ScanBufLen() int
More compatibility methods for tests
func (*ParseContext) ScanPos ¶
func (ctx *ParseContext) ScanPos() int
More compatibility getters and setters
func (*ParseContext) SetColumnNumber ¶
func (ctx *ParseContext) SetColumnNumber(col int)
func (*ParseContext) SetColumnNumber2 ¶
func (ctx *ParseContext) SetColumnNumber2(col int)
func (*ParseContext) SetCurrentPosition ¶
func (ctx *ParseContext) SetCurrentPosition(pos int, line int, col int)
SetCurrentPosition updates the current parsing position
func (*ParseContext) SetCurrentPosition2 ¶
func (ctx *ParseContext) SetCurrentPosition2(pos int)
func (*ParseContext) SetDolQStart ¶
func (ctx *ParseContext) SetDolQStart(value string)
func (*ParseContext) SetInMultiDotSequence ¶
func (ctx *ParseContext) SetInMultiDotSequence(value bool)
func (*ParseContext) SetLastToken ¶
func (ctx *ParseContext) SetLastToken(token *Token)
SetLastToken records the most recent token handed to the parser. The goyacc Error hook reads it to report the token the parse failed at, matching PostgreSQL's "syntax error at or near" wording. A nil token signals end of input.
func (*ParseContext) SetLineNumber ¶
func (ctx *ParseContext) SetLineNumber(line int)
func (*ParseContext) SetLineNumber2 ¶
func (ctx *ParseContext) SetLineNumber2(line int)
func (*ParseContext) SetParseTree ¶
func (ctx *ParseContext) SetParseTree(tree ast.Node)
SetParseTree sets the root of the parse tree
func (*ParseContext) SetScanPos ¶
func (ctx *ParseContext) SetScanPos(pos int)
func (*ParseContext) SetSourceText ¶
func (ctx *ParseContext) SetSourceText(sourceText string)
SetSourceText initializes the parser with new source text to parse This resets the parser state for a new parsing operation
func (*ParseContext) SetState ¶
func (ctx *ParseContext) SetState(state LexerState)
SetState changes the lexer state
func (*ParseContext) SetStatementBoundaries ¶
func (ctx *ParseContext) SetStatementBoundaries(start int, end int)
SetStatementBoundaries sets the boundaries of the current statement
func (*ParseContext) SetUTF16FirstPart ¶
func (ctx *ParseContext) SetUTF16FirstPart(value int32)
func (*ParseContext) SetXCDepth ¶
func (ctx *ParseContext) SetXCDepth(depth int)
func (*ParseContext) StandardConformingStrings ¶
func (ctx *ParseContext) StandardConformingStrings() bool
Getters and setters for lexer fields that were previously public
func (*ParseContext) StartLiteral ¶
func (ctx *ParseContext) StartLiteral()
StartLiteral starts accumulating a literal value
func (*ParseContext) State ¶
func (ctx *ParseContext) State() LexerState
func (*ParseContext) String ¶
func (ctx *ParseContext) String() string
String returns a string representation of the parser context for debugging
func (*ParseContext) UTF16FirstPart ¶
func (ctx *ParseContext) UTF16FirstPart() int32
func (*ParseContext) XCDepth ¶
func (ctx *ParseContext) XCDepth() int
type ParseError ¶
type ParseError struct {
// Core error information
Type LexerErrorType // For lexer-specific error types
Message string // Error message
Severity ErrorSeverity // Error severity level
// Location information (unified)
Position int // Byte offset in source text
Line int // Line number (1-based)
Column int // Column number (1-based)
NearText string // Text near the error for context
AtEOF bool // Whether error occurred at EOF
// Context and source text
Context string // Additional context information (e.g., "in quoted string")
SourceText string // Original source text
ErrorLength int // Length of problematic text
// WireDetail and WireHint are the PostgreSQL-visible DETAIL and HINT for
// this diagnostic. They are forwarded when the serving layer exposes parser
// diagnostics.
WireDetail string
WireHint string
// SQLState is the PostgreSQL SQLSTATE for this diagnostic when it differs
// from the syntax_error (42601) that parser errors otherwise carry. Empty
// means the serving layer applies its default. PostgreSQL raises most
// scanner failures through yyerror (hence 42601), but a few use ereport with
// their own errcode — see SQLStateInvalidEscapeSequence.
SQLState string
}
ParseError represents a unified error structure for both lexer and parser errors Combines LexerError and ParseError from the original contexts
func (*ParseError) CursorPosition ¶
func (pe *ParseError) CursorPosition() int32
CursorPosition returns the 1-based character offset of the error in the source text, the value PostgreSQL reports in the ErrorResponse "P" field. Position is tracked internally as a byte offset; PostgreSQL counts characters (parser_errposition uses pg_mbstrlen_with_len), so multi-byte input ahead of the error shifts the character count below the byte count. Returns 0 when no position is available, which tells the wire layer to omit the field.
func (*ParseError) Error ¶
func (pe *ParseError) Error() string
Error implements the error interface
type ParseOptions ¶
type ParseOptions struct {
// SQL standard conformance settings (shared by lexer and parser)
// Ported from postgres GUC variables related to SQL standards
StandardConformingStrings bool // standard_conforming_strings GUC
EscapeStringWarning bool // escape_string_warning GUC
BackslashQuote BackslashQuoteMode // backslash_quote GUC
// Parser behavior settings
MaxIdentifierLength int // NAMEDATALEN equivalent - ported from postgres/src/include/pg_config_manual.h
MaxExpressionDepth int // Maximum expression nesting depth
MaxStatementLength int // Maximum statement length in bytes
// Error handling options
StopOnFirstError bool // Whether to stop parsing on first error
CollectAllErrors bool // Whether to collect all errors instead of stopping
// Feature flags
EnableExtensions bool // Enable PostgreSQL extensions
EnableWindowFuncs bool // Enable window functions
EnablePartitioning bool // Enable table partitioning syntax
EnableMergeStmt bool // Enable MERGE statement
}
ParseOptions contains unified configuration options for both lexer and parser Combines configuration from both original contexts
func DefaultParseOptions ¶
func DefaultParseOptions() *ParseOptions
DefaultParseOptions returns default parsing options Based on standard PostgreSQL default settings
type ParseSyntaxError ¶
type ParseSyntaxError struct {
// Message is the PostgreSQL-compatible error text (e.g.
// `syntax error at or near "FROM"`).
Message string
// Detail is the PostgreSQL DETAIL accompanying the error, when present.
Detail string
// Hint is the PostgreSQL HINT accompanying the error, when the grammar
// action supplies one (PostgreSQL emits these via errhint). Empty for
// plain syntax errors.
Hint string
// SQLState is the PostgreSQL SQLSTATE this error must be reported with when
// it differs from syntax_error (42601) — e.g. invalid_escape_sequence
// (22025) for a malformed E'...' Unicode escape. Empty means the serving
// layer applies its default.
SQLState string
// Position is the 0-based byte offset of the error in the source text.
Position int
// CursorPosition is the 1-based character offset PostgreSQL reports in the
// ErrorResponse "P" field. Zero means no position is available.
CursorPosition int32
}
ParseSyntaxError is the error returned by ParseSQL for a parse/syntax failure. It carries the PostgreSQL-shaped message plus the error position, so callers that serve PostgreSQL clients can populate the ErrorResponse "P" field. It carries no SQLSTATE: the standalone parser must not depend on the mterrors vocabulary (enforced by the parser-isolation lint rule); the serving boundary maps it to a 42601 syntax_error diagnostic.
func (*ParseSyntaxError) Error ¶
func (e *ParseSyntaxError) Error() string
type PrivTarget ¶
type PrivTarget struct {
// contains filtered or unexported fields
}
PrivTarget - represents a privilege target for GRANT/REVOKE statements Internal struct for handling privilege_target grammar rule
type Token ¶
type Token struct {
Type int // The type of token (uses parser-generated constants)
Value TokenValue // The token's value
Position int // Byte offset from start of input (YYLTYPE equivalent)
Text string // Raw text that produced this token
}
Token represents a single lexical token with its type, value, and position
func NewIntToken ¶
NewIntToken creates a new integer token
func NewKeywordToken ¶
NewKeywordToken creates a new keyword token
func NewParamToken ¶
NewParamToken creates a new parameter token ($1, $2, etc.)
func NewStringToken ¶
NewStringToken creates a new string token
func ScanAllTokens ¶
ScanAllTokens scans all tokens from a lexer and returns them as a slice This is the consolidated version of the scanAllTokens function that was duplicated across multiple test files
func (*Token) IsBitStringLiteral ¶
IsBitStringLiteral returns true if the token is a bit string literal type
func (*Token) IsIdentifier ¶
IsIdentifier returns true if the token is an identifier
func (*Token) IsNumericLiteral ¶
IsNumericLiteral returns true if the token is a numeric literal type
func (*Token) IsOperator ¶
IsOperator returns true if the token is an operator
func (*Token) IsStringLiteral ¶
IsStringLiteral returns true if the token is a string literal type
type TokenType ¶
type TokenType = int
TokenType represents the type of a lexical token This is now just an alias for int to maintain compatibility during transition New code should use the generated parser constants directly
type TokenValue ¶
type TokenValue struct {
// Only one of these fields should be set for any given token
Ival int // For integer literals (ICONST, PARAM) - postgres/src/include/parser/scanner.h:31
Str string // For identifiers and non-integer literals - postgres/src/include/parser/scanner.h:32
Keyword string // For canonical spelling of keywords - postgres/src/include/parser/scanner.h:33
}
TokenValue represents the union of possible token values This is the Go equivalent of PostgreSQL's core_YYSTYPE union Ported from postgres/src/include/parser/scanner.h:29-34
Source Files
¶
Directories
¶
| Path | Synopsis |
|---|---|
|
PostgreSQL Database Management System (also known as Postgres, formerly known as Postgres95)
|
PostgreSQL Database Management System (also known as Postgres, formerly known as Postgres95) |
|
Package datum ports PostgreSQL's Datum value model (postgres/src/include/postgres.h, REL_17_6) to Go: the tagless value that every fmgr-callable function consumes and produces.
|
Package datum ports PostgreSQL's Datum value model (postgres/src/include/postgres.h, REL_17_6) to Go: the tagless value that every fmgr-callable function consumes and produces. |
|
Package pgoid is the leaf home of PostgreSQL's object identifier type and the builtin type OID constants — the analogue of postgres/src/include/postgres_ext.h (the Oid type itself) and the type OID macros of the generated pg_type_d.h.
|
Package pgoid is the leaf home of PostgreSQL's object identifier type and the builtin type OID constants — the analogue of postgres/src/include/postgres_ext.h (the Oid type itself) and the type OID macros of the generated pg_type_d.h. |
|
Package plpgsql parses PL/pgSQL function bodies into the AST defined in go/common/parser/ast.
|
Package plpgsql parses PL/pgSQL function bodies into the AST defined in go/common/parser/ast. |