const ( StmtSelect = iota StmtStream StmtInsert StmtReplace StmtUpdate StmtDelete StmtDDL StmtBegin StmtCommit StmtRollback StmtSet StmtShow StmtUse StmtOther StmtUnknown )
These constants are used to identify the SQL statement type.
View Sourceconst ( DistinctStr = "distinct " StraightJoinHint = "straight_join " )
Select.Distinct
View Sourceconst ( ForUpdateStr = " for update" ShareModeStr = " lock in share mode" )
Select.Lock
View Sourceconst ( SQLCacheStr = "sql_cache " SQLNoCacheStr = "sql_no_cache " )
Select.Cache
View Sourceconst ( UnionStr = "union" UnionAllStr = "union all" UnionDistinctStr = "union distinct" )
Union.Type
View Sourceconst ( InsertStr = "insert" ReplaceStr = "replace" )
DDL strings.
View Sourceconst ( SessionStr = "session" GlobalStr = "global" )
Set.Scope or Show.Scope
View Sourceconst ( CreateStr = "create" AlterStr = "alter" DropStr = "drop" RenameStr = "rename" TruncateStr = "truncate" CreateVindexStr = "create vindex" AddColVindexStr = "add vindex" DropColVindexStr = "drop vindex" VindexOwnerStr = "owner" )
DDL strings.
View Sourceconst ( JoinStr = "join" StraightJoinStr = "straight_join" LeftJoinStr = "left join" RightJoinStr = "right join" NaturalJoinStr = "natural join" NaturalLeftJoinStr = "natural left join" NaturalRightJoinStr = "natural right join" )
JoinTableExpr.Join
View Sourceconst ( UseStr = "use " IgnoreStr = "ignore " ForceStr = "force " )
Index hints.
View Sourceconst ( WhereStr = "where" HavingStr = "having" )
Where.Type
View Sourceconst ( EqualStr = "=" LessThanStr = "<" GreaterThanStr = ">" LessEqualStr = "<=" GreaterEqualStr = ">=" NotEqualStr = "!=" NullSafeEqualStr = "<=>" InStr = "in" NotInStr = "not in" LikeStr = "like" NotLikeStr = "not like" RegexpStr = "regexp" NotRegexpStr = "not regexp" )
ComparisonExpr.Operator
View Sourceconst ( BetweenStr = "between" NotBetweenStr = "not between" )
RangeCond.Operator
View Sourceconst ( IsNullStr = "is null" IsNotNullStr = "is not null" IsTrueStr = "is true" IsNotTrueStr = "is not true" IsFalseStr = "is false" IsNotFalseStr = "is not false" )
IsExpr.Operator
These are the possible Valtype values. HexNum represents a 0x... value. It cannot be treated as a simple value because it can be interpreted differently depending on the context.
View Sourceconst ( BitAndStr = "&" BitOrStr = "|" BitXorStr = "^" PlusStr = "+" MinusStr = "-" MultStr = "*" DivStr = "/" IntDivStr = "div" ModStr = "%" ShiftLeftStr = "<<" ShiftRightStr = ">>" )
BinaryExpr.Operator
View Sourceconst ( UPlusStr = "+" UMinusStr = "-" TildaStr = "~" BangStr = "!" BinaryStr = "binary " UBinaryStr = "_binary " )
UnaryExpr.Operator
View Sourceconst ( BooleanModeStr = " in boolean mode" NaturalLanguageModeStr = " in natural language mode" NaturalLanguageModeWithQueryExpansionStr = " in natural language mode with query expansion" QueryExpansionStr = " with query expansion" )
MatchExpr.Option
Order.Direction
View Sourceconst ( DirectiveMultiShardAutocommit = "MULTI_SHARD_AUTOCOMMIT" DirectiveSkipQueryPlanCache = "SKIP_QUERY_PLAN_CACHE" DirectiveQueryTimeout = "QUERY_TIMEOUT_MS" )View Source
const ( CharacterSetStr = " character set" )
this string is "character set" and this comment is required
View Sourceconst ( ReorganizeStr = "reorganize partition" )
Partition strings
View Sourcevar Aggregates = map[string]bool{ "avg": true, "bit_and": true, "bit_or": true, "bit_xor": true, "count": true, "group_concat": true, "max": true, "min": true, "std": true, "stddev_pop": true, "stddev_samp": true, "stddev": true, "sum": true, "var_pop": true, "var_samp": true, "variance": true, }
Aggregates is a map of all aggregate functions.
Append appends the SQLNode to the buffer.
Backtick produces a backticked literal given an input string.
EncodeValue encodes one bind variable value into the query.
ExtractMysqlComment extracts the version and SQL from a comment-only query such as /*!50708 sql here */
ExtractSetValues returns a map of key-value pairs if the query is a SET statement. Values can be bool, int64 or string. Since set variable names are case insensitive, all keys are returned as lower case.
FetchBindVar resolves the bind variable by fetching it from bindVariables.
FormatImpossibleQuery creates an impossible query in a TrackedBuffer. An impossible query is a modified version of a query where all selects have where clauses that are impossible for mysql to resolve. This is used in the vtgate and vttablet:
- In the vtgate it's used for joins: if the first query returns no result, then vtgate uses the impossible query just to fetch field info from vttablet - In the vttablet, it's just an optimization: the field info is fetched once form MySQL, cached and reused for subsequent queries
GetBindvars returns a map of the bind vars referenced in the statement. TODO(sougou); This function gets called again from vtgate/planbuilder. Ideally, this should be done only once.
IsColName returns true if the Expr is a *ColName.
IsDML returns true if the query is an INSERT, UPDATE or DELETE statement.
IsNull returns true if the Expr is SQL NULL
IsSimpleTuple returns true if the Expr is a ValTuple that contains simple values or if it's a list arg.
IsValue returns true if the Expr is a string, integral or value arg. NULL is not considered to be a value.
KeywordString returns the string corresponding to the given keyword
NewPlanValue builds a sqltypes.PlanValue from an Expr.
Normalize changes the statement to use bind values, and updates the bind vars to those values. The supplied prefix is used to generate the bind var names. The function ensures that there are no collisions with existing bind vars. Within Select constructs, bind vars are deduped. This allows us to identify vindex equality. Otherwise, every value is treated as distinct.
Preview analyzes the beginning of the query using a simpler and faster textual comparison to identify the statement type.
RedactSQLQuery returns a sql string with the params stripped out for display
SkipQueryPlanCacheDirective returns true if skip query plan cache directive is set to true in query.
SplitStatement returns the first sql statement up to either a ; or EOF and the remainder from the given buffer
SplitStatementToPieces split raw sql statement that may have multi sql pieces to sql pieces returns the sql pieces blob contains; or error if sql cannot be parsed
StmtType returns the statement type as a string
String returns a string representation of an SQLNode.
StringIn is a convenience function that returns true if str matches any of the values.
StripLeadingComments trims the SQL string and removes any leading comments
Walk calls visit on every node. If visit returns true, the underlying nodes are also visited. If it returns an error, walking is interrupted, and the error is returned.
AliasedExpr defines an aliased SELECT expression.
AliasedTableExpr represents a table expression coupled with an optional alias or index hint. If As is empty, no alias was used.
RemoveHints returns a new AliasedTableExpr with the hints removed.
type AndExpr ¶type AndExpr struct { Left, Right Expr }
AndExpr represents an AND expression.
func (*AndExpr) Format ¶Format formats the node.
Begin represents a Begin statement.
type BinaryExpr struct { Operator string Left, Right Expr }
BinaryExpr represents a binary value expression.
BoolVal is true or false.
CaseExpr represents a CASE expression.
ColIdent is a case insensitive SQL identifier. It will be escaped with backquotes if necessary.
NewColIdent makes a new ColIdent.
CompliantName returns a compliant id name that can be used for a bind var.
Equal performs a case-insensitive compare.
EqualString performs a case-insensitive compare with str.
IsEmpty returns true if the name is empty.
Lowered returns a lower-cased column name. This function should generally be used only for optimizing comparisons.
MarshalJSON marshals into JSON.
String returns the unescaped column name. It must not be used for SQL generation. Use sqlparser.String instead. The Stringer conformance is for usage in templates.
UnmarshalJSON unmarshals from JSON.
ColName represents a column name.
Equal returns true if the column names match.
type ColTuple interface { Expr }
ColTuple represents a list of column values. It can be ValTuple, Subquery, ListArg.
type CollateExpr struct { Expr Expr Charset string }
CollateExpr represents dynamic collate operator.
type ColumnDefinition ¶ColumnDefinition describes a column in a CREATE TABLE statement
func (*ColumnDefinition) Format ¶Format formats the node.
type ColumnKeyOption ¶ColumnKeyOption indicates whether or not the given column is defined as an index element and contains the type of the option
type ColumnType ¶ColumnType represents a sql type in a CREATE TABLE statement All optional fields are nil if not specified
func (*ColumnType) DescribeType ¶DescribeType returns the abbreviated type information as required for describe table
func (*ColumnType) Format ¶Format returns a canonical string representation of the type and all relevant options
func (*ColumnType) SQLType ¶SQLType returns the sqltypes type code for the given column
type Columns ¶Columns represents an insert column list.
func (Columns) FindColumn ¶FindColumn finds a column in the column list, returning the index if it exists or -1 otherwise
func (Columns) Format ¶Format formats the node.
type CommentDirectives map[string]interface{}
CommentDirectives is the parsed representation for execution directives conveyed in query comments
ExtractCommentDirectives parses the comment list for any execution directives of the form:
/*vt+ OPTION_ONE=1 OPTION_TWO OPTION_THREE=abcd */
It returns the map of the directive values or nil if there aren't any.
IsSet checks the directive map for the named directive and returns true if the directive is set and has a true/false or 0/1 value
Comments represents a list of comments.
Commit represents a Commit statement.
type ComparisonExpr struct { Operator string Left, Right Expr Escape Expr }
ComparisonExpr represents a two-value comparison expression.
ConvertExpr represents a call to CONVERT(expr, type) or it's equivalent CAST(expr AS type). Both are rewritten to the former.
ConvertType represents the type in call to CONVERT(expr, type)
type ConvertUsingExpr struct { Expr Expr Type string }
ConvertUsingExpr represents a call to CONVERT(expr USING charset).
DBDDL represents a CREATE, DROP database statement.
DDL represents a CREATE, ALTER, DROP, RENAME or TRUNCATE statement. Table is set for AlterStr, DropStr, RenameStr, TruncateStr NewName is set for AlterStr, CreateStr, RenameStr. VindexSpec is set for CreateVindexStr, DropVindexStr, AddColVindexStr, DropColVindexStr VindexCols is set for AddColVindexStr
type Default struct { ColName string }
Default represents a DEFAULT expression.
Delete represents a DELETE statement. If you add fields here, consider adding them to calls to validateSubquerySamePlan.
type Encodable interface { EncodeSQL(buf *bytes.Buffer) }
Encodable defines the interface for types that can be custom-encoded into SQL.
type ExistsExpr struct { Subquery *Subquery }
ExistsExpr represents an EXISTS expression.
Expr represents an expression.
ExprFromValue converts the given Value into an Expr or returns an error.
func ReplaceExpr(root, from, to Expr) Expr
ReplaceExpr finds the from expression from root and replaces it with to. If from matches root, then to is returned.
Exprs represents a list of value expressions. It's not a valid expression because it's not parenthesized.
FuncExpr represents a function call.
IsAggregate returns true if the function is an aggregate.
GroupBy represents a GROUP BY clause.
GroupConcatExpr represents a call to GROUP_CONCAT
type IndexColumn ¶IndexColumn describes a column in an index definition with optional length
IndexDefinition describes an index in a CREATE TABLE statement
IndexHints represents a list of index hints.
IndexInfo describes the name and type of an index in a CREATE TABLE statement
IndexOption is used for trailing options for indexes: COMMENT, KEY_BLOCK_SIZE, USING
Insert represents an INSERT or REPLACE statement. Per the MySQL docs, http://dev.mysql.com/doc/refman/5.7/en/replace.html Replace is the counterpart to `INSERT IGNORE`, and works exactly like a normal INSERT except if the row exists. In that case it first deletes the row and re-inserts with new values. For that reason we keep it as an Insert struct. Replaces are currently disallowed in sharded schemas because of the implications the deletion part may have on vindexes. If you add fields here, consider adding them to calls to validateSubquerySamePlan.
type InsertRows interface { SQLNode }
InsertRows represents the rows for an INSERT statement.
InsertValues is a custom SQL encoder for the values of an insert statement.
EncodeSQL performs the SQL encoding for InsertValues.
type IntervalExpr struct { Expr Expr Unit string }
IntervalExpr represents a date-time INTERVAL expression.
IsExpr represents an IS ... or an IS NOT ... expression.
JoinCondition represents the join conditions (either a ON or USING clause) of a JoinTableExpr.
JoinTableExpr represents a TableExpr that's a JOIN operation.
type LengthScaleOption struct { Length *SQLVal Scale *SQLVal }
LengthScaleOption is used for types that have an optional length and scale
type Limit struct { Offset, Rowcount Expr }
Limit represents a LIMIT clause.
ListArg represents a named list argument.
type MarginComments struct { }
MarginComments holds the leading and trailing comments that surround a query.
SplitMarginComments pulls out any leading or trailing comments from a raw sql query. This function also trims leading (if there's a comment) and trailing whitespace.
MatchExpr represents a call to the MATCH function
type Nextval struct { Expr Expr }
Nextval defines the NEXT VALUE expression.
NodeFormatter defines the signature of a custom node formatter function that can be given to TrackedBuffer for code generation.
type NotExpr struct { Expr Expr }
NotExpr represents a NOT expression.
NullVal represents a NULL value.
OnDup represents an ON DUPLICATE KEY clause.
type OrExpr struct { Left, Right Expr }
OrExpr represents an OR expression.
Order represents an ordering expression.
OrderBy represents an ORDER By clause.
OtherAdmin represents a misc statement that relies on ADMIN privileges, such as REPAIR, OPTIMIZE, or TRUNCATE statement. It should be used only as an indicator. It does not contain the full AST for the statement.
OtherRead represents a DESCRIBE, or EXPLAIN statement. It should be used only as an indicator. It does not contain the full AST for the statement.
type ParenExpr struct { Expr Expr }
ParenExpr represents a parenthesized boolean expression.
ParenSelect is a parenthesized SELECT statement.
AddOrder adds an order by element
SetLimit sets the limit clause
ParenTableExpr represents a parenthesized list of TableExpr.
type ParsedQuery struct { Query string }
ParsedQuery represents a parsed query where bind locations are precompued for fast substitutions.
BuildParsedQuery builds a ParsedQuery from the input.
NewParsedQuery returns a ParsedQuery of the ast.
GenerateQuery generates a query by substituting the specified bindVariables. The extras parameter specifies special parameters that can perform custom encoding.
PartitionDefinition describes a very minimal partition definition
PartitionSpec describe partition actions (for alter and create)
Partitions is a type alias for Columns so we can handle printing efficiently
RangeCond represents a BETWEEN or a NOT BETWEEN expression.
Rollback represents a Rollback statement.
SQLNode defines the interface for all nodes generated by the parser.
SQLVal represents a single value.
NewBitVal builds a new BitVal containing a bit literal.
NewFloatVal builds a new FloatVal.
NewHexNum builds a new HexNum.
NewHexVal builds a new HexVal.
NewIntVal builds a new IntVal.
NewStrVal builds a new StrVal.
NewValArg builds a new ValArg.
HexDecode decodes the hexval into bytes.
Select represents a SELECT statement.
AddHaving adds the boolean expression to the HAVING clause as an AND condition. If the expression is an OR clause, it parenthesizes it. Currently, the OR operator is the only one that's lower precedence than AND.
AddOrder adds an order by element
AddWhere adds the boolean expression to the WHERE clause as an AND condition. If the expression is an OR clause, it parenthesizes it. Currently, the OR operator is the only one that's lower precedence than AND.
SetLimit sets the limit clause
type SelectExpr interface { SQLNode }
SelectExpr represents a SELECT expression.
SelectExprs represents SELECT expressions.
SelectStatement any SELECT statement.
Set represents a SET statement.
SetExpr represents a set expression.
SetExprs represents a list of set expressions.
SetKey is the extracted key from one SetExpr
Show represents a show statement.
HasOnTable returns true if the show statement has an "on" clause
type ShowFilter struct { Like string Filter Expr }
ShowFilter is show tables filter
ShowTablesOpt is show tables option
type SimpleTableExpr interface { SQLNode }
SimpleTableExpr represents a simple table expression.
StarExpr defines a '*' or 'table.*' expression.
type Statement interface { SQLNode }
Statement represents a statement.
Parse parses the SQL in full and returns a Statement, which is the AST representation of the query. If a DDL statement is partially parsed but still contains a syntax error, the error is ignored and the DDL is returned anyway.
ExampleParse is the first example from the README.md.
sql := "SELECT * FROM table WHERE a = 'abc'" stmt, err := Parse(sql) if err != nil { // Do something with the err } // Otherwise do something with stmt switch stmt := stmt.(type) { case *Select: _ = stmt case *Insert: }
ParseNext parses a single SQL statement from the tokenizer returning a Statement which is the AST representation of the query. The tokenizer will always read up to the end of the statement, allowing for the next call to ParseNext to parse any subsequent SQL statements. When there are no more statements to parse, a error of io.EOF is returned.
ExampleParseNext is the second example from the README.md.
r := strings.NewReader("INSERT INTO table1 VALUES (1, 'a'); INSERT INTO table2 VALUES (3, 4);") tokens := NewTokenizer(r) for { stmt, err := ParseNext(tokens) if err == io.EOF { break } // Do something with stmt or err. _ = stmt }
ParseStrictDDL is the same as Parse except it errors on partially parsed DDL statements.
Stream represents a SELECT statement.
Subquery represents a subquery.
SubstrExpr represents a call to SubstrExpr(column, value_expression) or SubstrExpr(column, value_expression,value_expression) also supported syntax SubstrExpr(column from value_expression for value_expression)
type TableExpr interface { SQLNode }
TableExpr represents a table expression.
TableExprs represents a list of table expressions.
type TableIdent struct { }
TableIdent is a case sensitive SQL identifier. It will be escaped with backquotes if necessary.
GetTableName returns the table name from the SimpleTableExpr only if it's a simple expression. Otherwise, it returns "".
NewTableIdent creates a new TableIdent.
CompliantName returns a compliant id name that can be used for a bind var.
IsEmpty returns true if TabIdent is empty.
MarshalJSON marshals into JSON.
String returns the unescaped table name. It must not be used for SQL generation. Use sqlparser.String instead. The Stringer conformance is for usage in templates.
UnmarshalJSON unmarshals from JSON.
type TableName struct { Name, Qualifier TableIdent }
TableName represents a table name. Qualifier, if specified, represents a database or keyspace. TableName is a value struct whose fields are case sensitive. This means two TableName vars can be compared for equality and a TableName can also be used as key in a map.
IsEmpty returns true if TableName is nil or empty.
ToViewName returns a TableName acceptable for use as a VIEW. VIEW names are always lowercase, so ToViewName lowercasese the name. Databases are case-sensitive so Qualifier is left untouched.
TableNames is a list of TableName.
TableSpec describes the structure of a table from a CREATE TABLE statement
func (*TableSpec) AddColumn ¶AddColumn appends the given column to the list in the spec
AddIndex appends the given index to the list in the spec
Tokenizer is the struct used to generate SQL tokens for the parser.
NewStringTokenizer creates a new Tokenizer for the sql string.
NewTokenizer creates a new Tokenizer reading a sql string from the io.Reader.
Error is called by go yacc if there's a parsing error.
Lex returns the next token form the Tokenizer. This function is used by go yacc.
Scan scans the tokenizer for the next token and returns the token type and an optional value.
TrackedBuffer is used to rebuild a query from the ast. bindLocations keeps track of locations in the buffer that use bind variables for efficient future substitutions. nodeFormatter is the formatting function the buffer will use to format a node. By default(nil), it's FormatNode. But you can supply a different formatting function if you want to generate a query that's different from the default.
NewTrackedBuffer creates a new TrackedBuffer.
HasBindVars returns true if the parsed query uses bind vars.
Myprintf mimics fmt.Fprintf(buf, ...), but limited to Node(%v), Node.Value(%s) and string(%s). It also allows a %a for a value argument, in which case it adds tracking info for future substitutions.
The name must be something other than the usual Printf() to avoid "go vet" warnings due to our custom format specifiers.
ParsedQuery returns a ParsedQuery that contains bind locations for easy substitution.
WriteArg writes a value argument into the buffer along with tracking information for future substitutions. arg must contain the ":" or "::" prefix.
WriteNode function, initiates the writing of a single SQLNode tree by passing through to Myprintf with a default format string
TupleEqualityList is for generating equality constraints for tables that have composite primary keys.
EncodeSQL generates the where clause constraints for the tuple equality.
type UnaryExpr struct { Operator string Expr Expr }
UnaryExpr represents a unary value expression.
Union represents a UNION statement.
AddOrder adds an order by element
SetLimit sets the limit clause
Update represents an UPDATE statement. If you add fields here, consider adding them to calls to validateSubquerySamePlan.
UpdateExpr represents an update expression.
UpdateExprs represents a list of update expressions.
Use represents a use statement.
ValTuple represents a tuple of actual values.
ValType specifies the type for SQLVal.
Values represents a VALUES clause.
type ValuesFuncExpr struct { Name *ColName }
ValuesFuncExpr represents a function call.
VindexParam defines a key/value parameter for a CREATE VINDEX statement
VindexSpec defines a vindex for a CREATE VINDEX or DROP VINDEX statement
Format formats the node. The "CREATE VINDEX" preamble was formatted in the containing DDL node Format, so this just prints the type, any parameters, and optionally the owner
ParseParams parses the vindex parameter list, pulling out the special-case "owner" parameter
Visit defines the signature of a function that can be used to visit all nodes of a parse tree.
When represents a WHEN sub-expression.
Where represents a WHERE or HAVING clause.
NewWhere creates a WHERE or HAVING clause out of a Expr. If the expression is nil, it returns nil.
RetroSearch is an open source project built by @garambo | Open a GitHub Issue
Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo
HTML:
3.2
| Encoding:
UTF-8
| Version:
0.7.4