Documentation
¶
Index ¶
Constants ¶
This section is empty.
Variables ¶
var SentinelNone = Token{TokenType: SENTINEL}
Functions ¶
func ParseIntPython ¶
ParseIntPython parses value exactly the way CPython's int(value, base) does, for the bases sqlglot uses to validate BIT_STRING/HEX_STRING literals (2, 8, 16). It returns the arbitrary-precision value (a bit/hex literal can exceed 64 bits) and whether value is a valid literal. CPython accepts, in order: surrounding whitespace, an optional single +/- sign, an optional base prefix (0b/0o/0x matching the base), then one or more base digits with optional single '_' separators - each underscore between two digits or immediately after the base prefix, never leading, trailing, or doubled (int("A_B",16) and int("0x_FF",16) are valid; "_A"/"A_"/"A__B"/"+_A" are not).
The tokenizer validates the quoted forms (x'..'/b'..') by int(payload, base) and the bare forms (0x../0b..) by int(fullText, base); the generator reuses it to fold a hex/bit literal to its integer value on a dialect with no hex/bit family. Only the digit scan runs on invalid input (no big.Int allocation until the literal is known valid).
func ReprTokens ¶
Types ¶
type BatchSeparator ¶
type BatchSeparator uint8
BatchSeparator selects a client-tool batch separator: a line that a script runner (sqlcmd/SSMS) strips and treats as the end of the current batch, so it is a statement boundary rather than SQL. The tokenizer emits a matching line as a SEMICOLON token whose Text is the separator line itself, so every downstream consumer splits on it exactly as on `;`. A separator right after a `;` (or at the start of input) is dropped instead, so it never yields an empty statement.
const ( // BatchSeparatorNone recognizes no separator line (upstream behavior). BatchSeparatorNone BatchSeparator = iota // BatchSeparatorGo is the T-SQL `GO [count]` line (sqlcmd/SSMS): `GO`, case-insensitive, // alone on its line apart from spaces/tabs, an optional repeat count, and an optional // trailing `--` comment. BatchSeparatorGo // BatchSeparatorSlash is the Oracle SQL*Plus/SQLcl terminator: a `/` alone on its line // apart from spaces/tabs. BatchSeparatorSlash )
type FormatString ¶
type FormatString struct {
End string
TokenType TokenType
// DecodeUnicode marks a SQL-standard Unicode-escaped delimited form — Postgres
// `U&'...'` (string) and `U&"..."` (identifier). When set, scanString extracts the
// payload with delimiter-doubling only (no backslash string-escapes), decodes the
// backslash-Unicode escapes (`\XXXX`, `\+XXXXXX`, `\\`, surrogate pairs) into the real
// code points, and emits TokenType (STRING or IDENTIFIER) carrying the decoded text — so
// `U&"inf\006Frmation_schema"` becomes the identifier `information_schema`, matching what
// Postgres executes. A trailing custom `UESCAPE 'c'` is not consumed here, so those rare
// forms fall through and fail closed (parse error / Command) rather than decode wrongly.
// Beyond pinned upstream (which mis-tokenizes `U&'...'` as `U & '...'` and parse-errors on
// the identifier form). See DEVIATIONS §1.
DecodeUnicode bool
}
type Token ¶
type Token struct {
TokenType TokenType
Text string
Line int
Col int
Start int // inclusive rune offset into the original source
End int // inclusive rune offset into the original source
Comments []string
// WrapStart/WrapEnd (set iff WrapEnd > 0) widen a token spliced out of an activated MySQL
// executable comment to the `/*!NNNNN`/`*/` delimiters. Start/End keep the exact lexeme;
// span slicing must use the widened extent or the slice loses the wrapper and stops being
// executable MySQL (`SELECT 1 /*!40101 + 2` has no closing `*/`).
WrapStart int
WrapEnd int
// LeadingCommentStart is the source start (inclusive rune offset) of the first comment
// attached to this token that precedes it; HasLeadingComment disambiguates offset 0.
// TrailingCommentEnd is the inclusive end of the last comment attached to it that follows
// it. Together they let a statement span cover its attached comments without re-scanning
// the source (Go-only source spans, DEVIATIONS §6.2).
LeadingCommentStart int
HasLeadingComment bool
TrailingCommentEnd int
HasTrailingComment bool
// Keyword is set iff TokenType came from the Keywords table of the tokenizer that scanned this
// token (Hive or Trino under Athena); that table also holds operators such as `::` and `<=`.
Keyword bool
// Synthetic marks a token with no source text (Athena's HIVE_TOKEN_STREAM); its span is meaningless.
Synthetic bool
}
Token is one lexeme from Tokenize. Text is the DECODED value — for a string/quoted identifier the surrounding quotes are stripped and escapes resolved, so Text is NOT the raw source. To recover the exact source lexeme (e.g. for byte-exact hashing), slice the original source by Start/End, not Text. Start and End are INCLUSIVE rune offsets into the original source string passed to Tokenize (the tokenizer operates on []rune(sql)); string([]rune(sql)[Start:End+1]) yields the verbatim lexeme, and this holds for every token kind (STRING, quoted identifier, NUMBER, keyword, VAR, operator). Ordinary comments are attached to Comments rather than emitted as tokens.
func IdentifierToken ¶
func NewTokenFull ¶
func StringToken ¶
type TokenType ¶
type TokenType uint16
const ( L_PAREN TokenType = iota + 1 R_PAREN L_BRACKET R_BRACKET L_BRACE R_BRACE COMMA DOT DASH PLUS COLON DOTCOLON DOTCARET DCOLON DCOLONDOLLAR DCOLONPERCENT DCOLONQMARK DQMARK SEMICOLON STAR BACKSLASH SLASH LT LTE GT GTE NOT EQ NEQ NULLSAFE_EQ COLON_EQ COLON_GT NCOLON_GT AND OR AMP DPIPE PIPE_GT PIPE PIPE_SLASH DPIPE_SLASH CARET CARET_AT TILDE ARROW DARROW FARROW HASH HASH_ARROW DHASH_ARROW LR_ARROW LLRR_ARROW DAT AT_QMARK LT_AT AT_GT DOLLAR PARAMETER SESSION SESSION_PARAMETER SESSION_USER DAMP AMP_LT AMP_GT ADJACENT XOR DSTAR QMARK_AMP QMARK_PIPE HASH_DASH EXCLAMATION URI_START BLOCK_START BLOCK_END SPACE BREAK STRING NUMBER IDENTIFIER DATABASE COLUMN COLUMN_DEF SCHEMA TABLE WAREHOUSE STAGE STREAM STREAMLIT VAR BIT_STRING HEX_STRING BYTE_STRING NATIONAL_STRING RAW_STRING HEREDOC_STRING UNICODE_STRING BIT BOOLEAN TINYINT UTINYINT SMALLINT USMALLINT MEDIUMINT UMEDIUMINT INT UINT BIGINT UBIGINT BIGNUM INT128 UINT128 INT256 UINT256 FLOAT DOUBLE UDOUBLE DECIMAL DECIMAL32 DECIMAL64 DECIMAL128 DECIMAL256 DECFLOAT UDECIMAL BIGDECIMAL CHAR NCHAR VARCHAR NVARCHAR BPCHAR TEXT MEDIUMTEXT LONGTEXT BLOB MEDIUMBLOB LONGBLOB TINYBLOB TINYTEXT NAME BINARY VARBINARY JSON JSONB TIME TIMETZ TIME_NS TIMESTAMP TIMESTAMPTZ TIMESTAMPLTZ TIMESTAMPNTZ TIMESTAMP_S TIMESTAMP_MS TIMESTAMP_NS DATETIME DATETIME2 DATETIME64 SMALLDATETIME DATE DATE32 INT4RANGE INT4MULTIRANGE INT8RANGE INT8MULTIRANGE NUMRANGE NUMMULTIRANGE TSRANGE TSMULTIRANGE TSTZRANGE TSTZMULTIRANGE DATERANGE DATEMULTIRANGE UUID GEOGRAPHY GEOGRAPHYPOINT NULLABLE GEOMETRY POINT RING LINESTRING LOCALTIME LOCALTIMESTAMP SYSTIMESTAMP MULTILINESTRING POLYGON MULTIPOLYGON HLLSKETCH HSTORE SUPER SERIAL SMALLSERIAL BIGSERIAL XML YEAR USERDEFINED MONEY SMALLMONEY ROWVERSION IMAGE VARIANT OBJECT INET IPADDRESS IPPREFIX IPV4 IPV6 ENUM ENUM8 ENUM16 FIXEDSTRING LOWCARDINALITY NESTED AGGREGATEFUNCTION SIMPLEAGGREGATEFUNCTION TDIGEST UNKNOWN VECTOR DYNAMIC VOID ALIAS ALTER ALL ANTI ANY APPLY ARRAY ASC ASOF ATTACH AUTO_INCREMENT BEGIN BETWEEN BULK_COLLECT_INTO CACHE CASE CHARACTER_SET CLUSTER_BY COLLATE COMMAND COMMENT COMMIT CONNECT_BY CONSTRAINT COPY CREATE CROSS CUBE CURRENT_DATE CURRENT_DATETIME CURRENT_SCHEMA CURRENT_TIME CURRENT_TIMESTAMP CURRENT_USER CURRENT_USER_ID CURRENT_ROLE CURRENT_CATALOG DECLARE DEFAULT DELETE DESC DESCRIBE DETACH DICTIONARY DISTINCT DISTRIBUTE_BY DIV DROP ELSE END ESCAPE EXCEPT EXECUTE EXISTS FALSE FETCH FILE FILE_FORMAT FILTER FINAL FIRST FOR FORCE FOREIGN_KEY FORMAT FROM FULL FUNCTION GET GLOB GLOBAL GRANT GROUP_BY GROUPING_SETS HAVING HINT IGNORE ILIKE IN INDEX INDEXED_BY INNER INSERT INSTALL INTEGRATION INTERSECT INTERVAL INTO INTRODUCER IRLIKE IS ISNULL JOIN JOIN_MARKER KEEP KEY KILL LANGUAGE LATERAL LEFT LIKE LIMIT LIST LOAD LOCK MAP MATCH MATCH_CONDITION MATCH_RECOGNIZE MEMBER_OF MERGE MOD MODEL NATURAL NEXT NOTHING NOTNULL NULL OBJECT_IDENTIFIER OFFSET ON ONLY OPERATOR ORDER_BY ORDER_SIBLINGS_BY ORDERED ORDINALITY OUT INOUT OUTER OVER OVERLAPS OVERWRITE PACKAGE PARTITION PARTITION_BY PERCENT PIVOT PLACEHOLDER POLICY POOL POSITIONAL PRAGMA PREWHERE PRIMARY_KEY PROCEDURE PROPERTIES PSEUDO_TYPE PUT QUALIFY QUOTE QDCOLON RANGE RECURSIVE REFRESH RENAME REPLACE RETURNING REVOKE REFERENCES RIGHT RLIKE ROLE ROLLBACK ROLLUP ROW ROWS RULE SELECT SEMI SEPARATOR SEQUENCE SERDE_PROPERTIES SET SETTINGS SHOW SIMILAR_TO SOME SORT_BY SOUNDS_LIKE SQL_SECURITY START_WITH STORAGE_INTEGRATION STRAIGHT_JOIN STRUCT SUMMARIZE TABLE_SAMPLE TAG TEMPORARY TOP THEN TRUE TRUNCATE TRIGGER TYPE UNCACHE UNDROP UNION UNLOAD UNNEST UNPIVOT UPDATE USE USING VALUES VARIADIC VIEW SEMANTIC_VIEW VOLATILE VOLUME WHEN WHERE WINDOW WITH UNIQUE UTC_DATE UTC_TIME UTC_TIMESTAMP VERSION_SNAPSHOT TIMESTAMP_SNAPSHOT OPTION SINK SOURCE ANALYZE NAMESPACE EXPORT HIVE_TOKEN_STREAM // ClickHouse cluster (dialects/clickhouse.py:110): the PROJECTION keyword opening a // CREATE TABLE projection definition. PROJECTION SENTINEL )
type TokenizeFunc ¶
TokenizeFunc lets dialects with multi-stage tokenization retain the public concrete *Tokenizer API while routing each SQL string through a custom implementation.
type Tokenizer ¶
type Tokenizer struct {
// contains filtered or unexported fields
}
func NewTokenizer ¶
func NewTokenizer() *Tokenizer
func NewTokenizerWithConfig ¶
func NewTokenizerWithConfig(cfg TokenizerConfig) *Tokenizer
func NewTokenizerWithFunc ¶
func NewTokenizerWithFunc(tokenizeFunc TokenizeFunc) *Tokenizer
NewTokenizerWithFunc constructs a tokenizer backed by a non-nil custom callback.
type TokenizerConfig ¶
type TokenizerConfig struct {
SingleTokens map[rune]TokenType
Keywords map[string]TokenType
Quotes map[string]string
FormatStrings map[string]FormatString
Identifiers map[rune]string
Comments map[string]string
// MySQLExecutableComments and MySQLVersion implement the NON-UPSTREAM, opt-in
// executable-comment behavior documented in DEVIATIONS §1.5. A false capability
// or nil version preserves upstream comment stripping and attachment.
MySQLExecutableComments bool
MySQLVersion *int
// LineCommentRequiresSpace holds line-comment starts (keys of Comments) that only
// begin a comment when immediately followed by whitespace/control or EOF. MySQL
// requires this for `--` — `1--2` is arithmetic `1 - -2`, not `1` + comment. See
// DEVIATIONS §1.4 (upstream mis-tokenizes this).
LineCommentRequiresSpace map[string]bool
StringEscapes map[rune]bool
ByteStringEscapes map[rune]bool
IdentifierEscapes map[rune]bool
EscapeFollowChars map[rune]bool
Commands map[TokenType]bool
CommandPrefixTokens map[TokenType]bool
TokensPrecedingHint map[TokenType]bool
NumericLiterals map[string]string
VarSingleTokens map[rune]bool
UnescapedSequences map[string]string
NestedComments bool
HintStart string
HasBitStrings bool
HasHexStrings bool
// MariaDBExecutableComments enables MariaDB's `/*M! ... */` and `/*M!100100 ... */`
// executable comments alongside MySQL's `/*!` form, gated by the same version setting.
MariaDBExecutableComments bool
// HexIntegerLiterals makes 0x-prefixed tokens numeric integer literals instead of hex
// BLOB/binary literals. Upstream treats 0x as a hex string everywhere, but real SQLite
// parses it as an integer (see DEVIATIONS §1.28), so sqlite sets this.
HexIntegerLiterals bool
StringEscapesAllowedInRawStrings bool
HeredocTagIsIdentifier bool
HeredocStringAlternative TokenType
NumbersCanBeUnderscoreSeparated bool
NumbersCanHaveDecimals bool
IdentifiersCanStartWithDigit bool
// OracleQQuotes enables Oracle's q'[...]' alternative string literal. The
// delimiter is chosen dynamically from the character following q'.
OracleQQuotes bool
KeywordTrie *trie.Node
// BatchSeparator names the client-tool batch separator line the dialect recognizes.
// Upstream has none; BatchSeparatorNone (the zero value) keeps that behavior. See
// DEVIATIONS §1.22.
BatchSeparator BatchSeparator
}
func BaseConfig ¶
func BaseConfig() TokenizerConfig
func CompileConfig ¶
func CompileConfig(cfg TokenizerConfig) TokenizerConfig
CompileConfig recomputes derived config (national-string format strings, the hint comment, and the keyword trie) after a caller mutates a base config's maps. Exported so per-dialect config builders in package dialects can finalize configs.
type TokenizerCore ¶
type TokenizerCore struct {
// contains filtered or unexported fields
}
func NewTokenizerCore ¶
func NewTokenizerCore(cfg TokenizerConfig) *TokenizerCore