sql

package
v0.19.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Dec 19, 2024 License: Apache-2.0 Imports: 40 Imported by: 167

Documentation

Index

Constants

View Source
const (
	ConnectionIdLogField = "connectionID"
	ConnectionDbLogField = "connectionDb"
	ConnectTimeLogKey    = "connectTime"
)
View Source
const (
	QFlagNull int = iota

	QFlagShowWarnings
	QFlagInsert
	QFlagUpdate
	QFlagDelete
	QFlagScalarSubquery
	QFlagRelSubquery
	QFlgNotExpr
	QFlagCount
	QFlagCountStar
	QFlagAlterTable
	QFlagCrossJoin
	QFlagSort
	QFlagFilter
	QFlagAggregation
	QFlagSetDatabase
	QFlagStar
	QFlagInnerJoin
	QFlagLimit
	QFlagInterval
	QFlagAnyAgg

	// QFlagMax1Row indicates that a query can only return at most one row
	QFlagMax1Row

	// QFlagDeferProjections indicates that a top-level projections for this query should be deferred and handled by
	// RowToSQL
	QFlagDeferProjections
	// QFlagUndeferrableExprs indicates that the query has expressions that cannot be deferred
	QFlagUndeferrableExprs
	QFlagTrigger
)

Most QFlags indicate the presence of a specific AST node. Flags with more complex meanings have more specific comments.

View Source
const (
	CurrentDBSessionVar  = "current_database"
	AutoCommitSessionVar = "autocommit"
)
View Source
const (
	RowCount       = "row_count"
	FoundRows      = "found_rows"
	LastInsertId   = "last_insert_id"
	LastInsertUuid = "last_insert_uuid"
)
View Source
const (
	SqlModeSessionVar = "SQL_MODE"

	ANSI                 = "ANSI"
	ANSIQuotes           = "ANSI_QUOTES"
	OnlyFullGroupBy      = "ONLY_FULL_GROUP_BY"
	NoAutoValueOnZero    = "NO_AUTO_VALUE_ON_ZERO"
	NoEngineSubstitution = "NO_ENGINE_SUBSTITUTION"
	StrictTransTables    = "STRICT_TRANS_TABLES"
	DefaultSqlMode       = "NO_ENGINE_SUBSTITUTION,ONLY_FULL_GROUP_BY,STRICT_TRANS_TABLES"
)
View Source
const (
	IndexClassDefault = iota
	IndexClassSpatial
	IndexClassFulltext
)
View Source
const (
	// DateLayout is the layout of the MySQL date format in the representation
	// Go understands.
	DateLayout = "2006-01-02"

	// TimestampDatetimeLayout is the formatting string with the layout of the timestamp
	// using the format of Go "time" package.
	TimestampDatetimeLayout = "2006-01-02 15:04:05.999999"

	// DatetimeLayoutNoTrim is the formatting string with the layout of the datetime that
	// doesn't trim trailing zeros
	DatetimeLayoutNoTrim = "2006-01-02 15:04:05.000000"
)
View Source
const (
	// False is the numeric representation of False as defined by MySQL.
	False = int8(0)
	// True is the numeric representation of True as defined by MySQL.
	True = int8(1)
)
View Source
const ChecksumKey = "checksum"

ChecksumKey is the key in an index config to store the checksum.

View Source
const EventDateSpaceTimeFormat = "2006-01-02 15:04:05"
View Source
const IndexBatchSize = uint64(10000)

IndexBatchSize is the number of rows to save at a time when creating indexes.

View Source
const (
	// InformationSchemaDatabaseName is the name of the information schema database.
	InformationSchemaDatabaseName = "information_schema"
)
View Source
const MaxIdentifierLength = 64

MaxIdentifierLength is the maximum number of characters permissible in MySQL identifiers, like column or table names

View Source
const (
	// QueryKey to access query in the context.
	QueryKey key = iota
)

Variables

View Source
var (
	// ErrSyntaxError is returned when a syntax error in vitess is encountered.
	ErrSyntaxError = errors.NewKind("%s")

	// ErrUnsupportedFeature is thrown when a feature is not already supported
	ErrUnsupportedFeature = errors.NewKind("unsupported feature: %s")

	// ErrReadOnly is returned when the engine has been set to Read Only but a write operation was attempted.
	ErrReadOnly = errors.NewKind("database server is set to read only mode")

	// ErrInvalidSystemVariableValue is returned when a system variable is assigned a value that it does not accept.
	ErrInvalidSystemVariableValue = errors.NewKind("Variable '%s' can't be set to the value of '%v'")

	// ErrSystemVariableCodeFail is returned when failing to encode/decode a system variable.
	ErrSystemVariableCodeFail = errors.NewKind("unable to encode/decode value '%v' for '%s'")

	// ErrInvalidType is thrown when there is an unexpected type at some part of
	// the execution tree.
	ErrInvalidType = errors.NewKind("invalid type: %s")

	// ErrTableAlreadyExists is thrown when someone tries to create a
	// table with a name of an existing one
	ErrTableAlreadyExists = errors.NewKind("table with name %s already exists")

	// ErrTableNotFound is returned when the table is not available from the
	// current scope.
	ErrTableNotFound = errors.NewKind("table not found: %s")

	// ErrInvalidRefInView is returned when querying existing view that references non-existent table.
	// Creating new view or updating existing view to reference non-existent table/view do not apply here.
	ErrInvalidRefInView = errors.NewKind("View '%s.%s' references invalid table(s) or column(s) or function(s) or definer/invoker of view lack rights to use them")

	// ErrUnknownTable is returned when the non-table name is used for table actions.
	ErrUnknownTable = errors.NewKind("Unknown table '%s'")

	// ErrTableColumnNotFound is thrown when a column named cannot be found in scope
	ErrTableColumnNotFound = errors.NewKind("table %q does not have column %q")

	// ErrColumnNotFound is returned when the column does not exist in any
	// table in scope.
	ErrColumnNotFound = errors.NewKind("column %q could not be found in any table in scope")

	// ErrAmbiguousColumnName is returned when there is a column reference that
	// is present in more than one table.
	ErrAmbiguousColumnName = errors.NewKind("ambiguous column name %q, it's present in all these tables: %v")

	// ErrAmbiguousColumnOrAliasName is returned when a column or alias name can't be qualified to a table or alias definition
	ErrAmbiguousColumnOrAliasName = errors.NewKind("ambiguous column or alias name %q")

	// ErrAmbiguousColumnInOrderBy is returned when an order by column is ambiguous
	ErrAmbiguousColumnInOrderBy = errors.NewKind("Column %q in order clause is ambiguous")

	// ErrColumnExists is returned when an ALTER TABLE statement would create a duplicate column
	ErrColumnExists = errors.NewKind("Column %q already exists")

	// ErrCreateTableNotSupported is thrown when the database doesn't support table creation
	ErrCreateTableNotSupported = errors.NewKind("tables cannot be created on database %s")

	// ErrDropTableNotSupported is thrown when the database doesn't support dropping tables
	ErrDropTableNotSupported = errors.NewKind("tables cannot be dropped on database %s")

	// ErrRenameTableNotSupported is thrown when the database doesn't support renaming tables
	ErrRenameTableNotSupported = errors.NewKind("tables cannot be renamed on database %s")

	// ErrDatabaseCollationsNotSupported is thrown when a database does not allow updating its collation
	ErrDatabaseCollationsNotSupported = errors.NewKind("database %s does not support collation operations")

	// ErrTableCreatedNotFound is thrown when a table is created from CREATE TABLE but cannot be found immediately afterward
	ErrTableCreatedNotFound = errors.NewKind("table %q was created but could not be found")

	// ErrUnexpectedRowLength is thrown when the obtained row has more columns than the schema
	ErrUnexpectedRowLength = errors.NewKind("expected %d values, got %d")

	// ErrInvalidChildrenNumber is returned when the WithChildren method of a
	// node or expression is called with an invalid number of arguments.
	ErrInvalidChildrenNumber = errors.NewKind("%T: invalid children number, got %d, expected %d")

	// ErrInvalidExpressionNumber is returned when the WithExpression method of a node
	// is called with an invalid number of arguments.
	ErrInvalidExpressionNumber = errors.NewKind("%T: invalid expression number, got %d, expected %d")

	// ErrInvalidChildType is returned when the WithChildren method of a
	// node or expression is called with an invalid child type. This error is indicative of a bug.
	ErrInvalidChildType = errors.NewKind("%T: invalid child type, got %T, expected %T")

	// ErrInvalidJSONText is returned when a JSON string cannot be parsed or unmarshalled
	ErrInvalidJSONText = errors.NewKind("Invalid JSON text in argument %d to function %s: \"%s\"")

	// ErrInvalidJSONArgument is returned when a JSON function is called with a parameter that is not JSON or a string
	ErrInvalidJSONArgument = errors.NewKind("invalid data type for JSON data in argument %d to function %s; a JSON string or JSON type is required")

	// ErrDeleteRowNotFound is returned when row being deleted was not found
	ErrDeleteRowNotFound = errors.NewKind("row was not found when attempting to delete")

	// ErrDuplicateAliasOrTable should be returned when a query contains a duplicate alias / table name.
	ErrDuplicateAliasOrTable = errors.NewKind("Not unique table/alias: %s")

	// ErrPrimaryKeyViolation is returned when a primary key constraint is violated
	// This is meant to wrap a sql.UniqueKey error, which provides the key string
	ErrPrimaryKeyViolation = errors.NewKind("duplicate primary key given")

	// ErrUniqueKeyViolation is returned when a unique key constraint is violated
	// This is meant to wrap a sql.UniqueKey error, which provides the key string
	ErrUniqueKeyViolation = errors.NewKind("duplicate unique key given")

	// ErrMisusedAlias is returned when a alias is defined and used in the same projection.
	ErrMisusedAlias = errors.NewKind("column %q does not exist in scope, but there is an alias defined in" +
		" this projection with that name. Aliases cannot be used in the same projection they're defined in")

	// ErrInvalidAsOfExpression is returned when an expression for AS OF cannot be used
	ErrInvalidAsOfExpression = errors.NewKind("expression %s cannot be used in AS OF")

	// ErrIncompatibleDefaultType is returned when a provided default cannot be coerced into the type of the column
	ErrIncompatibleDefaultType = errors.NewKind("incompatible type for default value")

	// ErrColumnDefaultDatetimeOnlyFunc is returned when a non datetime/timestamp column attempts to declare now/current_timestamp as a default value literal.
	ErrColumnDefaultDatetimeOnlyFunc = errors.NewKind("only datetime/timestamp may declare default values of now()/current_timestamp() without surrounding parentheses")

	// ErrColumnDefaultSubquery is returned when a default value contains a subquery.
	ErrColumnDefaultSubquery = errors.NewKind("default value on column `%s` may not contain subqueries")

	// ErrInvalidColumnDefaultValue is returned when column default function value is not wrapped in parentheses for column types excluding datetime and timestamp
	ErrInvalidColumnDefaultValue = errors.NewKind("Invalid default value for '%s'")

	// ErrInvalidDefaultValueOrder is returned when a default value references a column that comes after it and contains a default expression.
	ErrInvalidDefaultValueOrder = errors.NewKind(`default value of column "%s" cannot refer to a column defined after it if those columns have an expression default value`)

	// ErrColumnDefaultReturnedNull is returned when a default expression evaluates to nil but the column is non-nullable.
	ErrColumnDefaultReturnedNull = errors.NewKind(`default value attempted to return null but column is non-nullable`)

	// ErrDropColumnReferencedInDefault is returned when a column cannot be dropped as it is referenced by another column's default value.
	ErrDropColumnReferencedInDefault = errors.NewKind(`cannot drop column "%s" as default value of column "%s" references it`)

	// ErrTriggersNotSupported is returned when attempting to create a trigger on a database that doesn't support them
	ErrTriggersNotSupported = errors.NewKind(`database "%s" doesn't support triggers`)

	// ErrTriggerCreateStatementInvalid is returned when a TriggerDatabase returns a CREATE TRIGGER statement that is invalid
	ErrTriggerCreateStatementInvalid = errors.NewKind(`Invalid CREATE TRIGGER statement: %s`)

	// ErrTriggerDoesNotExist is returned when a trigger does not exist.
	ErrTriggerDoesNotExist = errors.NewKind(`trigger "%s" does not exist`)

	// ErrTriggerTableInUse is returned when trigger execution calls for a table that invoked a trigger being updated by it
	ErrTriggerTableInUse = errors.NewKind("Can't update table %s in stored function/trigger because it is already used by statement which invoked this stored function/trigger")

	// ErrTriggerCannotBeDropped is returned when dropping a trigger would cause another trigger to reference a non-existent trigger.
	ErrTriggerCannotBeDropped = errors.NewKind(`trigger "%s" cannot be dropped as it is referenced by trigger "%s"`)

	// ErrStoredProceduresNotSupported is returned when attempting to create a stored procedure on a database that doesn't support them.
	ErrStoredProceduresNotSupported = errors.NewKind(`database "%s" doesn't support stored procedures`)

	// ErrVersionedStoredProceduresNotSupported is returned when attempting to retrieve a versioned stored procedure on a database that doesn't support them.
	ErrVersionedStoredProceduresNotSupported = errors.NewKind(`database "%s" doesn't support versioned stored procedures`)

	// ErrStoredProcedureAlreadyExists is returned when a stored procedure does not exist.
	ErrStoredProcedureAlreadyExists = errors.NewKind(`stored procedure "%s" already exists`)

	// ErrStoredProcedureDoesNotExist is returned when a stored procedure does not exist.
	ErrStoredProcedureDoesNotExist = errors.NewKind(`stored procedure "%s" does not exist`)

	// ErrProcedureCreateStatementInvalid is returned when a StoredProcedureDatabase returns a CREATE PROCEDURE statement that is invalid.
	ErrProcedureCreateStatementInvalid = errors.NewKind(`Invalid CREATE PROCEDURE statement: %s`)

	// ErrProcedureRecursiveCall is returned when a stored procedure has a CALL statement that refers to itself.
	ErrProcedureRecursiveCall = errors.NewKind("recursive CALL on stored procedure `%s`")

	// ErrProcedureNestedCallAsOf is returned when a stored procedure has a CALL ... AS OF statement, which is currently not allowed.
	ErrProcedureNestedCallAsOf = errors.NewKind("CALL ... AS OF in stored procedure `%s`")

	// ErrProcedureCallAsOfReadOnly is returned when a CALL ... AS OF statement attempts to modify a table.
	ErrProcedureCallAsOfReadOnly = errors.NewKind("CALL ... AS OF converts databases to read only")

	// ErrProcedureInvalidBodyStatement is returned when a stored procedure has a statement that is invalid inside of procedures.
	ErrProcedureInvalidBodyStatement = errors.NewKind("`%s` statements are invalid inside of stored procedures")

	// ErrExternalProcedureAmbiguousOverload is returned when an external stored procedure is overloaded and has two
	// functions with the same number of parameters.
	ErrExternalProcedureAmbiguousOverload = errors.NewKind("overloaded stored procedure `%s` may only have a single variant with `%d` parameters")

	// ErrExternalProcedureNonFunction is returned when an external stored procedure is given something other than the
	// expected function type.
	ErrExternalProcedureNonFunction = errors.NewKind("received `%T` in place of a function for an external stored procedure")

	// ErrExternalProcedureMissingContextParam is returned when an external stored procedure's first parameter is not
	// the context.
	ErrExternalProcedureMissingContextParam = errors.NewKind("external stored procedures require the first parameter to be the context")

	// ErrExternalProcedurePointerVariadic is returned when an external stored procedure's variadic parameter has a pointer type.
	ErrExternalProcedurePointerVariadic = errors.NewKind("an external stored procedures's variadiac parameter may not have a pointer type")

	// ErrExternalProcedureReturnTypes is returned when an external stored procedure's return types are incorrect.
	ErrExternalProcedureReturnTypes = errors.NewKind("external stored procedures must return a RowIter and error")

	// ErrExternalProcedureFirstReturn is returned when an external stored procedure's first return type is incorrect.
	ErrExternalProcedureFirstReturn = errors.NewKind("external stored procedures require the first return value to be the RowIter")

	// ErrExternalProcedureSecondReturn is returned when an external stored procedure's second return type is incorrect.
	ErrExternalProcedureSecondReturn = errors.NewKind("external stored procedures require the second return value to be the error")

	// ErrExternalProcedureInvalidParamType is returned when one of an external stored procedure's parameters have an
	// invalid type.
	ErrExternalProcedureInvalidParamType = errors.NewKind("external stored procedures do not support parameters with type `%s`")

	// ErrCallIncorrectParameterCount is returned when a CALL statement has the incorrect number of parameters.
	ErrCallIncorrectParameterCount = errors.NewKind("`%s` expected `%d` parameters but got `%d`")

	// ErrEventsNotSupported is returned when attempting to create an event on a database that doesn't support them.
	ErrEventsNotSupported = errors.NewKind("database '%s' doesn't support events")

	// ErrEventAlreadyExists is returned when an event does not exist.
	ErrEventAlreadyExists = errors.NewKind("Event '%s' already exists")

	// ErrEventDoesNotExist is returned when an event does not exist.
	ErrEventDoesNotExist = errors.NewKind("Event '%s' does not exist")

	// ErrUnknownEvent is returned when a query references an event that doesn't exist
	ErrUnknownEvent = errors.NewKind("Unknown event '%s'")

	// ErrEventCreateStatementInvalid is returned when an EventDatabase returns a CREATE EVENT statement that is invalid
	ErrEventCreateStatementInvalid = errors.NewKind(`Invalid CREATE TRIGGER statement: %s`)

	// ErrUnknownSystemVariable is returned when a query references a system variable that doesn't exist
	ErrUnknownSystemVariable = errors.NewKind(`Unknown system variable '%s'`)

	// ErrUnknownStatusVariable is returned when a query references a status variable that doesn't exist
	ErrUnknownStatusVariable = errors.NewKind(`Unknown status variable '%s'`)

	// ErrUnknownUserVariable is returned when a query references a user variable that doesn't exist
	ErrUnknownUserVariable = errors.NewKind(`Unknown user variable '%s'`)

	// ErrSystemVariableReadOnly is returned when attempting to set a value to a non-Dynamic system variable.
	ErrSystemVariableReadOnly = errors.NewKind(`Variable '%s' is a read only variable`)

	ErrSystemVariableReinitialized = errors.NewKind(`Variable '%s' was initialized more than 1x`)

	// ErrSystemVariableSessionOnly is returned when attempting to set a SESSION-only variable using SET GLOBAL.
	ErrSystemVariableSessionOnly = errors.NewKind(`Variable '%s' is a SESSION variable and can't be used with SET GLOBAL`)

	// ErrSystemVariableGlobalOnly is returned when attempting to set a GLOBAL-only variable using SET SESSION.
	ErrSystemVariableGlobalOnly = errors.NewKind(`Variable '%s' is a GLOBAL variable and should be set with SET GLOBAL`)

	// ErrUserVariableNoDefault is returned when attempting to set the default value on a user variable.
	ErrUserVariableNoDefault = errors.NewKind(`User variable '%s' does not have a default value`)

	// ErrInvalidUseOfOldNew is returned when a trigger attempts to make use of OLD or NEW references when they don't exist
	ErrInvalidUseOfOldNew = errors.NewKind("There is no %s row in on %s trigger")

	// ErrInvalidUpdateOfOldRow is returned when a trigger attempts to assign to an old row's value with SET
	ErrInvalidUpdateOfOldRow = errors.NewKind("Updating of old row is not allowed in trigger")

	// ErrInvalidUpdateInAfterTrigger is returned when a trigger attempts to assign to a new row in an AFTER trigger
	ErrInvalidUpdateInAfterTrigger = errors.NewKind("Updating of new row is not allowed in after trigger")

	// ErrUnknownColumn is returned when the given column is not found in referenced table
	ErrUnknownColumn = errors.NewKind("Unknown column '%s' in '%s'")

	// ErrUnboundPreparedStatementVariable is returned when a query is executed without a binding for one its variables.
	ErrUnboundPreparedStatementVariable = errors.NewKind(`unbound variable "%s" in query`)

	// ErrUnknownPreparedStatement is returned when an unknown query is executed.
	ErrUnknownPreparedStatement = errors.NewKind(`Unknown prepared statement handler (%s) given to EXECUTE`)

	// ErrTruncateReferencedFromForeignKey is returned when a table is referenced in a foreign key and TRUNCATE is called on it.
	ErrTruncateReferencedFromForeignKey = errors.NewKind("cannot truncate table %s as it is referenced in foreign key %s on table %s")

	// ErrInvalidColTypeDefinition is returned when a column type-definition has argument violations.
	ErrInvalidColTypeDefinition = errors.NewKind("column %s type definition is invalid: %s")

	// ErrDatabaseExists is returned when CREATE DATABASE attempts to create a database that already exists.
	ErrDatabaseExists = errors.NewKind("can't create database %s; database exists")

	// ErrDatabaseSchemaExists is returned when CREATE SCHEMA attempts to create a schema that already exists.
	ErrDatabaseSchemaExists = errors.NewKind("can't create schema %s; schema exists")

	// ErrDatabaseNoDatabaseSchemaSelectedCreate is returned when CREATE TABLE is called without a schema selected and one is required.
	ErrDatabaseNoDatabaseSchemaSelectedCreate = errors.NewKind("no schema has been selected to create in")

	// ErrInvalidDatabaseName is returned when a database name is invalid.
	ErrInvalidDatabaseName = errors.NewKind("invalid database name: %s")

	// ErrInvalidConstraintFunctionNotSupported is returned when a CONSTRAINT CHECK is called with an unsupported function expression.
	ErrInvalidConstraintFunctionNotSupported = errors.NewKind("Invalid constraint expression, function not supported: %s")

	// ErrInvalidConstraintSubqueryNotSupported is returned when a CONSTRAINT CHECK is called with a sub-query expression.
	ErrInvalidConstraintSubqueryNotSupported = errors.NewKind("Invalid constraint expression, sub-queries not supported: %s")

	// ErrCheckConstraintViolated is returned when a CONSTRAINT CHECK is called with a sub-query expression.
	ErrCheckConstraintViolated = errors.NewKind("Check constraint %q violated")

	// ErrCheckConstraintInvalidatedByColumnAlter is returned when an alter column statement would invalidate a check constraint.
	ErrCheckConstraintInvalidatedByColumnAlter = errors.NewKind("can't alter column %q because it would invalidate check constraint %q")

	// ErrColumnCountMismatch is returned when a view, derived table or common table expression has a declared column
	// list with a different number of columns than the schema of the table.
	ErrColumnCountMismatch = errors.NewKind("In definition of view, derived table or common table expression, SELECT list and column names list have different column counts")

	// ErrColValCountMismatch is returned when not all rows in values constructor are of equal length.
	ErrColValCountMismatch = errors.NewKind("Column count doesn't match value count at row %d")

	// ErrUuidUnableToParse is returned when a UUID is unable to be parsed.
	ErrUuidUnableToParse = errors.NewKind("unable to parse '%s' to UUID: %s")

	// ErrLoadDataCannotOpen is returned when a LOAD DATA operation is unable to open the file specified.
	ErrLoadDataCannotOpen = errors.NewKind("LOAD DATA is unable to open file: %s")

	// ErrLoadDataCharacterLength is returned when a symbol is of the wrong character length for a LOAD DATA operation.
	ErrLoadDataCharacterLength = errors.NewKind("%s must be 1 character long")

	// ErrJSONObjectAggNullKey is returned when JSON_OBJECTAGG is run on a table with NULL keys
	ErrJSONObjectAggNullKey = errors.NewKind("JSON documents may not contain NULL member names")

	// ErrDeclareConditionOrderInvalid is returned when a DECLARE ... CONDITION statement is at an invalid location.
	ErrDeclareConditionOrderInvalid = errors.NewKind("DECLARE ... CONDITION may only exist at the beginning of a BEGIN/END block")

	// ErrDeclareVariableOrderInvalid is returned when a DECLARE statement, for variables, is at an invalid location.
	ErrDeclareVariableOrderInvalid = errors.NewKind("DECLARE variables may only exist at the beginning of a BEGIN/END block")

	// ErrDeclareCursorOrderInvalid is returned when a DECLARE ... CURSOR statement is at an invalid location.
	ErrDeclareCursorOrderInvalid = errors.NewKind("DECLARE ... CURSOR may only exist at the beginning of a BEGIN/END block, following all variables and conditions")

	// ErrDeclareHandlerOrderInvalid is returned when a DECLARE ... HANDLER statement is at an invalid location.
	ErrDeclareHandlerOrderInvalid = errors.NewKind("DECLARE ... HANDLER may only exist at the beginning of a BEGIN/END block, following all variables, conditions, and cursors")

	// ErrDeclareConditionNotFound is returned when SIGNAL/RESIGNAL references a non-existent DECLARE CONDITION.
	ErrDeclareConditionNotFound = errors.NewKind("condition %s does not exist")

	// ErrDeclareConditionDuplicate is returned when a DECLARE CONDITION statement with the same name was declared in the current scope.
	ErrDeclareConditionDuplicate = errors.NewKind("duplicate condition '%s'")

	// ErrDeclareVariableDuplicate is returned when a DECLARE statement reuses an existing variable name in the current scope.
	ErrDeclareVariableDuplicate = errors.NewKind("duplicate variable '%s'")

	// ErrDeclareCursorDuplicate is returned when a DECLARE ... CURSOR statement reuses an existing name in the current scope.
	ErrDeclareCursorDuplicate = errors.NewKind("duplicate cursor '%s'")

	// ErrDeclareHandlerDuplicate is returned when a DECLARE ... HANDLER statement has a duplicate in the same block.
	ErrDeclareHandlerDuplicate = errors.NewKind("duplicate handler declared in the same block")

	// ErrDeclareHandlerUndo is returned when a DECLARE ... HANDLER statement has the UNDO action, which is currently unsupported.
	ErrDeclareHandlerUndo = errors.NewKind("DECLARE ... HANDLER does not support the UNDO action")

	// ErrLoopRedefinition is returned when a loop with the same label has already been declared in the current block.
	ErrLoopRedefinition = errors.NewKind("redefining label '%s'")

	// ErrLoopLabelNotFound is returned when a control flow statement references a non-existent loop.
	ErrLoopLabelNotFound = errors.NewKind("%s with no matching label: '%s'")

	// ErrCursorNotFound is returned when a CURSOR cannot be found.
	ErrCursorNotFound = errors.NewKind("cursor '%s' does not exist")

	// ErrCursorAlreadyOpen is returned when a CURSOR is already open.
	ErrCursorAlreadyOpen = errors.NewKind("cursor '%s' is already open")

	// ErrCursorNotOpen is returned when a CURSOR has not yet been opened.
	ErrCursorNotOpen = errors.NewKind("cursor '%s' is not open")

	// ErrFetchIncorrectCount is returned when a FETCH does not use the correct number of variables.
	ErrFetchIncorrectCount = errors.NewKind("incorrect number of FETCH variables")

	// ErrSignalOnlySqlState is returned when SIGNAL/RESIGNAL references a DECLARE CONDITION for a MySQL error code.
	ErrSignalOnlySqlState = errors.NewKind("SIGNAL/RESIGNAL can only use a condition defined with SQLSTATE")

	// ErrExpectedSingleRow is returned when a subquery executed in normal queries or aggregation function returns
	// more than 1 row without an attached IN clause.
	ErrExpectedSingleRow = errors.NewKind("the subquery returned more than 1 row")

	// ErrUnknownConstraint is returned when a DROP CONSTRAINT statement refers to a constraint that doesn't exist
	ErrUnknownConstraint = errors.NewKind("Constraint %q does not exist")

	// ErrInsertIntoNonNullableDefaultNullColumn is returned when an INSERT excludes a field which is non-nullable and has no default/autoincrement.
	ErrInsertIntoNonNullableDefaultNullColumn = errors.NewKind("Field '%s' doesn't have a default value")

	// ErrAlterTableNotSupported is thrown when the table doesn't support ALTER TABLE statements
	ErrAlterTableNotSupported = errors.NewKind("table %s cannot be altered")

	// ErrAlterTableCollationNotSupported is thrown when the table doesn't support ALTER TABLE COLLATE statements
	ErrAlterTableCollationNotSupported = errors.NewKind("table %s cannot have its collation altered")

	// ErrCollationNotSupportedOnUniqueTextIndex is thrown when a unique index is created on a TEXT column, with no
	// prefix length specified, and the collation is case-insensitive or accent-insensitive, meaning we can't
	// reliably use a content-hashed field to detect uniqueness.
	ErrCollationNotSupportedOnUniqueTextIndex = errors.NewKind("unable to create a unique index on TEXT columns without " +
		"a prefix length specified when using a case-insensitive or accent-insensitive collation")

	// ErrPartitionNotFound is thrown when a partition key on a table is not found
	ErrPartitionNotFound = errors.NewKind("partition not found %q")

	// ErrInsertIntoNonNullableProvidedNull is called when a null value is inserted into a non-nullable column
	ErrInsertIntoNonNullableProvidedNull = errors.NewKind("column name '%v' is non-nullable but attempted to set a value of null")

	// ErrForeignKeyChildViolation is called when a rows is added but there is no parent row, and a foreign key constraint fails. Add the parent row first.
	ErrForeignKeyChildViolation = errors.NewKind("cannot add or update a child row - Foreign key violation on fk: `%s`, table: `%s`, referenced table: `%s`, key: `%s`")

	// ErrForeignKeyParentViolation is called when a parent row that is deleted has children, and a foreign key constraint fails. Delete the children first.
	ErrForeignKeyParentViolation = errors.NewKind("cannot delete or update a parent row - Foreign key violation on fk: `%s`, table: `%s`, referenced table: `%s`, key: `%s`")

	// ErrForeignKeyColumnCountMismatch is called when the declared column and referenced column counts do not match.
	ErrForeignKeyColumnCountMismatch = errors.NewKind("the foreign key must reference an equivalent number of columns")

	// ErrForeignKeyColumnTypeMismatch is returned when the declared column's type and referenced column's type do not match.
	ErrForeignKeyColumnTypeMismatch = errors.NewKind("column type mismatch on `%s` and `%s`")

	// ErrForeignKeyNotResolved is called when an add or update is attempted on a foreign key that has not been resolved yet.
	ErrForeignKeyNotResolved = errors.NewKind("cannot add or update a child row: a foreign key constraint fails (`%s`.`%s`, CONSTRAINT `%s` FOREIGN KEY (`%s`) REFERENCES `%s` (`%s`))")

	// ErrNoForeignKeySupport is returned when the table does not support FOREIGN KEY operations.
	ErrNoForeignKeySupport = errors.NewKind("the table does not support foreign key operations: %s")

	// ErrForeignKeyMissingColumns is returned when an ALTER TABLE ADD FOREIGN KEY statement does not provide any columns
	ErrForeignKeyMissingColumns = errors.NewKind("cannot create a foreign key without columns")

	// ErrForeignKeyDropColumn is returned when attempting to drop a column used in a foreign key
	ErrForeignKeyDropColumn = errors.NewKind("cannot drop column `%s` as it is used in foreign key `%s`")

	// ErrForeignKeyDropTable is returned when attempting to drop a table used in a foreign key
	ErrForeignKeyDropTable = errors.NewKind("cannot drop table `%s` as it is referenced in foreign key `%s`")

	// ErrForeignKeyDropIndex is returned when attempting to drop an index used in a foreign key when there are no other
	// indexes which may be used in its place.
	ErrForeignKeyDropIndex = errors.NewKind("cannot drop index: `%s` is used by foreign key `%s`")

	// ErrForeignKeyDuplicateName is returned when a foreign key already exists with the given name.
	ErrForeignKeyDuplicateName = errors.NewKind("duplicate foreign key constraint name `%s`")

	// ErrAddForeignKeyDuplicateColumn is returned when an ALTER TABLE ADD FOREIGN KEY statement has the same column multiple times
	ErrAddForeignKeyDuplicateColumn = errors.NewKind("cannot have duplicates of columns in a foreign key: `%v`")

	// ErrTemporaryTablesForeignKeySupport is returned when a user tries to create a temporary table with a foreign key
	ErrTemporaryTablesForeignKeySupport = errors.NewKind("temporary tables do not support foreign keys")

	// ErrForeignKeyNotFound is returned when a foreign key was not found.
	ErrForeignKeyNotFound = errors.NewKind("foreign key `%s` was not found on the table `%s`")

	// ErrForeignKeySetDefault is returned when attempting to set a referential action as SET DEFAULT.
	ErrForeignKeySetDefault = errors.NewKind(`"SET DEFAULT" is not supported`)

	// ErrForeignKeySetNullNonNullable is returned when attempting to set a referential action as SET NULL when the
	// column is non-nullable.
	ErrForeignKeySetNullNonNullable = errors.NewKind("cannot use SET NULL as column `%s` is non-nullable")

	// ErrForeignKeyTypeChangeSetNull is returned when attempting to change a column's type to disallow NULL values when
	// a foreign key referential action is SET NULL.
	ErrForeignKeyTypeChangeSetNull = errors.NewKind("column `%s` must allow NULL values as foreign key `%s` has SET NULL")

	// ErrForeignKeyMissingReferenceIndex is returned when the referenced columns in a foreign key do not have an index.
	ErrForeignKeyMissingReferenceIndex = errors.NewKind("missing index for foreign key `%s` on the referenced table `%s`")

	// ErrForeignKeyTextBlob is returned when a TEXT or BLOB column is used in a foreign key, which are not valid types.
	ErrForeignKeyTextBlob = errors.NewKind("TEXT/BLOB are not valid types for foreign keys")

	// ErrForeignKeyTypeChange is returned when attempting to change the type of some column used in a foreign key.
	ErrForeignKeyTypeChange = errors.NewKind("unable to change type of column `%s` as it is used by foreign keys")

	// ErrForeignKeyDepthLimit is returned when the CASCADE depth limit has been reached.
	ErrForeignKeyDepthLimit = errors.NewKind("Foreign key cascade delete/update exceeds max depth of 15.")

	// ErrDuplicateKey is returned when a duplicate key is defined on a table.
	ErrDuplicateKey = errors.NewKind("Duplicate key name '%s'")

	// ErrDuplicateEntry is returns when a duplicate entry is placed on an index such as a UNIQUE or a Primary Key.
	ErrDuplicateEntry = errors.NewKind("Duplicate entry for key '%s'")

	// ErrDuplicateColumn is returned when a table has two columns with the same name.
	ErrDuplicateColumn = errors.NewKind("duplicate column name: `%s`")

	// ErrInvalidIdentifier is returned when an identifier is invalid
	ErrInvalidIdentifier = errors.NewKind("invalid identifier: `%s`")

	// ErrInvalidArgument is returned when an argument to a function is invalid.
	ErrInvalidArgument = errors.NewKind("Invalid argument to %s")

	// ErrInvalidArgumentType is thrown when a function receives invalid argument types
	ErrInvalidArgumentType = errors.NewKind("function '%s' received invalid argument types")

	// ErrInvalidArgumentDetails is returned when the argument is invalid with details of a specific function
	ErrInvalidArgumentDetails = errors.NewKind("Invalid argument to %s: %s")

	// ErrSavepointDoesNotExist is returned when a RELEASE SAVEPOINT or ROLLBACK TO SAVEPOINT statement references a
	// non-existent savepoint identifier
	ErrSavepointDoesNotExist = errors.NewKind("SAVEPOINT %s does not exist")

	// ErrTemporaryTableNotSupported is thrown when an integrator attempts to create a temporary tables without temporary table
	// support.
	ErrTemporaryTableNotSupported = errors.NewKind("database does not support temporary tables")

	// ErrInvalidSyntax is returned for syntax errors that aren't picked up by the parser, e.g. the wrong type of
	// expression used in part of statement.
	ErrInvalidSyntax = errors.NewKind("Invalid syntax: %s")

	// ErrTableCopyingNotSupported is returned when a table invokes the TableCopierDatabase interface's
	// CopyTableData method without supporting the interface
	ErrTableCopyingNotSupported = errors.NewKind("error: Table copying not supported")

	// ErrMultiplePrimaryKeysDefined is returned when a table invokes CreatePrimaryKey with a primary key already
	// defined.
	ErrMultiplePrimaryKeysDefined = errors.NewKind("error: Multiple primary keys defined")

	// ErrWrongAutoKey is returned when a table invokes DropPrimaryKey without first removing the auto increment property
	// (if it exists) on it.
	ErrWrongAutoKey = errors.NewKind("error: incorrect table definition: there can be only one auto column and it must be defined as a key")

	// ErrKeyColumnDoesNotExist is returned when a table invoked CreatePrimaryKey with a non-existent column.
	ErrKeyColumnDoesNotExist = errors.NewKind("key column '%s' doesn't exist in table")

	// ErrCantDropFieldOrKey is returned when a table invokes DropPrimaryKey on a keyless table.
	ErrCantDropFieldOrKey = errors.NewKind("error: can't drop '%s'; check that column/key exists")

	// ErrCantDropIndex is return when a table can't drop an index due to a foreign key relationship.
	ErrCantDropIndex = errors.NewKind("error: can't drop index '%s': needed in foreign key constraint %s")

	// ErrImmutableDatabaseProvider is returned when attempting to edit an immutable database databaseProvider.
	ErrImmutableDatabaseProvider = errors.NewKind("error: can't modify database databaseProvider")

	// ErrInvalidValue is returned when a given value does not match what is expected.
	ErrInvalidValue = errors.NewKind(`error: '%v' is not a valid value for '%v'`)

	// ErrInvalidValueType is returned when a given value's type does not match what is expected.
	ErrInvalidValueType = errors.NewKind(`error: '%T' is not a valid value type for '%v'`)

	// ErrFunctionNotFound is thrown when a function is not found
	ErrFunctionNotFound = errors.NewKind("function: '%s' not found")

	// ErrConflictingExternalQuery is thrown when a scope's parent has a conflicting sort or limit node
	ErrConflictingExternalQuery = errors.NewKind("found external scope with conflicting ORDER BY/LIMIT")

	// ErrTableFunctionNotFound is thrown when a table function is not found
	ErrTableFunctionNotFound = errors.NewKind("table function: '%s' not found")

	// ErrNonAggregatedColumnWithoutGroupBy is thrown when an aggregate function is used with the implicit, all-rows
	// grouping and another projected expression contains a non-aggregated column.
	// MySQL error code: 1140, SQL state: 42000
	ErrNonAggregatedColumnWithoutGroupBy = errors.NewKind("in aggregated query without GROUP BY, expression #%d of SELECT list contains nonaggregated column '%s'; " +
		"this is incompatible with sql_mode=only_full_group_by")

	// ErrInvalidArgumentNumber is returned when the number of arguments to call a
	// function is different from the function arity.
	ErrInvalidArgumentNumber = errors.NewKind("function '%s' expected %v arguments, %v received")

	// ErrDatabaseNotFound is thrown when a database is not found
	ErrDatabaseNotFound = errors.NewKind("database not found: %s")

	// ErrDatabaseSchemaNotFound is thrown when a database schema is not found
	ErrDatabaseSchemaNotFound = errors.NewKind("database schema not found: %s")

	// ErrDatabaseSchemasNotSupported is thrown when a database does not support schemas
	ErrDatabaseSchemasNotSupported = errors.NewKind("database '%s' does not support schemas")

	// ErrNoDatabaseSelected is thrown when a database is not selected and the query requires one
	ErrNoDatabaseSelected = errors.NewKind("no database selected")

	// ErrAsOfNotSupported is thrown when an AS OF query is run on a database that can't support it
	ErrAsOfNotSupported = errors.NewKind("AS OF not supported for database %s")

	// ErrIncompatibleAsOf is thrown when an AS OF clause is used in an incompatible manner, such as when using an AS OF
	// expression with a view when the view definition has its own AS OF expressions.
	ErrIncompatibleAsOf = errors.NewKind("incompatible use of AS OF: %s")

	// ErrPidAlreadyUsed is returned when the pid is already registered.
	ErrPidAlreadyUsed = errors.NewKind("pid %d is already in use")

	// ErrInvalidOperandColumns is returned when the columns in the left
	// operand and the elements of the right operand don't match. Also
	// returned for invalid number of columns in projections, filters,
	// joins, etc.
	ErrInvalidOperandColumns = errors.NewKind("operand should have %d columns, but has %d")

	// ErrReadOnlyTransaction is returned when a write query is executed in a READ ONLY transaction.
	ErrReadOnlyTransaction = errors.NewKind("cannot execute statement in a READ ONLY transaction")

	// ErrLockDeadlock is the go-mysql-server equivalent of ER_LOCK_DEADLOCK. Transactions throwing this error
	// are automatically rolled back. Clients receiving this error must retry the transaction.
	ErrLockDeadlock = errors.NewKind("serialization failure: %s, try restarting transaction.")

	// ErrViewCreateStatementInvalid is returned when a ViewDatabase returns a CREATE VIEW statement that is invalid
	ErrViewCreateStatementInvalid = errors.NewKind(`Invalid CREATE VIEW statement: %s`)

	// ErrViewsNotSupported is returned when attempting to access a view on a database that doesn't support them.
	ErrViewsNotSupported = errors.NewKind("database '%s' doesn't support views")

	// ErrExpectedTableFoundView is returned when attempting to rename a view using ALTER TABLE statement.
	ErrExpectedTableFoundView = errors.NewKind("expected a table and found view: '%s' ")

	// ErrExistingView is returned when a CREATE VIEW statement uses a name that already exists
	ErrExistingView = errors.NewKind("the view %s.%s already exists")

	// ErrViewDoesNotExist is returned when a DROP VIEW statement drops a view that does not exist
	ErrViewDoesNotExist = errors.NewKind("the view %s.%s does not exist")

	// ErrSessionDoesNotSupportPersistence is thrown when a feature is not already supported
	ErrSessionDoesNotSupportPersistence = errors.NewKind("session does not support persistence")

	// ErrInvalidGISData is thrown when a "ST_<spatial_type>FromText" function receives a malformed string
	ErrInvalidGISData = errors.NewKind("invalid GIS data provided to function %s")

	// ErrIllegalGISValue is thrown when a spatial type constructor receives a non-geometric when one should be provided
	ErrIllegalGISValue = errors.NewKind("illegal non geometric '%v' value found during parsing")

	// ErrDiffSRIDs is thrown when comparing two spatial types that have different SRIDs when they should be the same
	ErrDiffSRIDs = errors.NewKind("binary geometry function %s given two geometries of different srids: %v and %v, which should have been identical")

	// ErrUnsupportedSRID is thrown for spatial functions over unsupported SRIDs
	ErrUnsupportedSRID = errors.NewKind("SRID %v has not been implemented for geographic spatial reference systems.")

	// ErrSRIDOnNonGeomCol is thrown when attempting to define SRID over a non-geometry column
	ErrSRIDOnNonGeomCol = errors.NewKind("incorrect usage of SRID and non-geometry column")

	// ErrTooManyKeyParts is thrown when creating an index with too many columns
	ErrTooManyKeyParts = errors.NewKind("too many key parts specified; max %d parts allowed")

	// ErrNullableSpatialIdx is thrown when creating a SPATIAL index with a nullable column
	ErrNullableSpatialIdx = errors.NewKind("All parts of a SPATIAL index must be NOT NULL")

	// ErrBadSpatialIdxCol is thrown when attempting to define a SPATIAL index over a non-geometry column
	ErrBadSpatialIdxCol = errors.NewKind("a SPATIAL index may only contain a geometrical type column")

	// ErrNoSRID is thrown when attempting to create a Geometry with a non-existent SRID
	ErrNoSRID = errors.NewKind("There's no spatial reference with SRID %d")

	// ErrInvalidSRID is thrown when attempting to create a Geometry with an invalid SRID
	ErrInvalidSRID = errors.NewKind("SRID value is out of range in %s")

	// ErrSpatialRefSysAlreadyExists is thrown when attempting to create a spatial reference system with an existing SRID
	ErrSpatialRefSysAlreadyExists = errors.NewKind("There is already a spatial reference system with SRID %v")

	// ErrUnsupportedGISTypeForSpatialFunc is a temporary error because geometry is hard
	// TODO: remove this error when all types are full supported by spatial type functions
	ErrUnsupportedGISTypeForSpatialFunc = errors.NewKind("unsupported spatial type: %s for function %s")

	// ErrUnsupportedGISType is thrown when attempting to convert an unsupported geospatial value to a geometry struct
	ErrUnsupportedGISType = errors.NewKind("unsupported geospatial type: %s from value: 0x%s")

	// ErrUnsupportedSyntax is returned when syntax that parses correctly is not supported
	ErrUnsupportedSyntax = errors.NewKind("unsupported syntax: %s")

	// ErrInvalidSQLValType is returned when a SQL value is of the incorrect type during parsing
	ErrInvalidSQLValType = errors.NewKind("invalid SQLVal of type: %d")

	// ErrUnknownIndexColumn is returned when a column in an index is not in the table
	ErrUnknownIndexColumn = errors.NewKind("unknown column: '%s' in index '%s'")

	// ErrInvalidAutoIncCols is returned when an auto_increment column cannot be applied
	ErrInvalidAutoIncCols = errors.NewKind("there can be only one auto_increment column and it must be defined as a key")

	// ErrUnknownConstraintDefinition is returned when an unknown constraint type is used
	ErrUnknownConstraintDefinition = errors.NewKind("unknown constraint definition: %s, %T")

	// ErrInvalidCheckConstraint is returned when a check constraint is defined incorrectly
	ErrInvalidCheckConstraint = errors.NewKind("invalid constraint definition: %s")

	// ErrUserCreationFailure is returned when attempting to create a user and it fails for any reason.
	ErrUserCreationFailure = errors.NewKind("Operation CREATE USER failed for %s")

	// ErrUserNameTooLong is returned when a CREATE USER statement uses a name that is longer than 32 chars.
	ErrUserNameTooLong = errors.NewKind("String '%s' is too long for user name (should be no longer than 32)")

	// ErrUserHostTooLong is returned when a CREATE USER statement uses a host that is longer than 255 chars.
	ErrUserHostTooLong = errors.NewKind("String '%s' is too long for host name (should be no longer than 255)")

	// ErrUserAlterFailure is returned when attempting to alter a user and it fails for any reason.
	ErrUserAlterFailure = errors.NewKind("Operation ALTER USER failed for %s")

	// ErrRoleCreationFailure is returned when attempting to create a role and it fails for any reason.
	ErrRoleCreationFailure = errors.NewKind("Operation CREATE ROLE failed for %s")

	// ErrUserDeletionFailure is returned when attempting to create a user and it fails for any reason.
	ErrUserDeletionFailure = errors.NewKind("Operation DROP USER failed for %s")

	// ErrRoleDeletionFailure is returned when attempting to create a role and it fails for any reason.
	ErrRoleDeletionFailure = errors.NewKind("Operation DROP ROLE failed for %s")

	// ErrDatabaseAccessDeniedForUser is returned when attempting to access a database that the user does not have
	// permission for, regardless of whether that database actually exists.
	ErrDatabaseAccessDeniedForUser = errors.NewKind("Access denied for user %s to database '%s'")

	// ErrTableAccessDeniedForUser is returned when attempting to access a table that the user does not have permission
	// for, regardless of whether that table actually exists.
	ErrTableAccessDeniedForUser = errors.NewKind("Access denied for user %s to table '%s'")

	// ErrPrivilegeCheckFailed is returned when a user does not have the correct privileges to perform an operation.
	ErrPrivilegeCheckFailed = errors.NewKind("command denied to user %s")

	// ErrGrantUserDoesNotExist is returned when a user does not exist when attempting to grant them privileges.
	ErrGrantUserDoesNotExist = errors.NewKind("You are not allowed to create a user with GRANT")

	// ErrRevokeUserDoesNotExist is returned when a user does not exist when attempting to revoke privileges from them.
	ErrRevokeUserDoesNotExist = errors.NewKind("There is no such grant defined for user '%s' on host '%s'")

	// ErrGrantRevokeRoleDoesNotExist is returned when a user or role does not exist when attempting to grant or revoke roles.
	ErrGrantRevokeRoleDoesNotExist = errors.NewKind("Unknown authorization ID %s")

	// ErrShowGrantsUserDoesNotExist is returned when a user does not exist when attempting to show their grants.
	ErrShowGrantsUserDoesNotExist = errors.NewKind("There is no such grant defined for user '%s' on host '%s'")

	// ErrRecursiveCTEMissingUnion is returned when a recursive CTE is not a UNION or UNION ALL node.
	ErrRecursiveCTEMissingUnion = errors.NewKind("Recursive Common Table Expression '%s' should contain a UNION")

	// ErrRecursiveCTENotUnion is returned when an INTERSECT or EXCEPT includes a Recursive CTE.
	ErrRecursiveCTENotUnion = errors.NewKind("Recursive table reference in EXCEPT or INTERSECT operand is not allowed")

	// ErrCteRecursionLimitExceeded is returned when a recursive CTE's execution stack depth exceeds the static limit.
	ErrCteRecursionLimitExceeded = errors.NewKind("WITH RECURSIVE iteration limit exceeded")

	// ErrGrantRevokeIllegalPrivilege is returned when a GRANT or REVOKE statement is malformed, or attempts to use privilege incorrectly.
	ErrGrantRevokeIllegalPrivilege = errors.NewKind("Illegal GRANT/REVOKE command")

	// ErrGrantRevokeIllegalPrivilegeWithMessage is returned when a GRANT or REVOKE statement is malformed, or attempts
	// to use privilege incorrectly and an additional message needs to be provided to the user.
	ErrGrantRevokeIllegalPrivilegeWithMessage = errors.NewKind("Illegal GRANT/REVOKE command: %s")

	// ErrInvalidWindowInheritance is returned when a window and its dependency contains conflicting partitioning, ordering, or framing clauses
	ErrInvalidWindowInheritance = errors.NewKind("window '%s' cannot inherit '%s' since %s")

	// ErrCircularWindowInheritance is returned when a WINDOW clause has a circular dependency
	ErrCircularWindowInheritance = errors.NewKind("there is a circularity in the window dependency graph")

	// ErrCannotCopyWindowFrame is returned when we inherit a window frame with a frame clause (replacement without parenthesis is OK)
	ErrCannotCopyWindowFrame = errors.NewKind("cannot copy window '%s' because it has a frame clause")

	// ErrUnknownWindowName is returned when an over by clause references an unknown window definition
	ErrUnknownWindowName = errors.NewKind("named window not found: '%s'")

	// ErrUnexpectedNilRow is returned when an invalid operation is applied to an empty row
	ErrUnexpectedNilRow = errors.NewKind("unexpected nil row")

	// ErrMoreThanOneRow is returned when the result consists of multiple rows, when only one row is expected
	ErrMoreThanOneRow = errors.NewKind("Result consisted of more than one row")

	// ErrColumnNumberDoesNotMatch is returned when the number of columns in result does not match expected number of variables
	ErrColumnNumberDoesNotMatch = errors.NewKind("The used SELECT statements have a different number of columns")

	// ErrUnsupportedJoinFactorCount is returned for a query with more commutable join tables than we support
	ErrUnsupportedJoinFactorCount = errors.NewKind("unsupported join factor count: expected fewer than %d tables, found %d")

	// ErrSecureFilePriv is returned when an outfile/dumpfile path is invalid or not under the secure-file-priv directory
	ErrSecureFilePriv = errors.NewKind("The MySQL server is running with the --secure-file-priv option so it cannot execute this statement")

	// ErrFileExists is returned when a file already exists
	ErrFileExists = errors.NewKind("File '%s' already exists")

	// ErrUnexpectedSeparator is returned when an invalid separator is used
	ErrUnexpectedSeparator = errors.NewKind("Field separator argument is not what is expected; check the manual")

	// ErrNotMatchingSRID is returned for SRID values not matching
	ErrNotMatchingSRID = errors.NewKind("The SRID of the geometry is %v, but the SRID of the column is %v. Consider changing the SRID of the geometry or the SRID property of the column.")

	// ErrNotMatchingSRIDWithColName is returned for error of SRID values not matching with column name detail
	ErrNotMatchingSRIDWithColName = errors.NewKind("The SRID of the geometry does not match the SRID of the column '%s'. %v")

	// ErrSpatialTypeConversion is returned when one spatial type cannot be converted to the other spatial type
	ErrSpatialTypeConversion = errors.NewKind("Cannot get geometry object from data you sent to the GEOMETRY field")

	// ErrUnsupportedIndexPrefix is returned for an index on a string column with a prefix
	ErrUnsupportedIndexPrefix = errors.NewKind("prefix index on string column '%s' unsupported")

	// ErrInvalidIndexPrefix is returned for an index prefix on a non-string column, or the prefix is longer than string itself, or just unsupported
	ErrInvalidIndexPrefix = errors.NewKind("incorrect prefix key '%s'; the used key part isn't a string, the used length is longer than the key part, or the storage engine doesn't support unique prefix keys")

	// ErrInvalidBlobTextKey is returned for an index on a blob or text column with no key length specified
	ErrInvalidBlobTextKey = errors.NewKind("blob/text column '%s' used in key specification without a key length")

	// ErrKeyTooLong is returned for an index on a blob or text column that is longer than 3072 bytes
	ErrKeyTooLong = errors.NewKind("specified key was too long; max key length is 3072 bytes")

	// ErrKeyZero is returned for an index on a blob or text column that is 0 in length
	ErrKeyZero = errors.NewKind("key part '%s' length cannot be 0")

	// ErrDatabaseWriteLocked is returned when a database is locked in read-only mode to avoid
	// conflicts with an active server
	ErrDatabaseWriteLocked = errors.NewKind("database is locked to writes")

	// ErrCollationMalformedString is returned when a malformed string is encountered during a collation-related operation.
	ErrCollationMalformedString = errors.NewKind("malformed string encountered while %s")

	// ErrCollatedExprWrongType is returned when the wrong type is given to a CollatedExpression.
	ErrCollatedExprWrongType = errors.NewKind("wrong type in collated expression")

	// ErrCollationInvalidForCharSet is returned when the wrong collation is given for the character set when parsing.
	ErrCollationInvalidForCharSet = errors.NewKind("COLLATION '%s' is not valid for CHARACTER SET '%s'")

	// ErrCollationUnknown is returned when the collation is not a recognized MySQL collation.
	ErrCollationUnknown = errors.NewKind("Unknown collation: %v")

	// ErrCollationNotYetImplementedTemp is returned when the collation is valid but has not yet been implemented.
	// This error is temporary, and will be removed once all collations have been added.
	ErrCollationNotYetImplementedTemp = errors.NewKind("The collation `%s` has not yet been implemented, " +
		"please create an issue at https://github.com/dolthub/go-mysql-server/issues/new and the DoltHub developers will implement it")

	// ErrCollationIllegalMix is returned when two different collations are used in a scenario where they are not compatible.
	ErrCollationIllegalMix = errors.NewKind("Illegal mix of collations (%v) and (%v)")

	// ErrCharSetIntroducer is returned when a character set introducer is not attached to a string
	ErrCharSetIntroducer = errors.NewKind("CHARACTER SET introducer must be attached to a string")

	// ErrCharSetInvalidString is returned when an invalid string is given for a character set.
	ErrCharSetInvalidString = errors.NewKind("invalid string for character set `%s`: \"%s\"")

	// ErrCharSetFailedToEncode is returned when a character set fails encoding
	ErrCharSetFailedToEncode = errors.NewKind("failed to encode: `%s`, valid string: `%v`, snippet: `%s`")

	// ErrCharSetUnknown is returned when the character set is not a recognized MySQL character set
	ErrCharSetUnknown = errors.NewKind("Unknown character set: %v")

	// ErrCharSetNotYetImplementedTemp is returned when the character set is valid but has not yet been implemented.
	// This error is temporary, and will be removed once all character sets have been added.
	ErrCharSetNotYetImplementedTemp = errors.NewKind("The character set `%s` has not yet been implemented, " +
		"please create an issue at https://github.com/dolthub/go-mysql-server/issues/new and the DoltHub developers will implement it")

	// ErrNoTablesUsed is returned when there is no table provided or dual table is defined with column access.
	ErrNoTablesUsed = errors.NewKind("No tables used")

	// ErrInvalidJson is returned when a JSON string doesn't represent valid JSON.
	ErrInvalidJson = errors.NewKind("Invalid JSON text: %s")

	// ErrNoAutoIncrementCol is returned when there is no auto increment column defined on a table.
	ErrNoAutoIncrementCol = fmt.Errorf("this table has no AUTO_INCREMENT columns")

	// ErrValueOutOfRange is returned when a value is out of range for a type.
	ErrValueOutOfRange = errors.NewKind("%v out of range for %v")

	ErrConvertingToSet   = errors.NewKind("value %v is not valid for this set")
	ErrDuplicateEntrySet = errors.NewKind("duplicate entry: %v")
	ErrInvalidSetValue   = errors.NewKind("value %v was not found in the set")
	ErrTooLargeForSet    = errors.NewKind(`value "%v" is too large for this set`)
	ErrNotPoint          = errors.NewKind("value of type %T is not a point")
	ErrNotLineString     = errors.NewKind("value of type %T is not a linestring")

	// ErrMergeJoinExpectsComparerFilters is returned when we attempt to build a merge join with an invalid filter.
	ErrMergeJoinExpectsComparerFilters = errors.NewKind("merge join expects expression.Comparer filters, found: %T")

	// ErrNoJoinFilters is returned when we attempt to build a filtered join without filters
	ErrNoJoinFilters = errors.NewKind("join expected non-nil filters")

	// ErrDroppedJoinFilters is returned when we removed filters from a join, but failed to re-insert them
	ErrDroppedJoinFilters = errors.NewKind("dropped filters from join, but failed to re-insert them")

	// ErrInvalidIndexName is called when we try to create an index with an unusable name.
	ErrInvalidIndexName = errors.NewKind("invalid index name '%s'")

	// ErrStarUnsupported is called for * expressions seen outside: raw projections, count(*), and arrayagg(*)
	ErrStarUnsupported = errors.NewKind(
		"a '*' is in a context where it is not allowed.",
	)

	// ErrAggregationUnsupported is returned when the analyzer has failed
	// to push down an Aggregation in an expression to a GroupBy node.
	ErrAggregationUnsupported = errors.NewKind(
		"an aggregation remained in the expression '%s' after analysis, outside of a node capable of evaluating it; this query is currently unsupported.",
	)

	ErrWindowUnsupported = errors.NewKind(
		"a window function '%s' is in a context where it cannot be evaluated.",
	)

	// ErrFullTextNotSupported is returned when a table does not support the creation of Full-Text indexes.
	ErrFullTextNotSupported = errors.NewKind("table does not support FULLTEXT indexes")

	// ErrFullTextDatabaseNotSupported is returned when a database does not support the creation of Full-Text indexes.
	ErrFullTextDatabaseNotSupported = errors.NewKind("database does not support FULLTEXT indexes")

	// ErrIncompleteFullTextIntegration is returned when some portions of Full-Text are implemented but not all of them
	ErrIncompleteFullTextIntegration = errors.NewKind("proper Full-Text support requires all interfaces to be implemented")

	// ErrNoFullTextIndexFound is returned when the relevant Full-Text index cannot be found.
	ErrNoFullTextIndexFound = errors.NewKind("no matching Full-Text index found on table `%s`")

	// ErrFullTextMatchAgainstNotColumns is returned when the provided MATCH(...) columns are not column names.
	ErrFullTextMatchAgainstNotColumns = errors.NewKind("match columns must be column names")

	// ErrFullTextMatchAgainstSameTable is returned when the provided MATCH(...) columns belong to different tables.
	ErrFullTextMatchAgainstSameTable = errors.NewKind("match columns must refer to the same table")

	// ErrFullTextDifferentCollations is returned when creating a Full-Text index on columns that have different collations.
	ErrFullTextDifferentCollations = errors.NewKind("Full-Text index columns must have the same collation")

	// ErrFullTextMissingColumn is returned when a Full-Text column cannot be found.
	ErrFullTextMissingColumn = errors.NewKind("Full-Text index could not find the column `%s`")

	// ErrFullTextDuplicateColumn is returned when a Full-Text index declares the same column multiple times.
	ErrFullTextDuplicateColumn = errors.NewKind("cannot have duplicate columns in a Full-Text index: `%s`")

	// ErrFullTextInvalidColumnType is returned when a Full-Text index is declared on a non-text column.
	ErrFullTextInvalidColumnType = errors.NewKind("all Full-Text columns must be declared on a non-binary text type")

	// ErrGeneratedColumnValue is returned when a value is provided for a generated column
	ErrGeneratedColumnValue = errors.NewKind("The value specified for generated column %q in table %q is not allowed.")

	// ErrVirtualColumnPrimaryKey is returned when a virtual column is defined as a primary key
	ErrVirtualColumnPrimaryKey = errors.NewKind("Defining a virtual generated column as primary key is not supported")

	// ErrGeneratedColumnWithDefault is returned when a column specifies both a default and a generated value
	ErrGeneratedColumnWithDefault = errors.NewKind("Incorrect usage of DEFAULT and generated column")

	// ErrJSONIndex is returned when attempting to create an index over a JSON column directly
	ErrJSONIndex = errors.NewKind("JSON column '%s' supports indexing only via generated columns on a specified JSON path")

	ErrInvalidOnUpdate = errors.NewKind("Invalid ON UPDATE clause for '%s' column")

	ErrInsertIntoMismatchValueCount = errors.NewKind("number of values does not match number of columns provided")

	ErrInvalidTypeForLimit = errors.NewKind("invalid limit. expected %T, found %T")

	ErrColumnSpecifiedTwice = errors.NewKind("column '%v' specified twice")

	ErrEnumTypeTruncated = errors.NewKind("new enum type change truncates value")
)
View Source
var (
	ErrInvalidColExpr      = errors.NewKind("the expression `%s` could not be found from the index `%s`")
	ErrRangeSimplification = errors.NewKind("attempting to simplify ranges has removed all ranges")
	ErrInvalidRangeType    = errors.NewKind("encountered the RangeType_Invalid")
)
View Source
var (
	// ErrIndexIDAlreadyRegistered is the error returned when there is already
	// an index with the same ID.
	ErrIndexIDAlreadyRegistered = errors.NewKind("an index with id %q has already been registered")

	// ErrIndexExpressionAlreadyRegistered is the error returned when there is
	// already an index with the same expression.
	ErrIndexExpressionAlreadyRegistered = errors.NewKind("there is already an index registered for the expressions: %s")

	// ErrIndexNotFound is returned when the index could not be found.
	ErrIndexNotFound = errors.NewKind("index %q	was not found")

	// ErrIndexDeleteInvalidStatus is returned when the index trying to delete
	// does not have a ready or outdated state.
	ErrIndexDeleteInvalidStatus = errors.NewKind("can't delete index %q because it's not ready for removal")
)
View Source
var (
	// ErrNodeNotWritten is returned when the children are printed before the node.
	ErrNodeNotWritten = errors.New("treeprinter: a child was written before the node")
	// ErrNodeAlreadyWritten is returned when the node has already been written.
	ErrNodeAlreadyWritten = errors.New("treeprinter: node already written")
	// ErrChildrenAlreadyWritten is returned when the children have already been written.
	ErrChildrenAlreadyWritten = errors.New("treeprinter: children already written")
)
View Source
var (
	// ErrNotTuple is returned when the value is not a tuple.
	ErrNotTuple = errors.NewKind("value of type %T is not a tuple")

	// ErrInvalidColumnNumber is returned when a tuple has an invalid number of
	// arguments.
	ErrInvalidColumnNumber = errors.NewKind("tuple should contain %d column(s), but has %d")

	ErrInvalidBaseType = errors.NewKind("%v is not a valid %v base type")

	// ErrConvertToSQL is returned when Convert failed.
	// It makes an error less verbose comparing to what spf13/cast returns.
	ErrConvertToSQL = errors.NewKind("incompatible conversion to SQL type: '%v'->%s")
)
View Source
var ErrCannotAddToClosedBackgroundThreads = errors.New("cannot add to a close background threads instance")
View Source
var ErrIncorrectValue = errors.NewKind("Incorrect %s value: '%s'")
View Source
var ErrKeyNotFound = fmt.Errorf("memory: key not found in cache")

ErrKeyNotFound is returned when the key could not be found in the cache.

View Source
var ErrLockDoesNotExist = errors.NewKind("Lock '%s' does not exist.")

ErrLockDoesNotExist is the kind of error returned when a named lock does not exist and the operation does not created it

View Source
var ErrLockNotOwned = errors.NewKind("Operation '%s' failed as the lock '%s' has a different owner.")

ErrLockNotOwned is the kind of error returned when attempting an operation against a lock that the given context does not own.

View Source
var ErrLockTimeout = errors.NewKind("Timeout acquiring lock '%s'.")

ErrLockTimeout is the kind of error returned when acquiring a lock takes longer than the user specified timeout

View Source
var ErrNoMemoryAvailable = errors.NewKind("no memory available")

ErrNoMemoryAvailable is returned when there is no more available memory.

View Source
var ErrUnableSort = errors.NewKind("unable to sort")

ErrUnableSort is thrown when something happens on sorting

View Source
var (
	// ErrUnexpectedType is thrown when a received type is not the expected
	ErrUnexpectedType = errors.NewKind("value at %d has unexpected type: %s")
)
View Source
var NoopTracer = trace.NewNoopTracerProvider().Tracer("github.com/dolthub/go-mysql-server/sql")
View Source
var SupportedCharsets = []CharacterSetID{
	CharacterSet_utf8mb4,
}

SupportedCharsets contains all non-binary character sets that are currently supported.

View Source
var SupportedEngines = []Engine{
	{Name: "InnoDB", /* contains filtered or unexported fields */},
}

Functions

func CastSQLError added in v0.9.0

func CastSQLError(err error) *mysql.SQLError

CastSQLError returns a *mysql.SQLError with the error code and in some cases, also a SQL state, populated for the specified error object. Using this method enables Vitess to return an error code, instead of just "unknown error". Many tools (e.g. ORMs, SQL workbenches) rely on this error metadata to work correctly. If the specified error is nil, nil will be returned. If the error is already of type *mysql.SQLError, the error will be returned as is.

func ConvertToBool

func ConvertToBool(ctx *Context, v interface{}) (bool, error)

ConvertToBool converts a value to a boolean. nil is considered false.

func ConvertToVector added in v0.19.0

func ConvertToVector(v interface{}) ([]float64, error)

func DBTableIter

func DBTableIter(ctx *Context, db Database, cb func(Table) (cont bool, err error)) error

DBTableIter iterates over all tables returned by db.GetTableNames() calling cb for each one until all tables have been processed, or an error is returned from the callback, or the cont flag is false when returned from the callback.

func DebugString

func DebugString(nodeOrExpression interface{}) string

DebugString returns a debug string for the Node or Expression given.

func Describe added in v0.18.0

func Describe(n fmt.Stringer, options DescribeOptions) string

Describe produces a human-readable string for |n|, based on the values set in |options|. For |n| to benefit from |options|, it must implement `sql.Describable`.

func Dispose added in v0.11.0

func Dispose(i interface{})

func EvaluateCondition

func EvaluateCondition(ctx *Context, cond Expression, row Row) (interface{}, error)

EvaluateCondition evaluates a condition, which is an expression whose value will be nil or coerced boolean.

func FormatRow

func FormatRow(row Row) string

FormatRow returns a formatted string representing this row's values

func GenerateCreateTableCheckConstraintClause added in v0.15.0

func GenerateCreateTableCheckConstraintClause(checkName, checkExpr string, enforced bool) string

GenerateCreateTableCheckConstraintClause returns check constraint clause string for 'CREATE TABLE' statement for given check constraint. This part comes the last and after foreign key definitions if there are any.

func GenerateCreateTableColumnDefinition added in v0.15.0

func GenerateCreateTableColumnDefinition(col *Column, colDefault, onUpdate string, tableCollation CollationID) string

GenerateCreateTableColumnDefinition returns column definition string for 'CREATE TABLE' statement for given column. This part comes first in the 'CREATE TABLE' statement.

func GenerateCreateTableForiegnKeyDefinition added in v0.15.0

func GenerateCreateTableForiegnKeyDefinition(fkName string, fkCols []string, parentTbl string, parentCols []string, onDelete, onUpdate string) string

GenerateCreateTableForiegnKeyDefinition returns foreign key constraint definition string for 'CREATE TABLE' statement for given foreign key. This part comes after index definitions if there are any.

func GenerateCreateTableIndexDefinition added in v0.15.0

func GenerateCreateTableIndexDefinition(isUnique, isSpatial, isFullText, isVector bool, indexID string, indexCols []string, comment string) string

GenerateCreateTableIndexDefinition returns index definition string for 'CREATE TABLE' statement for given index. This part comes after primary key definition if there is any.

func GenerateCreateTablePrimaryKeyDefinition added in v0.15.0

func GenerateCreateTablePrimaryKeyDefinition(pkCols []string) string

GenerateCreateTablePrimaryKeyDefinition returns primary key definition string for 'CREATE TABLE' statement for given column(s). This part comes after each column definitions.

func GenerateCreateTableStatement added in v0.15.0

func GenerateCreateTableStatement(tblName string, colStmts []string, autoInc, tblCharsetName, tblCollName, comment string) string

GenerateCreateTableStatement returns 'CREATE TABLE' statement with given table names and column definition statements in order and the collation and character set names for the table

func GetMySQLRangeCutKey added in v0.19.0

func GetMySQLRangeCutKey(c MySQLRangeCut) interface{}

GetMySQLRangeCutKey returns the inner value from the given MySQLRangeCut.

func GetTableNameInsensitive

func GetTableNameInsensitive(tblName string, tableNames []string) (string, bool)

GetTableNameInsensitive implements a case-insensitive search of a slice of table names. It looks for exact matches first. If no exact matches are found then any table matching the name case insensitively should be returned. If there is more than one table that matches a case-insensitive comparison the resolution strategy is not defined.

func GetTimeValueFromStringInput added in v0.18.0

func GetTimeValueFromStringInput(field, t string) (time.Time, error)

GetTimeValueFromStringInput returns time.Time in system timezone (SYSTEM = time.Now().Location()). evaluating valid MySQL datetime and timestamp formats.

func HasAvailableMemory

func HasAvailableMemory(r Reporter) bool

HasAvailableMemory reports whether more memory is available to the program if it hasn't reached the max memory limit.

func HasDefaultValue

func HasDefaultValue(ctx *Context, s Session, key string) (bool, interface{})

HasDefaultValue checks if session variable value is the default one.

func HashOf

func HashOf(v Row) (uint64, error)

HashOf returns a hash of the given value to be used as key in a cache.

func IncrementStatusVariable added in v0.18.1

func IncrementStatusVariable(ctx *Context, name string, val int)

IncrementStatusVariable increments the value of the status variable by integer val. |name| is case-sensitive.

func Inspect

func Inspect(expr Expression, f func(expr Expression) bool)

Inspect traverses the plan in depth-first order: It starts by calling f(expr); expr must not be nil. If f returns true, Inspect invokes f recursively for each of the children of expr, followed by a call of f(nil).

func IsFalse added in v0.10.0

func IsFalse(val interface{}) bool

IsFalse coerces EvaluateCondition interface{} response to boolean

func IsKeyless added in v0.11.0

func IsKeyless(s Schema) bool

func IsTrue added in v0.10.0

func IsTrue(val interface{}) bool

IsTrue coerces EvaluateCondition interface{} response to boolean

func MustConvert added in v0.9.0

func MustConvert(val interface{}, _ ConvertInRange, err error) interface{}

func MySQLRangeCutIsBinding added in v0.19.0

func MySQLRangeCutIsBinding(c MySQLRangeCut) bool

func NewMapCache

func NewMapCache() mapCache

func NewUniqueKeyErr added in v0.10.0

func NewUniqueKeyErr(keyStr string, isPK bool, existing Row) error

func Now added in v0.15.0

func Now() time.Time

func OrderedCuts added in v0.12.0

func OrderedCuts(l, r MySQLRangeCut, typ Type) (MySQLRangeCut, MySQLRangeCut, error)

OrderedCuts returns the given Cuts in order from lowest-touched values to highest-touched values.

func QuoteIdentifier added in v0.15.0

func QuoteIdentifier(id string) string

QuoteIdentifier wraps the specified identifier in backticks and escapes all occurrences of backticks in the identifier by replacing them with double backticks.

func QuoteIdentifiers added in v0.15.0

func QuoteIdentifiers(ids []string) []string

QuoteIdentifiers wraps each of the specified identifiers in backticks, escapes all occurrences of backticks in the identifier, and returns a slice of the quoted identifiers.

func RemoveSpaceAndDelimiter added in v0.19.0

func RemoveSpaceAndDelimiter(query string, d rune) string

RemoveSpaceAndDelimiter removes space characters and given delimiter characters from the given query.

func RunWithNowFunc

func RunWithNowFunc(nowFunc func() time.Time, fn func() error) error

func SetAuthorizationHandlerFactory added in v0.19.0

func SetAuthorizationHandlerFactory(factory AuthorizationHandlerFactory)

SetAuthorizationHandlerFactory sets the desired authorization factory. Defaults to the factory that expects an AST that was generated by Vitess. This factory is used when creating a sql.Catalog, so it must be changed before the creation of a catalog. If set to nil, then all auth-related queries will succeed.

func UnwrapError added in v0.14.0

func UnwrapError(err error) error

UnwrapError removes any wrapping errors (e.g. WrappedInsertError) around the specified error and returns the first non-wrapped error type.

func ValidatePrimaryKeyDrop added in v0.18.0

func ValidatePrimaryKeyDrop(ctx *Context, t IndexAddressableTable, oldSchema PrimaryKeySchema) error

ValidatePrimaryKeyDrop validates that a primary key may be dropped. If any validation error is returned, then it means it is not valid to drop this table's primary key. Validation includes checking for PK columns with the auto_increment property, in which case, MySQL requires that another index exists on the table where the first column in the index is the auto_increment column from the primary key. https://dev.mysql.com/doc/refman/8.0/en/innodb-auto-increment-handling.html

func Walk

func Walk(v Visitor, expr Expression)

Walk traverses the expression tree in depth-first order. It starts by calling v.Visit(expr); expr must not be nil. If the visitor returned by v.Visit(expr) is not nil, Walk is invoked recursively with the returned visitor for each children of the expr, followed by a call of v.Visit(nil) to the returned visitor.

func WalkWithNode

func WalkWithNode(v NodeVisitor, n Node, expr Expression)

WalkWithNode traverses the expression tree in depth-first order. It starts by calling v.Visit(node, expr); expr must not be nil. If the visitor returned by v.Visit(node, expr) is not nil, Walk is invoked recursively with the returned visitor for each children of the expr, followed by a call of v.Visit(nil, nil) to the returned visitor.

Types

type Above added in v0.12.0

type Above struct {
	Key interface{}
}

Above represents the position immediately above the contained key.

func (Above) Compare added in v0.12.0

func (a Above) Compare(c MySQLRangeCut, typ Type) (int, error)

Compare implements MySQLRangeCut.

func (Above) String added in v0.12.0

func (a Above) String() string

String implements MySQLRangeCut.

func (Above) TypeAsLowerBound added in v0.12.0

func (Above) TypeAsLowerBound() MySQLRangeBoundType

TypeAsLowerBound implements MySQLRangeCut.

func (Above) TypeAsUpperBound added in v0.12.0

func (Above) TypeAsUpperBound() MySQLRangeBoundType

TypeAsUpperBound implements MySQLRangeCut.

type AboveAll added in v0.12.0

type AboveAll struct{}

AboveAll represents the position beyond the maximum possible value.

func (AboveAll) Compare added in v0.12.0

func (AboveAll) Compare(c MySQLRangeCut, typ Type) (int, error)

Compare implements MySQLRangeCut.

func (AboveAll) String added in v0.12.0

func (AboveAll) String() string

String implements MySQLRangeCut.

func (AboveAll) TypeAsLowerBound added in v0.12.0

func (AboveAll) TypeAsLowerBound() MySQLRangeBoundType

TypeAsLowerBound implements MySQLRangeCut.

func (AboveAll) TypeAsUpperBound added in v0.12.0

func (AboveAll) TypeAsUpperBound() MySQLRangeBoundType

TypeAsUpperBound implements MySQLRangeCut.

type AboveNull added in v0.14.0

type AboveNull struct{}

AboveNull represents the position just above NULL, lower than every possible value in the domain.

func (AboveNull) Compare added in v0.14.0

func (AboveNull) Compare(c MySQLRangeCut, typ Type) (int, error)

Compare implements MySQLRangeCut.

func (AboveNull) String added in v0.14.0

func (AboveNull) String() string

String implements MySQLRangeCut.

func (AboveNull) TypeAsLowerBound added in v0.14.0

func (AboveNull) TypeAsLowerBound() MySQLRangeBoundType

TypeAsLowerBound implements MySQLRangeCut.

func (AboveNull) TypeAsUpperBound added in v0.14.0

func (AboveNull) TypeAsUpperBound() MySQLRangeBoundType

TypeAsUpperBound implements MySQLRangeCut.

type Aggregation

type Aggregation interface {
	WindowAdaptableExpression
	// NewBuffer creates a new aggregation buffer and returns it as a Row.
	NewBuffer() (AggregationBuffer, error)
}

Aggregation implements an aggregation expression, where an aggregation buffer is created for each grouping (NewBuffer). Rows for the grouping should be fed to the buffer with |Update| and the buffer should be eval'd with |Eval|. Calling |Eval| directly on an Aggregation expression is typically an error.

type AggregationBuffer added in v0.11.0

type AggregationBuffer interface {
	Disposable

	// Eval the given buffer.
	Eval(*Context) (interface{}, error)
	// Update the given buffer with the given row.
	Update(ctx *Context, row Row) error
}

type AliasedDatabase added in v0.16.0

type AliasedDatabase interface {
	Database

	// AliasedName returns the alias (the underlying name for information_schema, privileges) for this database.
	AliasedName() string
}

AliasedDatabase is a database that has an alias: a name that is different from the name to be used system tables such as information_schema, or the mysql grant tables. This is the case when an integrator supports multiple ways to address a single physical database, but all such names should resolve to the same underlying name for permission checks.

type AlterableTable

type AlterableTable interface {
	Table
	UpdatableTable

	// AddColumn adds a column to this table as given. If non-nil, order
	// specifies where in the schema to add the column.
	AddColumn(ctx *Context, column *Column, order *ColumnOrder) error
	// DropColumn drops the column with the name given.
	DropColumn(ctx *Context, columnName string) error
	// ModifyColumn modifies the column with the name given, replacing
	// with the new column definition provided (which may include a name
	// change). If non-nil, order specifies where in the schema to move
	// the column.
	ModifyColumn(ctx *Context, columnName string, column *Column, order *ColumnOrder) error
}

AlterableTable should be implemented by tables that can receive ALTER TABLE statements to modify their schemas.

type AnalyzerVersion added in v0.16.0

type AnalyzerVersion uint8
const (
	VersionUnknown AnalyzerVersion = iota
	VersionStable
	VersionExperimental
)

type AuthorizationCheckerNode added in v0.19.0

type AuthorizationCheckerNode interface {
	Node
	// CheckAuth performs any authorization needed for the node, returning true if authorization succeeded.
	CheckAuth(ctx *Context, checker PrivilegedOperationChecker) bool
}

AuthorizationCheckerNode is a node that implements its own authorization checking.

type AuthorizationHandler added in v0.19.0

type AuthorizationHandler interface {
	// NewQueryState returns some kind of state that should be retained for an entire query. This is for the purposes of
	// optimization. If nothing needs to be retained between calls for a single query, then it is valid for this to
	// return nil. If an error occurs, then the state should contain the error so that it may be returned in HandleAuth.
	NewQueryState(ctx *Context) AuthorizationQueryState
	// HandleAuth checks whether the authentication information is valid. The state may be nil, therefore this function
	// may need to internally construct the state if a nil one is provided.
	HandleAuth(ctx *Context, state AuthorizationQueryState, auth ast.AuthInformation) error
	// HandleAuthNode handles the authentication of nodes that implement AuthorizationCheckerNode. These are often used
	// by integrators that do not modify the AST, and instead prefer a node-based form of authentication.
	HandleAuthNode(ctx *Context, state AuthorizationQueryState, node AuthorizationCheckerNode) error
	// CheckDatabase returns nil when access to the given database is permitted. If the database name is empty, it
	// should be assumed that the context's current database is being checked.
	CheckDatabase(ctx *Context, state AuthorizationQueryState, dbName string) error
	// CheckSchema returns nil when access to the given schema is permitted. If the database or schema name is empty,
	// it should be assumed that the context's current database and schema are being checked.
	CheckSchema(ctx *Context, state AuthorizationQueryState, dbName string, schemaName string) error
	// CheckTable returns nil when access to the given table is permitted. If the database or schema name is empty,
	// it should be assumed that the context's current database and schema are being checked. Should return an error if
	// the table name is empty.
	CheckTable(ctx *Context, state AuthorizationQueryState, dbName string, schemaName string, tableName string) error
}

AuthorizationHandler handles the authorization of queries, generally through the use of a privilege system. This handler exists to create handlers that will operate on a single query.

type AuthorizationHandlerFactory added in v0.19.0

type AuthorizationHandlerFactory interface {
	// CreateHandler creates an AuthorizationHandler from the given catalog.
	CreateHandler(cat Catalog) AuthorizationHandler
}

AuthorizationHandlerFactory creates an AuthorizationHandler, which will be used for all authorization needs.

func GetAuthorizationHandlerFactory added in v0.19.0

func GetAuthorizationHandlerFactory() AuthorizationHandlerFactory

GetAuthorizationHandlerFactory returns the global AuthorizationHandlerFactory that was set using SetAuthorizationHandlerFactory.

type AuthorizationQueryState added in v0.19.0

type AuthorizationQueryState interface {
	// Error returns the error contained within the state if one exists, otherwise returns nil.
	Error() error
	// AuthorizationQueryStateImpl has no actual usage besides enforcing that the returned object adheres to this
	// interface.
	AuthorizationQueryStateImpl()
}

AuthorizationQueryState contains any state that should be retained for an entire query, so that it is loaded once and then reused. If an error was created in NewQueryState, then that error should be retained here and returned in HandleAuth.

type AutoIncrementSetter

type AutoIncrementSetter interface {
	// SetAutoIncrementValue sets a new AUTO_INCREMENT value.
	SetAutoIncrementValue(*Context, uint64) error

	// AcquireAutoIncrementLock acquires (if necessary) an exclusive lock on generating auto-increment values for the underlying table.
	// This is called when @@innodb_autoinc_lock_mode is set to 0 (traditional) or 1 (consecutive), in order to guarentee that insert
	// operations get a consecutive range of generated ids. The function returns a callback to release the lock.
	AcquireAutoIncrementLock(ctx *Context) (func(), error)
	// Closer finalizes the set operation, persisting the result.
	Closer
}

AutoIncrementSetter provides support for altering a table's AUTO_INCREMENT sequence, eg 'ALTER TABLE t AUTO_INCREMENT = 10;'

type AutoIncrementTable

type AutoIncrementTable interface {
	Table
	// PeekNextAutoIncrementValue returns the next AUTO_INCREMENT value without incrementing the current
	// auto_increment counter.
	PeekNextAutoIncrementValue(ctx *Context) (uint64, error)
	// GetNextAutoIncrementValue gets the next AUTO_INCREMENT value. In the case that a table with an autoincrement
	// column is passed in a row with the autoinc column failed, the next auto increment value must
	// update its internal state accordingly and use the insert val at runtime.
	// Implementations are responsible for updating their state to provide the correct values.
	GetNextAutoIncrementValue(ctx *Context, insertVal interface{}) (uint64, error)
	// AutoIncrementSetter returns an AutoIncrementSetter.
	AutoIncrementSetter(*Context) AutoIncrementSetter
}

AutoIncrementTable is a table that supports AUTO_INCREMENT. Getter and Setter methods access the table's AUTO_INCREMENT sequence. These methods should only be used for tables with and AUTO_INCREMENT column in their schema.

type BackgroundThreads added in v0.12.0

type BackgroundThreads struct {
	// contains filtered or unexported fields
}

func NewBackgroundThreads added in v0.12.0

func NewBackgroundThreads() *BackgroundThreads

func (*BackgroundThreads) Add added in v0.12.0

func (bt *BackgroundThreads) Add(name string, f func(ctx context.Context)) error

Add starts a background goroutine wrapped by a top-level sync.WaitGroup. [f] must return when its [ctx] argument is cancelled, otherwise Shutdown will hang.

func (*BackgroundThreads) Shutdown added in v0.12.0

func (bt *BackgroundThreads) Shutdown() error

Shutdown cancels the parent context for every async thread, and waits for each goroutine to drain and return before exiting.

type BaseSession

type BaseSession struct {
	// contains filtered or unexported fields
}

BaseSession is the basic session implementation. Integrators should typically embed this type into their custom session implementations to get base functionality.

func BaseSessionFromConnection added in v0.18.1

func BaseSessionFromConnection(ctx context.Context, c *mysql.Conn, addr string) (*BaseSession, error)

BaseSessionFromConnection is a SessionBuilder that returns a base session for the given connection and remote address

func NewBaseSession

func NewBaseSession() *BaseSession

NewBaseSession creates a new empty session.

func NewBaseSessionWithClientServer added in v0.12.0

func NewBaseSessionWithClientServer(server string, client Client, id uint32) *BaseSession

NewBaseSessionWithClientServer creates a new session with data.

func (*BaseSession) AddLock

func (s *BaseSession) AddLock(lockName string) error

AddLock adds a lock to the set of locks owned by this user which will need to be released if this session terminates

func (*BaseSession) Address

func (s *BaseSession) Address() string

Address returns the server address.

func (*BaseSession) ClearWarningCount added in v0.19.0

func (s *BaseSession) ClearWarningCount()

ClearWarningCount cleans up session warnings

func (*BaseSession) ClearWarnings

func (s *BaseSession) ClearWarnings()

ClearWarnings cleans up session warnings

func (*BaseSession) Client

func (s *BaseSession) Client() Client

Client returns session's client information.

func (*BaseSession) DelLock

func (s *BaseSession) DelLock(lockName string) error

DelLock removes a lock from the set of locks owned by this user

func (*BaseSession) GetAllSessionVariables added in v0.10.0

func (s *BaseSession) GetAllSessionVariables() map[string]interface{}

GetAllSessionVariables implements the Session interface.

func (*BaseSession) GetAllStatusVariables added in v0.18.1

func (s *BaseSession) GetAllStatusVariables(_ *Context) map[string]StatusVarValue

GetAllStatusVariables implements the Session interface.

func (*BaseSession) GetCharacterSet added in v0.14.0

func (s *BaseSession) GetCharacterSet() CharacterSetID

GetCharacterSet returns the character set for this session (defined by the system variable `character_set_connection`).

func (*BaseSession) GetCharacterSetResults added in v0.14.0

func (s *BaseSession) GetCharacterSetResults() CharacterSetID

GetCharacterSetResults returns the result character set for this session (defined by the system variable `character_set_results`).

func (*BaseSession) GetCollation added in v0.14.0

func (s *BaseSession) GetCollation() CollationID

GetCollation returns the collation for this session (defined by the system variable `collation_connection`).

func (*BaseSession) GetCurrentDatabase

func (s *BaseSession) GetCurrentDatabase() string

GetCurrentDatabase gets the current database for this session

func (*BaseSession) GetIgnoreAutoCommit added in v0.10.0

func (s *BaseSession) GetIgnoreAutoCommit() bool

func (*BaseSession) GetIndexRegistry added in v0.11.0

func (s *BaseSession) GetIndexRegistry() *IndexRegistry

func (*BaseSession) GetLastQueryInfoInt added in v0.18.1

func (s *BaseSession) GetLastQueryInfoInt(key string) int64

func (*BaseSession) GetLastQueryInfoString added in v0.18.1

func (s *BaseSession) GetLastQueryInfoString(key string) string

func (*BaseSession) GetLogger added in v0.11.0

func (s *BaseSession) GetLogger() *logrus.Entry

func (*BaseSession) GetPrivilegeSet added in v0.15.0

func (s *BaseSession) GetPrivilegeSet() (PrivilegeSet, uint64)

func (*BaseSession) GetQueriedDatabase added in v0.9.0

func (s *BaseSession) GetQueriedDatabase() string

GetQueriedDatabase implements the Session interface.

func (*BaseSession) GetSessionVariable added in v0.10.0

func (s *BaseSession) GetSessionVariable(ctx *Context, sysVarName string) (interface{}, error)

GetSessionVariable implements the Session interface.

func (*BaseSession) GetStatusVariable added in v0.18.1

func (s *BaseSession) GetStatusVariable(_ *Context, statVarName string) (interface{}, error)

GetStatusVariable implements the Session interface.

func (*BaseSession) GetTransaction added in v0.10.0

func (s *BaseSession) GetTransaction() Transaction

func (*BaseSession) GetTransactionDatabase added in v0.15.0

func (s *BaseSession) GetTransactionDatabase() string

func (*BaseSession) GetUserVariable added in v0.10.0

func (s *BaseSession) GetUserVariable(ctx *Context, varName string) (Type, interface{}, error)

GetUserVariable implements the Session interface.

func (*BaseSession) GetViewRegistry added in v0.11.0

func (s *BaseSession) GetViewRegistry() *ViewRegistry

func (*BaseSession) ID

func (s *BaseSession) ID() uint32

ID implements the Session interface.

func (*BaseSession) IncrementStatusVariable added in v0.18.1

func (s *BaseSession) IncrementStatusVariable(ctx *Context, statVarName string, val int)

IncrementStatusVariable implements the Session interface.

func (*BaseSession) InitSessionVariable added in v0.14.0

func (s *BaseSession) InitSessionVariable(ctx *Context, sysVarName string, value interface{}) error

InitSessionVariable implements the Session interface and is used to initialize variables (Including read-only variables)

func (*BaseSession) IterLocks

func (s *BaseSession) IterLocks(cb func(name string) error) error

IterLocks iterates through all locks owned by this user

func (*BaseSession) LockWarnings added in v0.19.0

func (s *BaseSession) LockWarnings()

LockWarnings locks the session warnings so that they can't be cleared

func (*BaseSession) SetClient added in v0.12.0

func (s *BaseSession) SetClient(c Client)

SetClient implements the Session interface.

func (*BaseSession) SetConnectionId added in v0.12.0

func (s *BaseSession) SetConnectionId(id uint32)

SetConnectionId sets the [id] for this session

func (*BaseSession) SetCurrentDatabase

func (s *BaseSession) SetCurrentDatabase(dbName string)

SetCurrentDatabase sets the current database for this session

func (*BaseSession) SetIgnoreAutoCommit added in v0.10.0

func (s *BaseSession) SetIgnoreAutoCommit(ignore bool)

func (*BaseSession) SetIndexRegistry added in v0.11.0

func (s *BaseSession) SetIndexRegistry(reg *IndexRegistry)

func (*BaseSession) SetLastQueryInfoInt added in v0.18.1

func (s *BaseSession) SetLastQueryInfoInt(key string, value int64)

func (*BaseSession) SetLastQueryInfoString added in v0.18.1

func (s *BaseSession) SetLastQueryInfoString(key string, value string)

func (*BaseSession) SetLogger added in v0.11.0

func (s *BaseSession) SetLogger(logger *logrus.Entry)

func (*BaseSession) SetPrivilegeSet added in v0.15.0

func (s *BaseSession) SetPrivilegeSet(newPs PrivilegeSet, counter uint64)

func (*BaseSession) SetQueriedDatabase added in v0.9.0

func (s *BaseSession) SetQueriedDatabase(dbName string)

SetQueriedDatabase implements the Session interface.

func (*BaseSession) SetSessionVariable added in v0.10.0

func (s *BaseSession) SetSessionVariable(ctx *Context, sysVarName string, value interface{}) error

SetSessionVariable implements the Session interface.

func (*BaseSession) SetStatusVariable added in v0.18.1

func (s *BaseSession) SetStatusVariable(_ *Context, statVarName string, val interface{}) error

SetStatusVariable implements the Session interface.

func (*BaseSession) SetTransaction added in v0.10.0

func (s *BaseSession) SetTransaction(tx Transaction)

func (*BaseSession) SetTransactionDatabase added in v0.15.0

func (s *BaseSession) SetTransactionDatabase(dbName string)

func (*BaseSession) SetUserVariable added in v0.10.0

func (s *BaseSession) SetUserVariable(ctx *Context, varName string, value interface{}, typ Type) error

SetUserVariable implements the Session interface.

func (*BaseSession) SetViewRegistry added in v0.11.0

func (s *BaseSession) SetViewRegistry(reg *ViewRegistry)

func (*BaseSession) UnlockWarnings added in v0.19.0

func (s *BaseSession) UnlockWarnings()

UnlockWarnings locks the session warnings so that they can be cleared

func (*BaseSession) UseDatabase added in v0.16.0

func (s *BaseSession) UseDatabase(ctx *Context, db Database) error

func (*BaseSession) ValidateSession added in v0.14.0

func (s *BaseSession) ValidateSession(ctx *Context) error

ValidateSession provides integrators a chance to do any custom validation of this session before any query is executed in it.

func (*BaseSession) Warn

func (s *BaseSession) Warn(warn *Warning)

Warn stores the warning in the session.

func (*BaseSession) WarningCount

func (s *BaseSession) WarningCount() uint16

WarningCount returns a number of session warnings

func (*BaseSession) Warnings

func (s *BaseSession) Warnings() []*Warning

Warnings returns a copy of session warnings (from the most recent - the last one) The function implements sql.Session interface

type Below added in v0.12.0

type Below struct {
	Key interface{}
}

Below represents the position immediately below the contained key.

func (Below) Compare added in v0.12.0

func (b Below) Compare(c MySQLRangeCut, typ Type) (int, error)

Compare implements MySQLRangeCut.

func (Below) String added in v0.12.0

func (b Below) String() string

String implements MySQLRangeCut.

func (Below) TypeAsLowerBound added in v0.12.0

func (Below) TypeAsLowerBound() MySQLRangeBoundType

TypeAsLowerBound implements MySQLRangeCut.

func (Below) TypeAsUpperBound added in v0.12.0

func (Below) TypeAsUpperBound() MySQLRangeBoundType

TypeAsUpperBound implements MySQLRangeCut.

type BelowNull added in v0.14.0

type BelowNull struct{}

BelowNull represents the position below NULL, which sorts before |AboveNull| and every non-NULL value in the domain.

func (BelowNull) Compare added in v0.14.0

func (BelowNull) Compare(c MySQLRangeCut, typ Type) (int, error)

Compare implements MySQLRangeCut.

func (BelowNull) String added in v0.14.0

func (BelowNull) String() string

String implements MySQLRangeCut.

func (BelowNull) TypeAsLowerBound added in v0.14.0

func (BelowNull) TypeAsLowerBound() MySQLRangeBoundType

TypeAsLowerBound implements MySQLRangeCut.

func (BelowNull) TypeAsUpperBound added in v0.14.0

func (BelowNull) TypeAsUpperBound() MySQLRangeBoundType

TypeAsUpperBound implements MySQLRangeCut.

type BinaryNode added in v0.12.0

type BinaryNode interface {
	Left() Node
	Right() Node
}

BinaryNode is a Node with two children

type Catalog

type Catalog interface {
	DatabaseProvider
	FunctionProvider
	TableFunctionProvider
	ExternalStoredProcedureProvider
	StatsProvider

	// CreateDatabase creates a new database, or returns an error if the operation isn't supported or fails.
	CreateDatabase(ctx *Context, dbName string, collation CollationID) error

	// RemoveDatabase removes the  database named, or returns an error if the operation isn't supported or fails.
	RemoveDatabase(ctx *Context, dbName string) error

	// Table returns the table with the name given in the db with the name given
	Table(ctx *Context, dbName, tableName string) (Table, Database, error)

	// DatabaseTable returns the table with the name given in the db given
	DatabaseTable(ctx *Context, db Database, tableName string) (Table, Database, error)

	// TableAsOf returns the table with the name given in the db with the name given, as of the given marker
	TableAsOf(ctx *Context, dbName, tableName string, asOf interface{}) (Table, Database, error)

	// DatabaseTableAsOf returns the table with the name given in the db given, as of the given marker
	DatabaseTableAsOf(ctx *Context, db Database, tableName string, asOf interface{}) (Table, Database, error)

	// LockTable locks the table named
	LockTable(ctx *Context, table string)

	// UnlockTables unlocks all tables locked by the session id given
	UnlockTables(ctx *Context, id uint32) error

	// AuthorizationHandler returns the AuthorizationHandler that is used by the catalog.
	AuthorizationHandler() AuthorizationHandler
}

type CatalogTable added in v0.15.0

type CatalogTable interface {
	Table

	// AssignCatalog assigns a Catalog to the table.
	AssignCatalog(cat Catalog) Table
}

CatalogTable is a Table that depends on a Catalog.

type CatalogTableFunction added in v0.17.0

type CatalogTableFunction interface {
	TableFunction

	// WithCatalog returns a new instance of the table function with the given catalog
	WithCatalog(c Catalog) (TableFunction, error)
}

CatalogTableFunction is a table function that can be used as a table factor in many SQL queries.

type CharacterSet

type CharacterSet struct {
	ID               CharacterSetID
	Name             string
	DefaultCollation CollationID
	BinaryCollation  CollationID
	Description      string
	MaxLength        uint8
	Encoder          encodings.Encoder
}

CharacterSet represents the character set of a string.

type CharacterSetID added in v0.14.0

type CharacterSetID uint16

CharacterSetID represents a character set. Unlike collations, this ID is not intended for storage and may change as the default collation changes. It is recommended to use the character set's name if persistence is desired.

const (
	CharacterSet_armscii8 CharacterSetID = 32
	CharacterSet_ascii    CharacterSetID = 11
	CharacterSet_big5     CharacterSetID = 1
	CharacterSet_binary   CharacterSetID = 63
	CharacterSet_cp1250   CharacterSetID = 26
	CharacterSet_cp1251   CharacterSetID = 51
	CharacterSet_cp1256   CharacterSetID = 57
	CharacterSet_cp1257   CharacterSetID = 59
	CharacterSet_cp850    CharacterSetID = 4
	CharacterSet_cp852    CharacterSetID = 40
	CharacterSet_cp866    CharacterSetID = 36
	CharacterSet_cp932    CharacterSetID = 95
	CharacterSet_dec8     CharacterSetID = 3
	CharacterSet_eucjpms  CharacterSetID = 97
	CharacterSet_euckr    CharacterSetID = 19
	CharacterSet_gb18030  CharacterSetID = 248
	CharacterSet_gb2312   CharacterSetID = 24
	CharacterSet_gbk      CharacterSetID = 28
	CharacterSet_geostd8  CharacterSetID = 92
	CharacterSet_greek    CharacterSetID = 25
	CharacterSet_hebrew   CharacterSetID = 16
	CharacterSet_hp8      CharacterSetID = 6
	CharacterSet_keybcs2  CharacterSetID = 37
	CharacterSet_koi8r    CharacterSetID = 7
	CharacterSet_koi8u    CharacterSetID = 22
	CharacterSet_latin1   CharacterSetID = 8
	CharacterSet_latin2   CharacterSetID = 9
	CharacterSet_latin5   CharacterSetID = 30
	CharacterSet_latin7   CharacterSetID = 41
	CharacterSet_macce    CharacterSetID = 38
	CharacterSet_macroman CharacterSetID = 39
	CharacterSet_sjis     CharacterSetID = 13
	CharacterSet_swe7     CharacterSetID = 10
	CharacterSet_tis620   CharacterSetID = 18
	CharacterSet_ucs2     CharacterSetID = 35
	CharacterSet_ujis     CharacterSetID = 12
	CharacterSet_utf16    CharacterSetID = 54
	CharacterSet_utf16le  CharacterSetID = 56
	CharacterSet_utf32    CharacterSetID = 60
	CharacterSet_utf8mb3  CharacterSetID = 33
	CharacterSet_utf8mb4  CharacterSetID = 255

	CharacterSet_utf8 = CharacterSet_utf8mb3

	// CharacterSet_Unspecified is used when a character set has not been specified, either explicitly or implicitly.
	// This is usually used as an intermediate character set to be later replaced by an analyzer pass or a plan,
	// although it is valid to use it directly. When used, behaves identically to the character set belonging to the
	// default collation, although it will NOT match the aforementioned character set.
	CharacterSet_Unspecified CharacterSetID = 0
)

func ParseCharacterSet

func ParseCharacterSet(str string) (CharacterSetID, error)

ParseCharacterSet takes in a string representing a CharacterSet and returns the result if a match is found, or an error if not.

func (CharacterSetID) BinaryCollation added in v0.14.0

func (cs CharacterSetID) BinaryCollation() CollationID

BinaryCollation returns the binary CollationID for this CharacterSet.

func (CharacterSetID) DefaultCollation added in v0.14.0

func (cs CharacterSetID) DefaultCollation() CollationID

DefaultCollation returns the default CollationID for this CharacterSet.

func (CharacterSetID) Description added in v0.14.0

func (cs CharacterSetID) Description() string

Description returns the plain-English description of the CharacterSet.

func (CharacterSetID) Encoder added in v0.14.0

func (cs CharacterSetID) Encoder() encodings.Encoder

Encoder returns this CharacterSet's encoder. As character sets are a work-in-progress, it is recommended to check if it is nil before allowing the character set to be set within a table.

func (CharacterSetID) MaxLength added in v0.14.0

func (cs CharacterSetID) MaxLength() int64

MaxLength returns the maximum size of a single character in the CharacterSet.

func (CharacterSetID) Name added in v0.14.0

func (cs CharacterSetID) Name() string

Name returns the name of this CharacterSet.

func (CharacterSetID) String added in v0.14.0

func (cs CharacterSetID) String() string

String returns the string representation of the CharacterSet.

type CharacterSetsIterator added in v0.14.0

type CharacterSetsIterator struct {
	// contains filtered or unexported fields
}

CharacterSetsIterator iterates over every character set available.

func NewCharacterSetsIterator added in v0.14.0

func NewCharacterSetsIterator() *CharacterSetsIterator

NewCharacterSetsIterator returns a new CharacterSetsIterator.

func (*CharacterSetsIterator) Next added in v0.14.0

func (csi *CharacterSetsIterator) Next() (CharacterSet, bool)

Next returns the next character set. If all character sets have been iterated over, returns false.

type CheckAlterableTable added in v0.9.0

type CheckAlterableTable interface {
	Table
	// CreateCheck creates an check constraint for this table, using the provided parameters.
	// Returns an error if the constraint name already exists.
	CreateCheck(ctx *Context, check *CheckDefinition) error
	// DropCheck removes a check constraint from the database.
	DropCheck(ctx *Context, chName string) error
}

CheckAlterableTable represents a table that supports check constraints.

type CheckConstraint added in v0.9.0

type CheckConstraint struct {
	Name     string
	Expr     Expression
	Enforced bool
}

CheckConstraint declares a boolean-eval constraint.

func (CheckConstraint) DebugString added in v0.10.0

func (c CheckConstraint) DebugString() string

DebugString implements the DebugStringer interface.

type CheckConstraintNode added in v0.18.0

type CheckConstraintNode interface {
	Node
	Checks() CheckConstraints
	WithChecks(CheckConstraints) Node
}

type CheckConstraints added in v0.10.0

type CheckConstraints []*CheckConstraint

func (CheckConstraints) FromExpressions added in v0.10.0

func (cc CheckConstraints) FromExpressions(exprs []Expression) (CheckConstraints, error)

FromExpressions takes a slice of sql.Expression in the same order as these constraints, and returns a new slice of constraints with the expressions given, holding names and other properties constant.

func (CheckConstraints) ToExpressions added in v0.10.0

func (cc CheckConstraints) ToExpressions() []Expression

ToExpressions returns the check expressions in these constraints as a slice of sql.Expression

type CheckDefinition added in v0.9.0

type CheckDefinition struct {
	Name            string // The name of this check. Check names in a database are unique.
	CheckExpression string // String serialization of the check expression
	Enforced        bool   // Whether this constraint is enforced
}

CheckDefinition defines a check constraint. Integrators are not expected to parse or understand the check constraint definitions, but must store and return them when asked.

type CheckTable added in v0.9.0

type CheckTable interface {
	Table
	// GetChecks returns the check constraints on this table.
	GetChecks(ctx *Context) ([]CheckDefinition, error)
}

CheckTable is a table that declares check constraints.

type Checksumable

type Checksumable interface {
	// Checksum returns a checksum and an error if there was any problem
	// computing or obtaining the checksum.
	Checksum() (string, error)
}

Checksumable provides the checksum of some data.

type Client

type Client struct {
	// User of the session.
	User string
	// Address of the client.
	Address string
	// Capabilities of the client
	Capabilities uint32
}

Client holds session user information.

type Closer

type Closer interface {
	Close(*Context) error
}

Closer is a node that can be closed.

type ColSet added in v0.16.0

type ColSet struct {
	// contains filtered or unexported fields
}

func MakeColSet added in v0.16.0

func MakeColSet(vals ...ColumnId) ColSet

MakeColSet returns a set initialized with the given values.

func NewColSet added in v0.16.0

func NewColSet(vals ...ColumnId) ColSet

func NewColSetFromIntSet added in v0.18.0

func NewColSetFromIntSet(set FastIntSet) ColSet

func (*ColSet) Add added in v0.16.0

func (s *ColSet) Add(col ColumnId)

Add adds a column to the set. No-op if the column is already in the set.

func (ColSet) Contains added in v0.16.0

func (s ColSet) Contains(col ColumnId) bool

Contains returns true if the set contains the column.

func (ColSet) Copy added in v0.16.0

func (s ColSet) Copy() ColSet

Copy returns a copy of s which can be modified independently.

func (ColSet) Difference added in v0.16.0

func (s ColSet) Difference(rhs ColSet) ColSet

Difference returns the elements of s that are not in rhs as a new set.

func (*ColSet) DifferenceWith added in v0.16.0

func (s *ColSet) DifferenceWith(rhs ColSet)

DifferenceWith removes any elements in rhs from this set.

func (ColSet) Empty added in v0.16.0

func (s ColSet) Empty() bool

Empty returns true if the set is empty.

func (ColSet) Equals added in v0.16.0

func (s ColSet) Equals(rhs ColSet) bool

Equals returns true if the two sets are identical.

func (ColSet) ForEach added in v0.16.0

func (s ColSet) ForEach(f func(col ColumnId))

ForEach calls a function for each column in the set (in increasing order).

func (ColSet) Intersection added in v0.16.0

func (s ColSet) Intersection(rhs ColSet) ColSet

Intersection returns the intersection of s and rhs as a new set.

func (*ColSet) IntersectionWith added in v0.16.0

func (s *ColSet) IntersectionWith(rhs ColSet)

IntersectionWith removes any columns not in rhs from this set.

func (ColSet) Intersects added in v0.16.0

func (s ColSet) Intersects(rhs ColSet) bool

Intersects returns true if s has any elements in common with rhs.

func (ColSet) Len added in v0.16.0

func (s ColSet) Len() int

Len returns the number of the columns in the set.

func (ColSet) Next added in v0.16.0

func (s ColSet) Next(startVal ColumnId) (ColumnId, bool)

Next returns the first value in the set which is >= startVal. If there is no such column, the second return value is false.

func (*ColSet) Remove added in v0.16.0

func (s *ColSet) Remove(col ColumnId)

Remove removes a column from the set. No-op if the column is not in the set.

func (ColSet) String added in v0.16.0

func (s ColSet) String() string

func (ColSet) SubsetOf added in v0.16.0

func (s ColSet) SubsetOf(rhs ColSet) bool

SubsetOf returns true if rhs contains all the elements in s.

func (ColSet) Union added in v0.16.0

func (s ColSet) Union(rhs ColSet) ColSet

Union returns the union of s and rhs as a new set.

func (*ColSet) UnionWith added in v0.16.0

func (s *ColSet) UnionWith(rhs ColSet)

UnionWith adds all the columns from rhs to this set.

type CollatedDatabase added in v0.14.0

type CollatedDatabase interface {
	Database
	// GetCollation returns this database's collation.
	GetCollation(ctx *Context) CollationID
	// SetCollation updates this database's collation.
	SetCollation(ctx *Context, collation CollationID) error
}

CollatedDatabase is a Database that can store and update its collation.

type CollatedDatabaseProvider added in v0.14.0

type CollatedDatabaseProvider interface {
	MutableDatabaseProvider

	// CreateCollatedDatabase creates a collated database and adds it to the provider's collection.
	CreateCollatedDatabase(ctx *Context, name string, collation CollationID) error
}

CollatedDatabaseProvider is a DatabaseProvider that can create a Database with a specific collation.

type Collation

type Collation struct {
	ID                CollationID
	Name              string
	CharacterSet      CharacterSetID
	IsDefault         bool
	IsCompiled        bool
	IsCaseSensitive   bool
	IsAccentSensitive bool
	SortLength        uint8
	PadAttribute      string
	Sorter            CollationSorter
}

Collation represents the collation of a string.

type CollationAlterableTable added in v0.15.0

type CollationAlterableTable interface {
	Table
	// ModifyStoredCollation modifies the default collation that is set on the table, along with converting all columns
	// to the given collation (ALTER TABLE ... CONVERT TO CHARACTER SET).
	ModifyStoredCollation(ctx *Context, collation CollationID) error
	// ModifyDefaultCollation modifies the default collation that is set on the table (ALTER TABLE ... COLLATE).
	ModifyDefaultCollation(ctx *Context, collation CollationID) error
}

CollationAlterableTable represents a table that supports the alteration of its collation.

type CollationCoercible added in v0.15.0

type CollationCoercible interface {
	// CollationCoercibility returns the collation and coercibility of the expression or node.
	CollationCoercibility(ctx *Context) (collation CollationID, coercibility byte)
}

CollationCoercible represents the coercibility of an expression or node. Although the resulting value from the node or expression may be NULL, this interface returns the coercibility as though a NULL would not be returned.

type CollationID added in v0.14.0

type CollationID uint16

CollationID represents the collation's unique identifier. May be safely converted to and from an uint16 for storage.

const (
	Collation_armscii8_bin                CollationID = 64
	Collation_armscii8_general_ci         CollationID = 32
	Collation_ascii_bin                   CollationID = 65
	Collation_ascii_general_ci            CollationID = 11
	Collation_big5_bin                    CollationID = 84
	Collation_big5_chinese_ci             CollationID = 1
	Collation_binary                      CollationID = 63
	Collation_cp1250_bin                  CollationID = 66
	Collation_cp1250_croatian_ci          CollationID = 44
	Collation_cp1250_czech_cs             CollationID = 34
	Collation_cp1250_general_ci           CollationID = 26
	Collation_cp1250_polish_ci            CollationID = 99
	Collation_cp1251_bin                  CollationID = 50
	Collation_cp1251_bulgarian_ci         CollationID = 14
	Collation_cp1251_general_ci           CollationID = 51
	Collation_cp1251_general_cs           CollationID = 52
	Collation_cp1251_ukrainian_ci         CollationID = 23
	Collation_cp1256_bin                  CollationID = 67
	Collation_cp1256_general_ci           CollationID = 57
	Collation_cp1257_bin                  CollationID = 58
	Collation_cp1257_general_ci           CollationID = 59
	Collation_cp1257_lithuanian_ci        CollationID = 29
	Collation_cp850_bin                   CollationID = 80
	Collation_cp850_general_ci            CollationID = 4
	Collation_cp852_bin                   CollationID = 81
	Collation_cp852_general_ci            CollationID = 40
	Collation_cp866_bin                   CollationID = 68
	Collation_cp866_general_ci            CollationID = 36
	Collation_cp932_bin                   CollationID = 96
	Collation_cp932_japanese_ci           CollationID = 95
	Collation_dec8_bin                    CollationID = 69
	Collation_dec8_swedish_ci             CollationID = 3
	Collation_eucjpms_bin                 CollationID = 98
	Collation_eucjpms_japanese_ci         CollationID = 97
	Collation_euckr_bin                   CollationID = 85
	Collation_euckr_korean_ci             CollationID = 19
	Collation_gb18030_bin                 CollationID = 249
	Collation_gb18030_chinese_ci          CollationID = 248
	Collation_gb18030_unicode_520_ci      CollationID = 250
	Collation_gb2312_bin                  CollationID = 86
	Collation_gb2312_chinese_ci           CollationID = 24
	Collation_gbk_bin                     CollationID = 87
	Collation_gbk_chinese_ci              CollationID = 28
	Collation_geostd8_bin                 CollationID = 93
	Collation_geostd8_general_ci          CollationID = 92
	Collation_greek_bin                   CollationID = 70
	Collation_greek_general_ci            CollationID = 25
	Collation_hebrew_bin                  CollationID = 71
	Collation_hebrew_general_ci           CollationID = 16
	Collation_hp8_bin                     CollationID = 72
	Collation_hp8_english_ci              CollationID = 6
	Collation_keybcs2_bin                 CollationID = 73
	Collation_keybcs2_general_ci          CollationID = 37
	Collation_koi8r_bin                   CollationID = 74
	Collation_koi8r_general_ci            CollationID = 7
	Collation_koi8u_bin                   CollationID = 75
	Collation_koi8u_general_ci            CollationID = 22
	Collation_latin1_bin                  CollationID = 47
	Collation_latin1_danish_ci            CollationID = 15
	Collation_latin1_general_ci           CollationID = 48
	Collation_latin1_general_cs           CollationID = 49
	Collation_latin1_german1_ci           CollationID = 5
	Collation_latin1_german2_ci           CollationID = 31
	Collation_latin1_spanish_ci           CollationID = 94
	Collation_latin1_swedish_ci           CollationID = 8
	Collation_latin2_bin                  CollationID = 77
	Collation_latin2_croatian_ci          CollationID = 27
	Collation_latin2_czech_cs             CollationID = 2
	Collation_latin2_general_ci           CollationID = 9
	Collation_latin2_hungarian_ci         CollationID = 21
	Collation_latin5_bin                  CollationID = 78
	Collation_latin5_turkish_ci           CollationID = 30
	Collation_latin7_bin                  CollationID = 79
	Collation_latin7_estonian_cs          CollationID = 20
	Collation_latin7_general_ci           CollationID = 41
	Collation_latin7_general_cs           CollationID = 42
	Collation_macce_bin                   CollationID = 43
	Collation_macce_general_ci            CollationID = 38
	Collation_macroman_bin                CollationID = 53
	Collation_macroman_general_ci         CollationID = 39
	Collation_sjis_bin                    CollationID = 88
	Collation_sjis_japanese_ci            CollationID = 13
	Collation_swe7_bin                    CollationID = 82
	Collation_swe7_swedish_ci             CollationID = 10
	Collation_tis620_bin                  CollationID = 89
	Collation_tis620_thai_ci              CollationID = 18
	Collation_ucs2_bin                    CollationID = 90
	Collation_ucs2_croatian_ci            CollationID = 149
	Collation_ucs2_czech_ci               CollationID = 138
	Collation_ucs2_danish_ci              CollationID = 139
	Collation_ucs2_esperanto_ci           CollationID = 145
	Collation_ucs2_estonian_ci            CollationID = 134
	Collation_ucs2_general_ci             CollationID = 35
	Collation_ucs2_general_mysql500_ci    CollationID = 159
	Collation_ucs2_german2_ci             CollationID = 148
	Collation_ucs2_hungarian_ci           CollationID = 146
	Collation_ucs2_icelandic_ci           CollationID = 129
	Collation_ucs2_latvian_ci             CollationID = 130
	Collation_ucs2_lithuanian_ci          CollationID = 140
	Collation_ucs2_persian_ci             CollationID = 144
	Collation_ucs2_polish_ci              CollationID = 133
	Collation_ucs2_roman_ci               CollationID = 143
	Collation_ucs2_romanian_ci            CollationID = 131
	Collation_ucs2_sinhala_ci             CollationID = 147
	Collation_ucs2_slovak_ci              CollationID = 141
	Collation_ucs2_slovenian_ci           CollationID = 132
	Collation_ucs2_spanish2_ci            CollationID = 142
	Collation_ucs2_spanish_ci             CollationID = 135
	Collation_ucs2_swedish_ci             CollationID = 136
	Collation_ucs2_turkish_ci             CollationID = 137
	Collation_ucs2_unicode_520_ci         CollationID = 150
	Collation_ucs2_unicode_ci             CollationID = 128
	Collation_ucs2_vietnamese_ci          CollationID = 151
	Collation_ujis_bin                    CollationID = 91
	Collation_ujis_japanese_ci            CollationID = 12
	Collation_utf16_bin                   CollationID = 55
	Collation_utf16_croatian_ci           CollationID = 122
	Collation_utf16_czech_ci              CollationID = 111
	Collation_utf16_danish_ci             CollationID = 112
	Collation_utf16_esperanto_ci          CollationID = 118
	Collation_utf16_estonian_ci           CollationID = 107
	Collation_utf16_general_ci            CollationID = 54
	Collation_utf16_german2_ci            CollationID = 121
	Collation_utf16_hungarian_ci          CollationID = 119
	Collation_utf16_icelandic_ci          CollationID = 102
	Collation_utf16_latvian_ci            CollationID = 103
	Collation_utf16_lithuanian_ci         CollationID = 113
	Collation_utf16_persian_ci            CollationID = 117
	Collation_utf16_polish_ci             CollationID = 106
	Collation_utf16_roman_ci              CollationID = 116
	Collation_utf16_romanian_ci           CollationID = 104
	Collation_utf16_sinhala_ci            CollationID = 120
	Collation_utf16_slovak_ci             CollationID = 114
	Collation_utf16_slovenian_ci          CollationID = 105
	Collation_utf16_spanish2_ci           CollationID = 115
	Collation_utf16_spanish_ci            CollationID = 108
	Collation_utf16_swedish_ci            CollationID = 109
	Collation_utf16_turkish_ci            CollationID = 110
	Collation_utf16_unicode_520_ci        CollationID = 123
	Collation_utf16_unicode_ci            CollationID = 101
	Collation_utf16_vietnamese_ci         CollationID = 124
	Collation_utf16le_bin                 CollationID = 62
	Collation_utf16le_general_ci          CollationID = 56
	Collation_utf32_bin                   CollationID = 61
	Collation_utf32_croatian_ci           CollationID = 181
	Collation_utf32_czech_ci              CollationID = 170
	Collation_utf32_danish_ci             CollationID = 171
	Collation_utf32_esperanto_ci          CollationID = 177
	Collation_utf32_estonian_ci           CollationID = 166
	Collation_utf32_general_ci            CollationID = 60
	Collation_utf32_german2_ci            CollationID = 180
	Collation_utf32_hungarian_ci          CollationID = 178
	Collation_utf32_icelandic_ci          CollationID = 161
	Collation_utf32_latvian_ci            CollationID = 162
	Collation_utf32_lithuanian_ci         CollationID = 172
	Collation_utf32_persian_ci            CollationID = 176
	Collation_utf32_polish_ci             CollationID = 165
	Collation_utf32_roman_ci              CollationID = 175
	Collation_utf32_romanian_ci           CollationID = 163
	Collation_utf32_sinhala_ci            CollationID = 179
	Collation_utf32_slovak_ci             CollationID = 173
	Collation_utf32_slovenian_ci          CollationID = 164
	Collation_utf32_spanish2_ci           CollationID = 174
	Collation_utf32_spanish_ci            CollationID = 167
	Collation_utf32_swedish_ci            CollationID = 168
	Collation_utf32_turkish_ci            CollationID = 169
	Collation_utf32_unicode_520_ci        CollationID = 182
	Collation_utf32_unicode_ci            CollationID = 160
	Collation_utf32_vietnamese_ci         CollationID = 183
	Collation_utf8mb3_bin                 CollationID = 83
	Collation_utf8mb3_croatian_ci         CollationID = 213
	Collation_utf8mb3_czech_ci            CollationID = 202
	Collation_utf8mb3_danish_ci           CollationID = 203
	Collation_utf8mb3_esperanto_ci        CollationID = 209
	Collation_utf8mb3_estonian_ci         CollationID = 198
	Collation_utf8mb3_general_ci          CollationID = 33
	Collation_utf8mb3_general_mysql500_ci CollationID = 223
	Collation_utf8mb3_german2_ci          CollationID = 212
	Collation_utf8mb3_hungarian_ci        CollationID = 210
	Collation_utf8mb3_icelandic_ci        CollationID = 193
	Collation_utf8mb3_latvian_ci          CollationID = 194
	Collation_utf8mb3_lithuanian_ci       CollationID = 204
	Collation_utf8mb3_persian_ci          CollationID = 208
	Collation_utf8mb3_polish_ci           CollationID = 197
	Collation_utf8mb3_roman_ci            CollationID = 207
	Collation_utf8mb3_romanian_ci         CollationID = 195
	Collation_utf8mb3_sinhala_ci          CollationID = 211
	Collation_utf8mb3_slovak_ci           CollationID = 205
	Collation_utf8mb3_slovenian_ci        CollationID = 196
	Collation_utf8mb3_spanish2_ci         CollationID = 206
	Collation_utf8mb3_spanish_ci          CollationID = 199
	Collation_utf8mb3_swedish_ci          CollationID = 200
	Collation_utf8mb3_tolower_ci          CollationID = 76
	Collation_utf8mb3_turkish_ci          CollationID = 201
	Collation_utf8mb3_unicode_520_ci      CollationID = 214
	Collation_utf8mb3_unicode_ci          CollationID = 192
	Collation_utf8mb3_vietnamese_ci       CollationID = 215
	Collation_utf8mb4_0900_ai_ci          CollationID = 255
	Collation_utf8mb4_0900_as_ci          CollationID = 305
	Collation_utf8mb4_0900_as_cs          CollationID = 278
	Collation_utf8mb4_0900_bin            CollationID = 309
	Collation_utf8mb4_bg_0900_ai_ci       CollationID = 318
	Collation_utf8mb4_bg_0900_as_cs       CollationID = 319
	Collation_utf8mb4_bin                 CollationID = 46
	Collation_utf8mb4_bs_0900_ai_ci       CollationID = 316
	Collation_utf8mb4_bs_0900_as_cs       CollationID = 317
	Collation_utf8mb4_croatian_ci         CollationID = 245
	Collation_utf8mb4_cs_0900_ai_ci       CollationID = 266
	Collation_utf8mb4_cs_0900_as_cs       CollationID = 289
	Collation_utf8mb4_czech_ci            CollationID = 234
	Collation_utf8mb4_da_0900_ai_ci       CollationID = 267
	Collation_utf8mb4_da_0900_as_cs       CollationID = 290
	Collation_utf8mb4_danish_ci           CollationID = 235
	Collation_utf8mb4_de_pb_0900_ai_ci    CollationID = 256
	Collation_utf8mb4_de_pb_0900_as_cs    CollationID = 279
	Collation_utf8mb4_eo_0900_ai_ci       CollationID = 273
	Collation_utf8mb4_eo_0900_as_cs       CollationID = 296
	Collation_utf8mb4_es_0900_ai_ci       CollationID = 263
	Collation_utf8mb4_es_0900_as_cs       CollationID = 286
	Collation_utf8mb4_es_trad_0900_ai_ci  CollationID = 270
	Collation_utf8mb4_es_trad_0900_as_cs  CollationID = 293
	Collation_utf8mb4_esperanto_ci        CollationID = 241
	Collation_utf8mb4_estonian_ci         CollationID = 230
	Collation_utf8mb4_et_0900_ai_ci       CollationID = 262
	Collation_utf8mb4_et_0900_as_cs       CollationID = 285
	Collation_utf8mb4_general_ci          CollationID = 45
	Collation_utf8mb4_german2_ci          CollationID = 244
	Collation_utf8mb4_gl_0900_ai_ci       CollationID = 320
	Collation_utf8mb4_gl_0900_as_cs       CollationID = 321
	Collation_utf8mb4_hr_0900_ai_ci       CollationID = 275
	Collation_utf8mb4_hr_0900_as_cs       CollationID = 298
	Collation_utf8mb4_hu_0900_ai_ci       CollationID = 274
	Collation_utf8mb4_hu_0900_as_cs       CollationID = 297
	Collation_utf8mb4_hungarian_ci        CollationID = 242
	Collation_utf8mb4_icelandic_ci        CollationID = 225
	Collation_utf8mb4_is_0900_ai_ci       CollationID = 257
	Collation_utf8mb4_is_0900_as_cs       CollationID = 280
	Collation_utf8mb4_ja_0900_as_cs       CollationID = 303
	Collation_utf8mb4_ja_0900_as_cs_ks    CollationID = 304
	Collation_utf8mb4_la_0900_ai_ci       CollationID = 271
	Collation_utf8mb4_la_0900_as_cs       CollationID = 294
	Collation_utf8mb4_latvian_ci          CollationID = 226
	Collation_utf8mb4_lithuanian_ci       CollationID = 236
	Collation_utf8mb4_lt_0900_ai_ci       CollationID = 268
	Collation_utf8mb4_lt_0900_as_cs       CollationID = 291
	Collation_utf8mb4_lv_0900_ai_ci       CollationID = 258
	Collation_utf8mb4_lv_0900_as_cs       CollationID = 281
	Collation_utf8mb4_mn_cyrl_0900_ai_ci  CollationID = 322
	Collation_utf8mb4_mn_cyrl_0900_as_cs  CollationID = 323
	Collation_utf8mb4_nb_0900_ai_ci       CollationID = 310
	Collation_utf8mb4_nb_0900_as_cs       CollationID = 311
	Collation_utf8mb4_nn_0900_ai_ci       CollationID = 312
	Collation_utf8mb4_nn_0900_as_cs       CollationID = 313
	Collation_utf8mb4_persian_ci          CollationID = 240
	Collation_utf8mb4_pl_0900_ai_ci       CollationID = 261
	Collation_utf8mb4_pl_0900_as_cs       CollationID = 284
	Collation_utf8mb4_polish_ci           CollationID = 229
	Collation_utf8mb4_ro_0900_ai_ci       CollationID = 259
	Collation_utf8mb4_ro_0900_as_cs       CollationID = 282
	Collation_utf8mb4_roman_ci            CollationID = 239
	Collation_utf8mb4_romanian_ci         CollationID = 227
	Collation_utf8mb4_ru_0900_ai_ci       CollationID = 306
	Collation_utf8mb4_ru_0900_as_cs       CollationID = 307
	Collation_utf8mb4_sinhala_ci          CollationID = 243
	Collation_utf8mb4_sk_0900_ai_ci       CollationID = 269
	Collation_utf8mb4_sk_0900_as_cs       CollationID = 292
	Collation_utf8mb4_sl_0900_ai_ci       CollationID = 260
	Collation_utf8mb4_sl_0900_as_cs       CollationID = 283
	Collation_utf8mb4_slovak_ci           CollationID = 237
	Collation_utf8mb4_slovenian_ci        CollationID = 228
	Collation_utf8mb4_spanish2_ci         CollationID = 238
	Collation_utf8mb4_spanish_ci          CollationID = 231
	Collation_utf8mb4_sr_latn_0900_ai_ci  CollationID = 314
	Collation_utf8mb4_sr_latn_0900_as_cs  CollationID = 315
	Collation_utf8mb4_sv_0900_ai_ci       CollationID = 264
	Collation_utf8mb4_sv_0900_as_cs       CollationID = 287
	Collation_utf8mb4_swedish_ci          CollationID = 232
	Collation_utf8mb4_tr_0900_ai_ci       CollationID = 265
	Collation_utf8mb4_tr_0900_as_cs       CollationID = 288
	Collation_utf8mb4_turkish_ci          CollationID = 233
	Collation_utf8mb4_unicode_520_ci      CollationID = 246
	Collation_utf8mb4_unicode_ci          CollationID = 224
	Collation_utf8mb4_vi_0900_ai_ci       CollationID = 277
	Collation_utf8mb4_vi_0900_as_cs       CollationID = 300
	Collation_utf8mb4_vietnamese_ci       CollationID = 247
	Collation_utf8mb4_zh_0900_as_cs       CollationID = 308

	Collation_utf8_general_ci          = Collation_utf8mb3_general_ci
	Collation_utf8_tolower_ci          = Collation_utf8mb3_tolower_ci
	Collation_utf8_bin                 = Collation_utf8mb3_bin
	Collation_utf8_unicode_ci          = Collation_utf8mb3_unicode_ci
	Collation_utf8_icelandic_ci        = Collation_utf8mb3_icelandic_ci
	Collation_utf8_latvian_ci          = Collation_utf8mb3_latvian_ci
	Collation_utf8_romanian_ci         = Collation_utf8mb3_romanian_ci
	Collation_utf8_slovenian_ci        = Collation_utf8mb3_slovenian_ci
	Collation_utf8_polish_ci           = Collation_utf8mb3_polish_ci
	Collation_utf8_estonian_ci         = Collation_utf8mb3_estonian_ci
	Collation_utf8_spanish_ci          = Collation_utf8mb3_spanish_ci
	Collation_utf8_swedish_ci          = Collation_utf8mb3_swedish_ci
	Collation_utf8_turkish_ci          = Collation_utf8mb3_turkish_ci
	Collation_utf8_czech_ci            = Collation_utf8mb3_czech_ci
	Collation_utf8_danish_ci           = Collation_utf8mb3_danish_ci
	Collation_utf8_lithuanian_ci       = Collation_utf8mb3_lithuanian_ci
	Collation_utf8_slovak_ci           = Collation_utf8mb3_slovak_ci
	Collation_utf8_spanish2_ci         = Collation_utf8mb3_spanish2_ci
	Collation_utf8_roman_ci            = Collation_utf8mb3_roman_ci
	Collation_utf8_persian_ci          = Collation_utf8mb3_persian_ci
	Collation_utf8_esperanto_ci        = Collation_utf8mb3_esperanto_ci
	Collation_utf8_hungarian_ci        = Collation_utf8mb3_hungarian_ci
	Collation_utf8_sinhala_ci          = Collation_utf8mb3_sinhala_ci
	Collation_utf8_german2_ci          = Collation_utf8mb3_german2_ci
	Collation_utf8_croatian_ci         = Collation_utf8mb3_croatian_ci
	Collation_utf8_unicode_520_ci      = Collation_utf8mb3_unicode_520_ci
	Collation_utf8_vietnamese_ci       = Collation_utf8mb3_vietnamese_ci
	Collation_utf8_general_mysql500_ci = Collation_utf8mb3_general_mysql500_ci

	Collation_Default                    = Collation_utf8mb4_0900_bin
	Collation_Information_Schema_Default = Collation_utf8mb3_general_ci
	// Collation_Unspecified is used when a collation has not been specified, either explicitly or implicitly. This is
	// usually used as an intermediate collation to be later replaced by an analyzer pass or a plan, although it is
	// valid to use it directly. When used, behaves identically to the default collation, although it will NOT match
	// the default collation.
	Collation_Unspecified CollationID = 0
)

func GetCoercibility added in v0.15.0

func GetCoercibility(ctx *Context, nodeOrExpr interface{}) (collation CollationID, coercibility byte)

GetCoercibility returns the coercibility of the given node or expression.

func ParseCollation

func ParseCollation(characterSetStr string, collationStr string, binary bool) (CollationID, error)

ParseCollation takes in an optional character set and collation, along with the binary attribute if present, and returns a valid collation or error. A nil character set and collation will return the default collation.

func ResolveCoercibility added in v0.15.0

func ResolveCoercibility(leftCollation CollationID, leftCoercibility byte, rightCollation CollationID, rightCoercibility byte) (CollationID, byte)

ResolveCoercibility returns the collation to use by comparing coercibility, along with giving priority to binary collations. This is an approximation of MySQL's coercibility rules: https://dev.mysql.com/doc/refman/8.0/en/charset-collation-coercibility.html As we do not implement the full coercion pipeline, we make some assumptions when information is missing, and never error even when MySQL would find an expression invalid.

func (CollationID) CharacterSet added in v0.14.0

func (c CollationID) CharacterSet() CharacterSetID

CharacterSet returns the CharacterSetID belonging to this Collation.

func (CollationID) Collation added in v0.14.0

func (c CollationID) Collation() Collation

Collation returns the Collation with this ID.

func (CollationID) Equals added in v0.14.0

func (c CollationID) Equals(other CollationID) bool

Equals returns whether the given collation is the same as the calling collation.

func (CollationID) HashToBytes added in v0.14.0

func (c CollationID) HashToBytes(str string) ([]byte, error)

HashToBytes returns a hash of the given decoded string based on the collation. Collations take each rune's weight into account, therefore two strings with technically different contents may hash to the same value, as the collation considers them the same string. This is equivalent to HashToUint, except that it converts the uint64 to a byte slice.

func (CollationID) HashToUint added in v0.14.0

func (c CollationID) HashToUint(str string) (uint64, error)

HashToUint returns a hash of the given decoded string based on the collation. Collations take each rune's weight into account, therefore two strings with technically different contents may hash to the same value, as the collation considers them the same string.

func (CollationID) IsCompiled added in v0.14.0

func (c CollationID) IsCompiled() string

IsCompiled returns a string indicating whether this collation is compiled.

func (CollationID) IsDefault added in v0.14.0

func (c CollationID) IsDefault() string

IsDefault returns a string indicating whether this collation is the default for the character set.

func (CollationID) Name added in v0.14.0

func (c CollationID) Name() string

Name returns the name of this collation.

func (CollationID) PadAttribute added in v0.14.0

func (c CollationID) PadAttribute() string

PadAttribute returns a string representing the pad attribute of the collation.

func (CollationID) SortLength added in v0.14.0

func (c CollationID) SortLength() uint32

SortLength returns the sort length of the collation.

func (CollationID) Sorter added in v0.14.0

func (c CollationID) Sorter() CollationSorter

Sorter returns this collation's sort function. As collations are a work-in-progress, it is recommended to avoid using any collations that return a nil sort function.

func (CollationID) String added in v0.14.0

func (c CollationID) String() string

String returns the string representation of the Collation.

func (CollationID) WorksWithCharacterSet added in v0.14.0

func (c CollationID) WorksWithCharacterSet(cs CharacterSetID) bool

WorksWithCharacterSet returns whether the Collation is valid for the given CharacterSet.

func (CollationID) WriteWeightString added in v0.15.0

func (c CollationID) WriteWeightString(hash io.Writer, str string) error

WriteWeightString writes the weights of each codepoint in the string into the given io.Writer. Two strings with technically different contents may generate the same WeightString to the same value, as the collation considers them the same string.

type CollationSorter added in v0.15.0

type CollationSorter func(r rune) int32

CollationSorter is a collation's sort function. When given a rune, an integer is returned that represents that rune's order when sorted against all other runes. That integer is referred to as a sort order. When two runes have the same sort order, they are considered equivalent. For example, case-insensitive collations return the same sort order for uppercase and lowercase variants of a character, while case-sensitive collations return different sort orders. Comparing sort orders from different collations is meaningless, and therefore represents a logical error.

type CollationsIterator added in v0.14.0

type CollationsIterator struct {
	// contains filtered or unexported fields
}

CollationsIterator iterates over every collation available, ordered by their ID (ascending).

func NewCollationsIterator added in v0.14.0

func NewCollationsIterator() *CollationsIterator

NewCollationsIterator returns a new CollationsIterator.

func (*CollationsIterator) Next added in v0.14.0

func (ci *CollationsIterator) Next() (Collation, bool)

Next returns the next collation. If all collations have been iterated over, returns false.

type Column

type Column struct {
	// Name is the name of the column.
	Name string
	// Type is the data type of the column.
	Type Type
	// Default contains the default value of the column or nil if it was not explicitly defined.
	Default *ColumnDefaultValue
	// AutoIncrement is true if the column auto-increments.
	AutoIncrement bool
	// Nullable is true if the column can contain NULL values, or false
	// otherwise.
	Nullable bool
	// Source is the name of the table this column came from.
	Source string
	// DatabaseSource is the name of the database this column came from.
	DatabaseSource string
	// PrimaryKey is true if the column is part of the primary key for its table.
	PrimaryKey bool
	// Comment contains the string comment for this column.
	Comment string
	// Extra contains any additional information to put in the `extra` column under `information_schema.columns`.
	Extra string
	// Generated is non-nil if the column is defined with a generated value. Mutually exclusive with Default
	Generated *ColumnDefaultValue
	// Virtual is true if the column is defined as a virtual column. Generated must be non-nil in this case.
	// Virtual column values will be provided for write operations, in case integrators need to use them to update
	// indexes, but must not be returned in rows from tables that include them.
	Virtual bool
	// OnUpdate contains the on update value of the column or nil if it was not explicitly defined.
	OnUpdate *ColumnDefaultValue
}

Column is the definition of a table column. As SQL:2016 puts it:

A column is a named component of a table. It has a data type, a default,
and a nullability characteristic.

func (*Column) Check

func (c *Column) Check(v interface{}) bool

Check ensures the value is correct for this column.

func (Column) Copy added in v0.12.0

func (c Column) Copy() *Column

func (*Column) DebugString added in v0.10.0

func (c *Column) DebugString() string

func (*Column) Equals

func (c *Column) Equals(c2 *Column) bool

Equals checks whether two columns are equal.

type ColumnDefaultValue

type ColumnDefaultValue struct {
	// Expression is the expression representing this default value
	Expr Expression
	// OutType converts the output of the expression into this type, when not nil
	OutType Type
	// Literal indicates whether the default value is a Literal value or expression
	Literal bool
	// ReturnNil indicates whether a nil value from the default value expression is returned as null or an error
	ReturnNil bool
	// Parenthesized indicates whether the value was specified in parens or not; this is typically the opposite of the Literal field,
	// but they can both be false in the case of now/current_timestamp for datetimes and timestamps.
	Parenthesized bool
}

ColumnDefaultValue is an expression representing the default value of a column. May represent both a default literal and a default expression. A nil pointer of this type represents an implicit default value and is thus valid, so all method calls will return without error.

func NewColumnDefaultValue

func NewColumnDefaultValue(expr Expression, outType Type, representsLiteral bool, parenthesized bool, mayReturnNil bool) (*ColumnDefaultValue, error)

NewColumnDefaultValue returns a new ColumnDefaultValue expression.

func NewUnresolvedColumnDefaultValue added in v0.12.0

func NewUnresolvedColumnDefaultValue(expr string) *ColumnDefaultValue

NewUnresolvedColumnDefaultValue returns a column default

func (*ColumnDefaultValue) CheckType added in v0.12.0

func (e *ColumnDefaultValue) CheckType(ctx *Context) error

CheckType validates that the ColumnDefaultValue has the correct type.

func (*ColumnDefaultValue) Children

func (e *ColumnDefaultValue) Children() []Expression

Children implements sql.Expression

func (*ColumnDefaultValue) CollationCoercibility added in v0.15.0

func (e *ColumnDefaultValue) CollationCoercibility(ctx *Context) (collation CollationID, coercibility byte)

CollationCoercibility implements the interface sql.CollationCoercible.

func (*ColumnDefaultValue) DebugString added in v0.12.0

func (e *ColumnDefaultValue) DebugString() string

func (*ColumnDefaultValue) Eval

func (e *ColumnDefaultValue) Eval(ctx *Context, r Row) (interface{}, error)

Eval implements sql.Expression

func (*ColumnDefaultValue) IsLiteral

func (e *ColumnDefaultValue) IsLiteral() bool

IsLiteral returns whether this expression represents a literal default value (otherwise it's an expression default value).

func (*ColumnDefaultValue) IsNullable

func (e *ColumnDefaultValue) IsNullable() bool

IsNullable implements sql.Expression

func (*ColumnDefaultValue) IsParenthesized added in v0.14.0

func (e *ColumnDefaultValue) IsParenthesized() bool

IsParenthesized returns whether this column default was specified in parentheses, using the expression default value form. It is almost always the opposite of IsLiteral, but there is one edge case where matching MySQL's behavior require that we can distinguish between a non-literal value in parens and a non-literal value not in parens. The edge case is using now/current_timestamp as a column default; now/current_timestamp can be specified without parens for datetime/timestamp fields, but it must be enclosed in parens to be used as the default for other types.

func (*ColumnDefaultValue) Resolved

func (e *ColumnDefaultValue) Resolved() bool

Resolved implements sql.Expression

func (*ColumnDefaultValue) String

func (e *ColumnDefaultValue) String() string

String implements sql.Expression

func (*ColumnDefaultValue) Type

func (e *ColumnDefaultValue) Type() Type

Type implements sql.Expression

func (*ColumnDefaultValue) WithChildren

func (e *ColumnDefaultValue) WithChildren(children ...Expression) (Expression, error)

WithChildren implements sql.Expression

type ColumnExpressionType added in v0.12.0

type ColumnExpressionType struct {
	Expression string
	Type       Type
}

ColumnExpressionType returns a column expression along with its Type.

type ColumnId added in v0.16.0

type ColumnId uint16

type ColumnOrder

type ColumnOrder struct {
	First       bool   // True if this column should come first
	AfterColumn string // Set to the name of the column after which this column should appear
}

ColumnOrder is used in ALTER TABLE statements to change the order of inserted / modified columns.

type ColumnRename added in v0.15.0

type ColumnRename struct {
	Before, After string
}

type CommentedNode added in v0.9.0

type CommentedNode interface {
	Node
	WithComment(string) Node
	Comment() string
}

CommentedNode allows comments to be set and retrieved on it. Used primarily for join hint comments.

type CommentedTable added in v0.18.0

type CommentedTable interface {
	Table
	// Comment returns the table's optional comment.
	Comment() string
}

CommentedTable is a table that has a comment on it.

type Context

type Context struct {
	context.Context
	Session
	Memory      *MemoryManager
	ProcessList ProcessList

	Version AnalyzerVersion
	// contains filtered or unexported fields
}

Context of the query execution.

func NewContext

func NewContext(
	ctx context.Context,
	opts ...ContextOption,
) *Context

NewContext creates a new query context. Options can be passed to configure the context. If some aspect of the context is not configure, the default value will be used. By default, the context will have an empty base session, a noop tracer and a memory manager using the process reporter.

func NewEmptyContext

func NewEmptyContext() *Context

NewEmptyContext returns a default context with default values.

func (*Context) ApplyOpts

func (c *Context) ApplyOpts(opts ...ContextOption)

ApplyOpts the options given to the context. Mostly for tests, not safe for use after construction of the context.

func (*Context) Error

func (c *Context) Error(code int, msg string, args ...interface{})

Error adds an error as warning to the session.

func (*Context) KillConnection added in v0.12.0

func (c *Context) KillConnection(connID uint32) error

KillConnection terminates the connection associated with |connID|.

func (*Context) LoadInfile added in v0.12.0

func (c *Context) LoadInfile(filename string) (io.ReadCloser, error)

LoadInfile loads the remote file |filename| from the client. Returns a |ReadCloser| for the file's contents. Returns an error if this functionality is not supported.

func (*Context) NewCtxWithClient added in v0.12.0

func (c *Context) NewCtxWithClient(client Client) *Context

NewCtxWithClient returns a new Context with the given [client]

func (*Context) NewErrgroup added in v0.11.0

func (c *Context) NewErrgroup() (*errgroup.Group, *Context)

func (*Context) NewSubContext

func (c *Context) NewSubContext() (*Context, context.CancelFunc)

NewSubContext creates a new sub-context with the current context as parent. Returns the resulting context.CancelFunc as well as the new *sql.Context, which be used to cancel the new context before the parent is finished.

func (*Context) Pid

func (c *Context) Pid() uint64

Pid returns the process id associated with this context.

func (*Context) Query

func (c *Context) Query() string

Query returns the query string associated with this context.

func (*Context) QueryTime

func (c *Context) QueryTime() time.Time

QueryTime returns the time.Time when the context associated with this query was created

func (*Context) RootSpan

func (c *Context) RootSpan() trace.Span

RootSpan returns the root span, if any.

func (*Context) SetQueryTime added in v0.15.0

func (c *Context) SetQueryTime(t time.Time)

SetQueryTime updates the queryTime to the given time

func (*Context) Span

func (c *Context) Span(
	opName string,
	opts ...trace.SpanStartOption,
) (trace.Span, *Context)

Span creates a new tracing span with the given context. It will return the span and a new context that should be passed to all children of this span.

func (*Context) Warn

func (c *Context) Warn(code int, msg string, args ...interface{})

Warn adds a warning to the session.

func (*Context) WithContext

func (c *Context) WithContext(ctx context.Context) *Context

WithContext returns a new context with the given underlying context.

func (*Context) WithQuery added in v0.12.0

func (c *Context) WithQuery(q string) *Context

type ContextOption

type ContextOption func(*Context)

ContextOption is a function to configure the context.

func WithMemoryManager

func WithMemoryManager(m *MemoryManager) ContextOption

WithMemoryManager adds the given memory manager to the context.

func WithPid

func WithPid(pid uint64) ContextOption

WithPid adds the given pid to the context.

func WithProcessList added in v0.11.0

func WithProcessList(p ProcessList) ContextOption

func WithQuery

func WithQuery(q string) ContextOption

WithQuery adds the given query to the context.

func WithRootSpan

func WithRootSpan(s trace.Span) ContextOption

WithRootSpan sets the root span of the context.

func WithServices added in v0.12.0

func WithServices(services Services) ContextOption

WithServices sets the services for the Context

func WithSession

func WithSession(s Session) ContextOption

WithSession adds the given session to the context.

func WithTracer

func WithTracer(t trace.Tracer) ContextOption

WithTracer adds the given tracer to the context.

type ContextProvider added in v0.19.0

type ContextProvider interface {
	// NewContext creates a new sql.Context instance for the connection |c|. The
	// optional |query| can be specified to populate the sql.Context's query field.
	NewContext(ctx context.Context, c *mysql.Conn, query string) (*Context, error)
}

ContextProvider creates sql.Context instances from a database connection.

type ConvertInRange added in v0.15.0

type ConvertInRange bool
const (
	InRange    ConvertInRange = true
	OutOfRange                = false
)

type CountingRowIter added in v0.18.0

type CountingRowIter struct {
	RowIter
	Stats *DescribeStats
}

func NewCountingRowIter added in v0.18.0

func NewCountingRowIter(iter RowIter, describable WithDescribeStats) CountingRowIter

func (CountingRowIter) Next added in v0.18.0

func (c CountingRowIter) Next(ctx *Context) (Row, error)

type CreateFunc0Args

type CreateFunc0Args func() Expression

type CreateFunc1Args

type CreateFunc1Args func(e1 Expression) Expression

type CreateFunc2Args

type CreateFunc2Args func(e1, e2 Expression) Expression

type CreateFunc3Args

type CreateFunc3Args func(e1, e2, e3 Expression) Expression

type CreateFunc4Args

type CreateFunc4Args func(e1, e2, e3, e4 Expression) Expression

type CreateFunc5Args

type CreateFunc5Args func(e1, e2, e3, e4, e5 Expression) Expression

type CreateFunc6Args

type CreateFunc6Args func(e1, e2, e3, e4, e5, e6 Expression) Expression

type CreateFunc7Args

type CreateFunc7Args func(e1, e2, e3, e4, e5, e6, e7 Expression) Expression

type CreateFuncNArgs

type CreateFuncNArgs func(args ...Expression) (Expression, error)

type Database

type Database interface {
	Nameable
	// GetTableInsensitive retrieves a table by its case-insensitive name. To be SQL compliant, databases should not
	// allow two tables with the same case-insensitive name. Behavior is undefined when two tables have the same
	// case-insensitive name.
	GetTableInsensitive(ctx *Context, tblName string) (Table, bool, error)
	// GetTableNames returns the table names of every table in the database. It does not return the names of temporary
	// tables
	GetTableNames(ctx *Context) ([]string, error)
}

Database represents the database. Its primary job is to provide access to all tables.

type DatabaseProvider added in v0.11.0

type DatabaseProvider interface {
	// Database returns the database with the name given, or sql.ErrDatabaseNotFound if it doesn't exist.
	Database(ctx *Context, name string) (Database, error)
	// HasDatabase checks if the Database exists in the provider.
	HasDatabase(ctx *Context, name string) bool
	// AllDatabases returns a slice of all Databases in the provider.
	AllDatabases(ctx *Context) []Database
}

DatabaseProvider is the fundamental interface to integrate with the engine. It provides access to all databases in a given backend. A DatabaseProvider is provided to the Catalog when the engine is initialized.

func NewDatabaseProvider added in v0.11.0

func NewDatabaseProvider(dbs ...Database) DatabaseProvider

type DatabaseSchema added in v0.19.0

type DatabaseSchema interface {
	Database
	// SchemaName returns the schema name for Doltgres, or database name if empty for Dolt.
	SchemaName() string
}

DatabaseSchema is a schema that can be queried for tables. It is functionally equivalent to a Database (and in MySQL, database and Schema are synonymous). Some providers may have additional schemas.

type DatabaseSchemaTable added in v0.19.0

type DatabaseSchemaTable interface {
	Table
	// DatabaseSchema returns the database schema that this table belongs to.
	DatabaseSchema() DatabaseSchema
}

DatabaseSchemaTable is a table that can return the database schema it belongs to. This interface must be implemented for correct function of some DDL in databases that implement SchemaDatabase.

type Databaseable added in v0.12.0

type Databaseable interface {
	Database() string
}

Databaseable is a node with a string reference to a database

type Databaser

type Databaser interface {
	// Database the current database.
	Database() Database
	// WithDatabase returns a new node instance with the database replaced with
	// the one given as parameter.
	WithDatabase(Database) (Node, error)
}

Databaser is a node that contains a reference to a database.

type DatetimeType

type DatetimeType interface {
	Type
	ConvertWithoutRangeCheck(v interface{}) (time.Time, error)
	MaximumTime() time.Time
	MinimumTime() time.Time
	Precision() int
}

DatetimeType represents DATE, DATETIME, and TIMESTAMP. https://dev.mysql.com/doc/refman/8.0/en/datetime.html The type of the returned value is time.Time.

type DebugStringer

type DebugStringer interface {
	// DebugString prints a debug string of the node in question.
	DebugString() string
}

DebugStringer is shared by implementors of Node and Expression, and is used for debugging the analyzer. It allows a node or expression to be printed in greater detail than its default String() representation.

type DecimalType

type DecimalType interface {
	Type
	// ConvertToNullDecimal converts the given value to a decimal.NullDecimal if it has a compatible type. It is worth
	// noting that Convert() returns a nil value for nil inputs, and also returns decimal.Decimal rather than
	// decimal.NullDecimal.
	ConvertToNullDecimal(v interface{}) (decimal.NullDecimal, error)
	//ConvertNoBoundsCheck normalizes an interface{} to a decimal type without performing expensive bound checks
	ConvertNoBoundsCheck(v interface{}) (decimal.Decimal, error)
	// BoundsCheck rounds and validates a decimal, returning the decimal,
	// whether the value was out of range, and an error.
	BoundsCheck(v decimal.Decimal) (decimal.Decimal, ConvertInRange, error)
	// ExclusiveUpperBound returns the exclusive upper bound for this Decimal.
	// For example, DECIMAL(5,2) would return 1000, as 999.99 is the max represented.
	ExclusiveUpperBound() decimal.Decimal
	// MaximumScale returns the maximum scale allowed for the current precision.
	MaximumScale() uint8
	// Precision returns the base-10 precision of the type, which is the total number of digits. For example, a
	// precision of 3 means that 999, 99.9, 9.99, and .999 are all valid maximums (depending on the scale).
	Precision() uint8
	// Scale returns the scale, or number of digits after the decimal, that may be held.
	// This will always be less than or equal to the precision.
	Scale() uint8
}

DecimalType represents the DECIMAL type. https://dev.mysql.com/doc/refman/8.0/en/fixed-point-types.html The type of the returned value is decimal.Decimal.

type DeferredType added in v0.12.0

type DeferredType interface {
	Type
	IsDeferred() bool
	Name() string
}

DeferredType is a placeholder for prepared statements that is replaced by the BindVar type on re-analysis.

type DeletableTable

type DeletableTable interface {
	Table
	// Deleter returns a RowDeleter for this table. The RowDeleter will get one call to Delete for each row to be deleted,
	// and will end with a call to Close() to finalize the delete operation.
	Deleter(*Context) RowDeleter
}

DeletableTable is a table that can delete rows.

type Describable added in v0.18.0

type Describable interface {
	Describe(options DescribeOptions) string
}

type DescribeOptions added in v0.18.0

type DescribeOptions struct {
	Analyze   bool
	Estimates bool
	Debug     bool
	Plan      bool
}

func (DescribeOptions) String added in v0.18.0

func (d DescribeOptions) String() string

type DescribeStats added in v0.18.0

type DescribeStats struct {
	HasStats           bool
	EstimatedRowCount  uint64
	ActualRowCount     uint64
	NumberOfIterations uint64
	Cost               float64
}

func (*DescribeStats) GetDescribeStatsString added in v0.18.0

func (e *DescribeStats) GetDescribeStatsString(options DescribeOptions) string

GetDescribeStatsString implements WithDescribeStats

func (DescribeStats) GetEstimatedCost added in v0.18.0

func (e DescribeStats) GetEstimatedCost() float64

GetEstimatedCost implements WithDescribeStats

func (DescribeStats) GetEstimatedRowCount added in v0.18.0

func (e DescribeStats) GetEstimatedRowCount() uint64

GetEstimatedRowCount implements WithDescribeStats

func (*DescribeStats) SetDescribeStats added in v0.18.0

func (e *DescribeStats) SetDescribeStats(newStats DescribeStats)

type Disposable

type Disposable interface {
	// Dispose the contents.
	Dispose()
}

Disposable objects can erase all their content when they're no longer in use. Expressions and Nodes that implement Disposable will have Dispose called on them as a final stage of query execution. This can be used to clean up cached memory that wouldn't get caught via the normal garbage collection process.

type DisposeFunc

type DisposeFunc func()

DisposeFunc is a function to completely erase a cache and remove it from the manager.

type DriverIndex

type DriverIndex interface {
	Index
	// Driver ID of the index.
	Driver() string
}

DriverIndex is an index managed by a driver, as opposed to natively by a DB table. Deprecated. This interface is incompletely supported and may be removed.

type DriverIndexLookup

type DriverIndexLookup interface {
	Lookup() IndexLookup

	// Values returns the values in the subset of the index. These are used to populate the index via the driver.
	Values(Partition) (IndexValueIter, error)

	// Indexes returns the IDs of all indexes involved in this lookup.
	Indexes() []string
}

DriverIndexLookup is a subset of an index. More specific interfaces can be implemented to grant more capabilities to the index lookup. Deprecated. This interface is incompletely supported and may be removed.

type DriverIndexableTable

type DriverIndexableTable interface {
	IndexAddressableTable
	// WithDriverIndexLookup returns a version of this table with the given lookup applied.
	// This method is currently unused in the engine.
	WithDriverIndexLookup(DriverIndexLookup) Table
	// IndexKeyValues returns an iterator over partitions and ultimately the rows of the table to compute the value of an
	// index for every row in this table. Used when creating an index for access through an IndexDriver.
	IndexKeyValues(*Context, []string) (PartitionIndexKeyValueIter, error)
}

DriverIndexableTable represents a table that supports being indexed and receiving indexes to be able to speed up its execution. Deprecated. DriverIndexableTable support is currently incomplete. The engine will pass CREATE INDEX with a custom driver through to |IndexKeyValues|, but will not apply DriverIndexes via |WithDriverIndexLookup|. There are currently no plans to revive this interface.

type DynamicColumnsTable added in v0.17.0

type DynamicColumnsTable interface {
	// AllColumns returns all columns that need to be resolved
	// for this particular table.
	AllColumns(*Context) (Schema, error)
	// WithDefaultsSchema returns a table with a fully resolved
	// schema for every column in AllColumns.
	WithDefaultsSchema(Schema) (Table, error)
	// HasDynamicColumns indicates that a type implements the
	// DynamicColumnsTable interface.
	HasDynamicColumns() bool
}

DynamicColumnsTable is a table with a schema that is variable depending on the tables in the database (information_schema.columns).

type EditOpenerCloser added in v0.15.0

type EditOpenerCloser interface {
	// StatementBegin is called before the first operation of a statement. Integrators should mark the state of the data
	// in some way that it may be returned to in the case of an error.
	StatementBegin(ctx *Context)
	// DiscardChanges is called if a statement encounters an error, and all current changes since the statement beginning
	// should be discarded.
	DiscardChanges(ctx *Context, errorEncountered error) error
	// StatementComplete is called after the last operation of the statement, indicating that it has successfully completed.
	// The mark set in StatementBegin may be removed, and a new one should be created on the next StatementBegin.
	StatementComplete(ctx *Context) error
}

EditOpenerCloser is the base interface for table editors, and deals with statement boundaries.

type EmptyProcessList added in v0.11.0

type EmptyProcessList struct{}

EmptyProcessList is a no-op implementation of ProcessList suitable for use in tests or other installations that don't require a process list

func (EmptyProcessList) AddConnection added in v0.15.0

func (e EmptyProcessList) AddConnection(id uint32, addr string)

func (EmptyProcessList) AddPartitionProgress added in v0.11.0

func (e EmptyProcessList) AddPartitionProgress(pid uint64, tableName, partitionName string, total int64)

func (EmptyProcessList) AddTableProgress added in v0.11.0

func (e EmptyProcessList) AddTableProgress(pid uint64, name string, total int64)

func (EmptyProcessList) BeginQuery added in v0.15.0

func (e EmptyProcessList) BeginQuery(ctx *Context, query string) (*Context, error)

func (EmptyProcessList) ConnectionReady added in v0.15.0

func (e EmptyProcessList) ConnectionReady(Session)

func (EmptyProcessList) Done added in v0.11.0

func (e EmptyProcessList) Done(pid uint64)

func (EmptyProcessList) EndQuery added in v0.15.0

func (e EmptyProcessList) EndQuery(ctx *Context)

func (EmptyProcessList) Kill added in v0.11.0

func (e EmptyProcessList) Kill(connID uint32)

func (EmptyProcessList) Processes added in v0.11.0

func (e EmptyProcessList) Processes() []Process

func (EmptyProcessList) RemoveConnection added in v0.15.0

func (e EmptyProcessList) RemoveConnection(uint32)

func (EmptyProcessList) RemovePartitionProgress added in v0.11.0

func (e EmptyProcessList) RemovePartitionProgress(pid uint64, tableName, partitionName string)

func (EmptyProcessList) RemoveTableProgress added in v0.11.0

func (e EmptyProcessList) RemoveTableProgress(pid uint64, name string)

func (EmptyProcessList) UpdatePartitionProgress added in v0.11.0

func (e EmptyProcessList) UpdatePartitionProgress(pid uint64, tableName, partitionName string, delta int64)

func (EmptyProcessList) UpdateTableProgress added in v0.11.0

func (e EmptyProcessList) UpdateTableProgress(pid uint64, name string, delta int64)

type Engine added in v0.9.0

type Engine struct {
	Name string
	// contains filtered or unexported fields
}

Engine represents a sql engine.

func (Engine) Comment added in v0.9.0

func (e Engine) Comment() string

Comment returns a brief description of the storage engine.

func (Engine) Savepoints added in v0.9.0

func (e Engine) Savepoints() string

Savepoints returns whether the storage engine supports savepoints.

func (Engine) String added in v0.9.0

func (e Engine) String() string

String returns the string representation of the Engine.

func (Engine) Support added in v0.9.0

func (e Engine) Support() string

Support returns the server's level of support for the storage engine,

func (Engine) Transactions added in v0.9.0

func (e Engine) Transactions() string

Transactions returns whether the storage engine supports transactions.

func (Engine) XA added in v0.9.0

func (e Engine) XA() string

XA returns whether the storage engine supports XA transactions.

type EnumType

type EnumType interface {
	Type
	// At returns the string at the given index, as well if the string was found.
	At(index int) (string, bool)
	CharacterSet() CharacterSetID
	Collation() CollationID
	// IndexOf returns the index of the given string. If the string was not found, then this returns -1.
	IndexOf(v string) int
	// NumberOfElements returns the number of enumerations.
	NumberOfElements() uint16
	// Values returns the elements, in order, of every enumeration.
	Values() []string
}

EnumType represents the ENUM type. https://dev.mysql.com/doc/refman/8.0/en/enum.html The type of the returned value is uint16.

type EqualityIndexBuilder added in v0.19.0

type EqualityIndexBuilder struct {
	// contains filtered or unexported fields
}

EqualityIndexBuilder is a range builder builds equality expressions more quickly than the default builder

func NewEqualityIndexBuilder added in v0.19.0

func NewEqualityIndexBuilder(idx Index) *EqualityIndexBuilder

func (*EqualityIndexBuilder) AddEquality added in v0.19.0

func (b *EqualityIndexBuilder) AddEquality(_ *Context, colIdx int, k interface{}) error

AddEquality represents colExpr = key. For IN expressions, pass all of them in the same AddEquality call.

func (*EqualityIndexBuilder) Build added in v0.19.0

type EquivSets added in v0.16.0

type EquivSets struct {
	// contains filtered or unexported fields
}

EquivSets maintains column equivalency sets created by WHERE a = b filters.

func (*EquivSets) Add added in v0.16.0

func (e *EquivSets) Add(cols ColSet)

Add adds a new equivalence set, compacting any intersections with existing sets.

func (*EquivSets) Len added in v0.16.0

func (e *EquivSets) Len() int

func (*EquivSets) Sets added in v0.16.0

func (e *EquivSets) Sets() []ColSet

func (*EquivSets) String added in v0.16.0

func (e *EquivSets) String() string

type EventDatabase added in v0.15.0

type EventDatabase interface {
	Database
	// GetEvent returns the desired EventDefinition and if it exists in the database.
	// All time values of EventDefinition needs to be converted into appropriate TZ.
	GetEvent(ctx *Context, name string) (EventDefinition, bool, error)
	// GetEvents returns all EventDefinition for the database, as well as an opaque token that is used to
	// track if events need to be reloaded. This token is specific to an EventDatabase and is passed to
	// NeedsToReloadEvents so that integrators can examine it and signal if events need to be reloaded. If
	// integrators do not need to implement out-of-band event reloading, then they can simply return nil for
	// the token. All time values of EventDefinition needs to be converted into appropriate TZ.
	GetEvents(ctx *Context) (events []EventDefinition, token interface{}, err error)
	// SaveEvent stores the given EventDefinition to the database. The integrator should verify that
	// the name of the new event is unique amongst existing events. The time values are converted
	// into UTC TZ for storage. It returns whether the event status is enabled.
	SaveEvent(ctx *Context, ed EventDefinition) (bool, error)
	// DropEvent removes the EventDefinition with the matching name from the database.
	DropEvent(ctx *Context, name string) error
	// UpdateEvent updates existing event stored in the database with the given EventDefinition
	// with the updates. The original name event is required for renaming of an event.
	// The time values are converted into UTC TZ for storage. It returns whether the event status is enabled.
	UpdateEvent(ctx *Context, originalName string, ed EventDefinition) (bool, error)
	// UpdateLastExecuted updated the lastExecuted metadata for the given event.
	// The lastExecuted time is converted into UTC TZ for storage.
	UpdateLastExecuted(ctx *Context, eventName string, lastExecuted time.Time) error
	// NeedsToReloadEvents allows integrators to signal that out-of-band changes have modified an event (i.e. an
	// event was modified without going through the SaveEvent or UpdateEvent methods in this interface), and that
	// event definitions need to be reloaded. The event executor will periodically check to see if it needs to reload
	// the events from a database by calling this method and if this method returns true, then the event executor will
	// call the ReloadEvents method next to load in the new event definitions. The opaque token is the same token
	// returned from the last call to GetEvents and integrators are free to use whatever underlying data they
	// need to track whether an out-of-band event change has occurred. If integrators to do not support events
	// changing out-of-band, then they can simply return false from this method.
	NeedsToReloadEvents(ctx *Context, token interface{}) (bool, error)
}

EventDatabase is a database that supports the creation and execution of events. The engine will handle execution logic for events. Integrators only need to store and retrieve EventDefinition.

type EventDefinition added in v0.15.0

type EventDefinition struct {
	// The name of this event. Event names in a database are unique.
	Name string
	// The SQL statements to be executed when this event is executed.
	EventBody string
	// The timezone offset the event was created or last altered at.
	TimezoneOffset string
	// The enabled or disabled status of this event.
	Status string
	// The user or account who created this scheduled event.
	Definer string
	// The SQL_MODE in effect when this event was created.
	SqlMode string
	// The time at which the event was created.
	CreatedAt time.Time
	// The time at which the event was last altered.
	LastAltered time.Time
	// The time at which the event was last executed.
	LastExecuted time.Time

	/* Fields parsed from the CREATE EVENT statement */
	Comment              string
	OnCompletionPreserve bool
	HasExecuteAt         bool
	ExecuteAt            time.Time
	ExecuteEvery         string
	Starts               time.Time // STARTS is always defined when EVERY is defined.
	HasEnds              bool
	Ends                 time.Time
}

EventDefinition describes a scheduled event.

func (*EventDefinition) ConvertTimesFromUTCToTz added in v0.18.0

func (e *EventDefinition) ConvertTimesFromUTCToTz(tz string) *EventDefinition

ConvertTimesFromUTCToTz returns a new EventDefinition with all its time values converted from UTC TZ to the given TZ. This function should only be used when needing to display data that includes the time values in string format for such as SHOW EVENTS or SHOW CREATE EVENT statements.

func (*EventDefinition) CreateEventStatement added in v0.18.0

func (e *EventDefinition) CreateEventStatement() string

CreateEventStatement returns a CREATE EVENT statement for this event.

func (*EventDefinition) GetNextExecutionTime added in v0.18.0

func (e *EventDefinition) GetNextExecutionTime(curTime time.Time) (time.Time, bool, error)

GetNextExecutionTime returns the next execution time for the event, which depends on AT or EVERY field of EventDefinition. It also returns whether the event is expired.

type EventOnScheduleEveryInterval added in v0.18.0

type EventOnScheduleEveryInterval struct {
	Years   int64
	Months  int64
	Days    int64
	Hours   int64
	Minutes int64
	Seconds int64
}

EventOnScheduleEveryInterval is used to store ON SCHEDULE EVERY clause's interval definition. It is equivalent of expression.TimeDelta without microseconds field.

func EventOnScheduleEveryIntervalFromString added in v0.18.0

func EventOnScheduleEveryIntervalFromString(every string) (*EventOnScheduleEveryInterval, error)

EventOnScheduleEveryIntervalFromString returns *EventOnScheduleEveryInterval parsing given interval string such as `2 DAY` or `'1:2' MONTH_DAY`. This function is used in Dolt to construct EventOnScheduleEveryInterval value for the EventDefinition.

func NewEveryInterval added in v0.18.0

func NewEveryInterval(y, mo, d, h, mi, s int64) *EventOnScheduleEveryInterval

func (*EventOnScheduleEveryInterval) GetIntervalValAndField added in v0.18.0

func (e *EventOnScheduleEveryInterval) GetIntervalValAndField() (string, string)

GetIntervalValAndField returns ON SCHEDULE EVERY clause's interval value and field type in string format (e.g. returns "'1:2'" and "MONTH_DAY" for 1 month and 2 day or returns "4" and "HOUR" for 4 hour intervals).

type EventScheduler added in v0.18.0

type EventScheduler interface {
	// AddEvent is called when there is an event created at runtime.
	AddEvent(ctx *Context, edb EventDatabase, event EventDefinition)
	// UpdateEvent is called when there is an event altered at runtime.
	UpdateEvent(ctx *Context, edb EventDatabase, orgEventName string, event EventDefinition)
	// RemoveEvent is called when there is an event dropped at runtime. This function
	// removes the given event if it exists in the enabled events list of the EventSchedulerStatus.
	RemoveEvent(dbName, eventName string)
	// RemoveSchemaEvents is called when there is a database dropped at runtime. This function
	// removes all events of given database that exist in the enabled events list of the EventSchedulerStatus.
	RemoveSchemaEvents(dbName string)
}

EventScheduler is an interface used for notifying the EventSchedulerStatus for querying any events related statements. This allows plan Nodes to communicate to the EventSchedulerStatus.

type EventStatus added in v0.18.0

type EventStatus byte

EventStatus represents an event status that is defined for an event.

const (
	EventStatus_Enable EventStatus = iota
	EventStatus_Disable
	EventStatus_DisableOnSlave
)

func EventStatusFromString added in v0.18.0

func EventStatusFromString(status string) (EventStatus, error)

EventStatusFromString returns EventStatus based on the given string value. This function is used in Dolt to get EventStatus value for the EventDefinition.

func (EventStatus) String added in v0.18.0

func (e EventStatus) String() string

String returns the original SQL representation.

type ExecSourceRel added in v0.15.0

type ExecSourceRel interface {
	Node
	RowIter(ctx *Context, r Row) (RowIter, error)
}

ExecSourceRel is a node that has no children and is directly row generating.

type Expression

type Expression interface {
	Resolvable
	fmt.Stringer
	// Type returns the expression type.
	Type() Type
	// IsNullable returns whether the expression can be null.
	IsNullable() bool
	// Eval evaluates the given row and returns a result.
	Eval(ctx *Context, row Row) (interface{}, error)
	// Children returns the children expressions of this expression.
	Children() []Expression
	// WithChildren returns a copy of the expression with children replaced.
	// It will return an error if the number of children is different than
	// the current number of children. They must be given in the same order
	// as they are returned by Children.
	WithChildren(children ...Expression) (Expression, error)
}

Expression is a combination of one or more SQL expressions.

func NillaryWithChildren added in v0.9.0

func NillaryWithChildren(expr Expression, children ...Expression) (Expression, error)

NillaryWithChildren is a common implementation of expression.WithChildren for expressions with no children.

type Expression2 added in v0.12.0

type Expression2 interface {
	Expression
	// Eval2 evaluates the given row frame and returns a result.
	Eval2(ctx *Context, row Row2) (Value, error)
	// Type2 returns the expression type.
	Type2() Type2
}

Expression2 is an experimental future interface alternative to Expression to provide faster access.

type ExpressionWithNodes added in v0.15.0

type ExpressionWithNodes interface {
	Expression
	// NodeChildren returns all node children.
	NodeChildren() []Node
	// WithNodeChildren returns a copy of the expression with its node children replaced. It will return an error if the
	// number of children is different than the current number of children. They must be given in the same order as they
	// are returned by NodeChildren.
	WithNodeChildren(children ...Node) (ExpressionWithNodes, error)
}

ExpressionWithNodes is an expression that contains nodes as children.

type Expressioner

type Expressioner interface {
	// Expressions returns the list of expressions contained by the node.
	Expressions() []Expression
	// WithExpressions returns a copy of the node with expressions replaced.
	// It will return an error if the number of expressions is different than
	// the current number of expressions. They must be given in the same order
	// as they are returned by Expressions.
	WithExpressions(...Expression) (Node, error)
}

Expressioner is a node that contains expressions.

type ExtendedIndex added in v0.16.0

type ExtendedIndex interface {
	Index
	// ExtendedExpressions returns the same result as Expressions, but appends any primary keys that are implicitly in
	// the index. The appended primary keys are in declaration order.
	ExtendedExpressions() []string
	// ExtendedColumnExpressionTypes returns the same result as ColumnExpressionTypes, but appends the type of any
	// primary keys that are implicitly in the index. The appended primary keys are in declaration order.
	ExtendedColumnExpressionTypes() []ColumnExpressionType
}

ExtendedIndex is an extension of Index, that allows access to appended primary keys. MySQL internally represents an index as the collection of all explicitly referenced columns, while appending any unreferenced primary keys to the end (in order of their declaration). For full MySQL compatibility, integrators are encouraged to mimic this, however not all implementations may define their indexes (on tables with primary keys) in this way, therefore this interface is optional.

type ExternalStoredProcedureDetails added in v0.12.0

type ExternalStoredProcedureDetails struct {
	// Name is the name of the external stored procedure. If two external stored procedures share a name, then they're
	// considered overloaded. Standard stored procedures do not support overloading.
	Name string
	// Schema describes the row layout of the RowIter returned from Function.
	Schema Schema
	// Function is the implementation of the external stored procedure. All functions should have the following definition:
	// `func(*Context, <PARAMETERS>) (RowIter, error)`. The <PARAMETERS> may be any of the following types: `bool`,
	// `string`, `[]byte`, `int8`-`int64`, `uint8`-`uint64`, `float32`, `float64`, `time.Time`, or `Decimal`
	// (shopspring/decimal). The architecture-dependent types `int` and `uint` (without a number) are also supported.
	// It is valid to return a nil RowIter if there are no rows to be returned.
	//
	// Each parameter, by default, is an IN parameter. If the parameter type is a pointer, e.g. `*int32`, then it
	// becomes an INOUT parameter. INOUT parameters will be given their zero value if the parameter's value is nil.
	// There is no way to set a parameter as an OUT parameter.
	//
	// Values are converted to their nearest type before being passed in, following the conversion rules of their
	// related SQL types. The exceptions are `time.Time` (treated as a `DATETIME`), string (treated as a `LONGTEXT` with
	// the default collation) and Decimal (treated with a larger precision and scale). Take extra care when using decimal
	// for an INOUT parameter, to ensure that the returned value fits the original's precision and scale, else an error
	// will occur.
	//
	// As functions support overloading, each variant must have a completely unique function signature to prevent
	// ambiguity. Uniqueness is determined by the number of parameters. If two functions are returned that have the same
	// name and same number of parameters, then an error is thrown. If the last parameter is variadic, then the stored
	// procedure functions as though it has the integer-max number of parameters. When an exact match is not found for
	// overloaded functions, the largest function is used (which in this case will be the variadic function). Also, due
	// to the usage of the integer-max for the parameter count, only one variadic function is allowed per function name.
	// The type of the variadic parameter may not have a pointer type.
	Function interface{}
	// If true, the procedure is ReadOnly and can be run against a locked or read-only server.
	ReadOnly bool
	// If true, then this procedure's access control requires that the user must have explicit Execute permissions
	// on the procedure in question. If false, then the user will be granted access to the procedure if they have Execute
	// permissions on the DB. MySQL does not support anything like this, but it is useful for Dolt procedures which
	// grant elevated access.
	AdminOnly bool
}

ExternalStoredProcedureDetails are the details of an external stored procedure. Compared to standard stored procedures, external ones are considered "built-in", in that they're not created by the user, and may not be modified or deleted by a user. In addition, they're implemented as a function taking standard parameters, compared to stored procedures being implemented as expressions.

func (ExternalStoredProcedureDetails) FakeCreateProcedureStmt added in v0.12.0

func (espd ExternalStoredProcedureDetails) FakeCreateProcedureStmt() string

FakeCreateProcedureStmt returns a parseable CREATE PROCEDURE statement for this external stored procedure, as some tools (such as Java's JDBC connector) require a valid statement in some situations.

type ExternalStoredProcedureProvider added in v0.14.0

type ExternalStoredProcedureProvider interface {
	// ExternalStoredProcedure returns the external stored procedure details for the procedure with the specified name
	// that is able to accept the specified number of parameters. If no matching external stored procedure is found,
	// nil, nil is returned. If an unexpected error is encountered, it is returned as the error parameter.
	ExternalStoredProcedure(ctx *Context, name string, numOfParams int) (*ExternalStoredProcedureDetails, error)
	// ExternalStoredProcedures returns a slice of all external stored procedure details with the specified name. External
	// stored procedures can overload the same name with different arguments, so this method enables a caller to see all
	// available variants with the specified name. If no matching external stored procedures are found, an
	// empty slice is returned, with a nil error. If an unexpected error is encountered, it is returned as the
	// error parameter.
	ExternalStoredProcedures(ctx *Context, name string) ([]ExternalStoredProcedureDetails, error)
}

ExternalStoredProcedureProvider provides access to built-in stored procedures. These procedures are implemented as functions, instead of as SQL statements. The returned stored procedures cannot be modified or deleted.

type ExternalStoredProcedureRegistry added in v0.14.0

type ExternalStoredProcedureRegistry struct {
	// contains filtered or unexported fields
}

ExternalStoredProcedureRegistry manages a collection of ExternalStoredProcedures and encapsulates the logic for looking up external stored procedures based on name and number of arguments.

func NewExternalStoredProcedureRegistry added in v0.14.0

func NewExternalStoredProcedureRegistry() ExternalStoredProcedureRegistry

NewExternalStoredProcedureRegistry creates a new, empty instance of ExternalStoredProcedureRegistry.

func (*ExternalStoredProcedureRegistry) LookupByName added in v0.14.0

LookupByName returns all stored procedure variants registered with the specified name, no matter how many parameters they require. If no external stored procedures are registered with the specified name, nil is returned, with no error. If an unexpected error occurs, it is returned as the error parameter.

func (*ExternalStoredProcedureRegistry) LookupByNameAndParamCount added in v0.14.0

func (epd *ExternalStoredProcedureRegistry) LookupByNameAndParamCount(name string, numOfParams int) (*ExternalStoredProcedureDetails, error)

LookupByNameAndParamCount returns the external stored procedure registered with the specified name and able to accept the specified number of parameters. If no external stored procedures are registered with the specified name and able to accept the specified number of parameters, nil is returned with no error. If an unexpected error occurs, it is returned as the error param.

func (*ExternalStoredProcedureRegistry) Register added in v0.14.0

func (epd *ExternalStoredProcedureRegistry) Register(procedureDetails ExternalStoredProcedureDetails)

Register adds an external stored procedure to this registry.

type FastIntSet added in v0.14.0

type FastIntSet struct {
	// contains filtered or unexported fields
}

FastIntSet keeps track of a set of integers. It does not perform any allocations when the values are small. It is not thread-safe.

func NewFastIntSet added in v0.14.0

func NewFastIntSet(vals ...int) FastIntSet

NewFastIntSet returns a set initialized with the given values.

func (*FastIntSet) Add added in v0.14.0

func (s *FastIntSet) Add(i int)

Add adds a value to the set. No-op if the value is already in the set.

func (*FastIntSet) AddRange added in v0.14.0

func (s *FastIntSet) AddRange(from, to int)

AddRange adds values 'from' up to 'to' (inclusively) to the set. E.g. AddRange(1,5) adds the values 1, 2, 3, 4, 5 to the set. 'to' must be >= 'from'. AddRange is always more efficient than individual Adds.

func (FastIntSet) Contains added in v0.14.0

func (s FastIntSet) Contains(i int) bool

Contains returns true if the set contains the value.

func (FastIntSet) Copy added in v0.14.0

func (s FastIntSet) Copy() FastIntSet

Copy returns a copy of s which can be modified independently.

func (*FastIntSet) CopyFrom added in v0.14.0

func (s *FastIntSet) CopyFrom(c FastIntSet)

CopyFrom sets the receiver to a copy of c, which can then be modified independently.

func (FastIntSet) Difference added in v0.14.0

func (s FastIntSet) Difference(rhs FastIntSet) FastIntSet

Difference returns the elements of s that are not in rhs as a new set.

func (*FastIntSet) DifferenceWith added in v0.14.0

func (s *FastIntSet) DifferenceWith(rhs FastIntSet)

DifferenceWith removes any elements in rhs from this set.

func (FastIntSet) Empty added in v0.14.0

func (s FastIntSet) Empty() bool

Empty returns true if the set is empty.

func (FastIntSet) Equals added in v0.14.0

func (s FastIntSet) Equals(rhs FastIntSet) bool

Equals returns true if the two sets are identical.

func (FastIntSet) ForEach added in v0.14.0

func (s FastIntSet) ForEach(f func(i int))

ForEach calls a function for each value in the set (in increasing order).

func (FastIntSet) Intersection added in v0.14.0

func (s FastIntSet) Intersection(rhs FastIntSet) FastIntSet

Intersection returns the intersection of s and rhs as a new set.

func (*FastIntSet) IntersectionWith added in v0.14.0

func (s *FastIntSet) IntersectionWith(rhs FastIntSet)

IntersectionWith removes any elements not in rhs from this set.

func (FastIntSet) Intersects added in v0.14.0

func (s FastIntSet) Intersects(rhs FastIntSet) bool

Intersects returns true if s has any elements in common with rhs.

func (FastIntSet) Len added in v0.14.0

func (s FastIntSet) Len() int

Len returns the number of the elements in the set.

func (FastIntSet) Next added in v0.14.0

func (s FastIntSet) Next(startVal int) (int, bool)

Next returns the first value in the set which is >= startVal. If there is no value, the second return value is false.

func (FastIntSet) Ordered added in v0.14.0

func (s FastIntSet) Ordered() []int

Ordered returns a slice with all the integers in the set, in increasing order.

func (*FastIntSet) Remove added in v0.14.0

func (s *FastIntSet) Remove(i int)

Remove removes a value from the set. No-op if the value is not in the set.

func (*FastIntSet) Shift added in v0.14.0

func (s *FastIntSet) Shift(delta int) FastIntSet

Shift generates a new set which contains elements i+delta for elements i in the original set.

func (FastIntSet) String added in v0.14.0

func (s FastIntSet) String() string

String returns a list representation of elements. Sequential runs of positive numbers are shown as ranges. For example, for the set {0, 1, 2, 5, 6, 10}, the output is "(0-2,5,6,10)".

func (FastIntSet) SubsetOf added in v0.14.0

func (s FastIntSet) SubsetOf(rhs FastIntSet) bool

SubsetOf returns true if rhs contains all the elements in s.

func (FastIntSet) Union added in v0.14.0

func (s FastIntSet) Union(rhs FastIntSet) FastIntSet

Union returns the union of s and rhs as a new set.

func (*FastIntSet) UnionWith added in v0.14.0

func (s *FastIntSet) UnionWith(rhs FastIntSet)

UnionWith adds all the elements from rhs to this set.

type FilteredIndex added in v0.12.0

type FilteredIndex interface {
	Index
	// HandledFilters returns a subset of |filters| that are satisfied
	// by index lookups to this index.
	HandledFilters(filters []Expression) (handled []Expression)
}

FilteredIndex is an extension of |Index| that allows an index to declare certain filter predicates handled, allowing them to be removed from the overall plan for greater execution efficiency

type FilteredTable

type FilteredTable interface {
	Table
	// Filters returns the filter expressions that have been applied to this table.
	Filters() []Expression
	// HandledFilters returns the subset of the filter expressions given that this table can apply.
	HandledFilters(filters []Expression) []Expression
	// WithFilters returns a table with the given filter expressions applied.
	WithFilters(ctx *Context, filters []Expression) Table
}

FilteredTable is a table that can filter its result rows from RowIter using filter expressions that would otherwise be applied by a separate Filter node.

type ForeignKeyConstraint

type ForeignKeyConstraint struct {
	// Name is the name of the foreign key constraint
	Name string
	// Database is the name of the database of the table with the constraint
	Database string
	// SchemaName is the name of the schema of the table, for databases that support schemas.
	SchemaName string
	// Table is the name of the table with the constraint
	Table string
	// Columns is the list of columns in the table that are part of the foreign key
	Columns []string
	// ParentDatabase is the name of the database of the parent table
	ParentDatabase string
	// ParentSchema is the name of the schema of the parent table, for databases that support schemas.
	ParentSchema string
	// ParentTable is the name of the parent table
	ParentTable string
	// ParentColumns is the list of columns in the parent table that are part of the foreign key
	ParentColumns []string
	// OnUpdate is the action to take when the constraint is violated when a row in the parent table is updated
	OnUpdate ForeignKeyReferentialAction
	// OnDelete is the action to take when the constraint is violated when a row in the parent table is deleted
	OnDelete ForeignKeyReferentialAction
	// IsResolved is true if the foreign key has been resolved, false otherwise
	IsResolved bool
}

ForeignKeyConstraint declares a constraint between the columns of two tables.

func (*ForeignKeyConstraint) DebugString added in v0.10.0

func (f *ForeignKeyConstraint) DebugString() string

DebugString implements the DebugStringer interface.

func (*ForeignKeyConstraint) IsSelfReferential added in v0.12.0

func (f *ForeignKeyConstraint) IsSelfReferential() bool

IsSelfReferential returns whether this foreign key represents a self-referential foreign key.

type ForeignKeyConstraints added in v0.18.1

type ForeignKeyConstraints []*ForeignKeyConstraint

type ForeignKeyEditor added in v0.15.0

type ForeignKeyEditor interface {
	TableEditor
	IndexAddressable
}

ForeignKeyEditor is a TableEditor that is addressable via IndexLookup.

type ForeignKeyReferentialAction added in v0.12.0

type ForeignKeyReferentialAction string

ForeignKeyReferentialAction is the behavior for this foreign key with the relevant action is performed on the foreign table.

const (
	ForeignKeyReferentialAction_DefaultAction ForeignKeyReferentialAction = "DEFAULT" // No explicit action was specified
	ForeignKeyReferentialAction_Restrict      ForeignKeyReferentialAction = "RESTRICT"
	ForeignKeyReferentialAction_Cascade       ForeignKeyReferentialAction = "CASCADE"
	ForeignKeyReferentialAction_NoAction      ForeignKeyReferentialAction = "NO ACTION"
	ForeignKeyReferentialAction_SetNull       ForeignKeyReferentialAction = "SET NULL"
	ForeignKeyReferentialAction_SetDefault    ForeignKeyReferentialAction = "SET DEFAULT"
)

func (ForeignKeyReferentialAction) IsEquivalentToRestrict added in v0.15.0

func (f ForeignKeyReferentialAction) IsEquivalentToRestrict() bool

IsEquivalentToRestrict returns whether the referential action is equivalent to RESTRICT. In MySQL, although there are a number of referential actions, the majority of them are functionally ignored and default to RESTRICT.

type ForeignKeyTable

type ForeignKeyTable interface {
	IndexAddressableTable
	// CreateIndexForForeignKey creates an index for this table, using the provided parameters. Indexes created through
	// this function are specifically ones generated for use with a foreign key. Returns an error if the index name
	// already exists, or an index on the same columns already exists.
	CreateIndexForForeignKey(ctx *Context, indexDef IndexDef) error
	// GetDeclaredForeignKeys returns the foreign key constraints that are declared by this table.
	GetDeclaredForeignKeys(ctx *Context) ([]ForeignKeyConstraint, error)
	// GetReferencedForeignKeys returns the foreign key constraints that are referenced by this table.
	GetReferencedForeignKeys(ctx *Context) ([]ForeignKeyConstraint, error)
	// AddForeignKey adds the given foreign key constraint to the table. Returns an error if the foreign key name
	// already exists on any other table within the database.
	AddForeignKey(ctx *Context, fk ForeignKeyConstraint) error
	// DropForeignKey removes a foreign key from the table.
	DropForeignKey(ctx *Context, fkName string) error
	// UpdateForeignKey updates the given foreign key constraint. May range from updated table names to setting the
	// IsResolved boolean.
	UpdateForeignKey(ctx *Context, fkName string, fk ForeignKeyConstraint) error
	// GetForeignKeyEditor returns a ForeignKeyEditor for this table.
	GetForeignKeyEditor(ctx *Context) ForeignKeyEditor
}

ForeignKeyTable is a table that declares foreign key constraints, and can be referenced by other tables' foreign key constraints.

type ForeignKeyTables added in v0.18.1

type ForeignKeyTables []ForeignKeyTable

type Freeable

type Freeable interface {
	// Free the memory.
	Free()
}

Freeable objects can free their memory.

type FuncDepSet added in v0.16.0

type FuncDepSet struct {
	// contains filtered or unexported fields
}

FuncDepSet encodes functional dependencies for a relational expression. Common uses for functional dependencies:

  • Do a set of equality columns comprise a strict key? (lookup joins)
  • Is there a strict key for a relation? (decorrelate scopes)
  • What are the set of equivalent filters? (join planning)
  • Do a set of grouping columns constitute a strict key (only_full_group_by)

The docs here provide a summary of how functional dependencies work: - https://github.com/cockroachdb/cockroach/blob/5a6aa768cd945118e795d1086ba6f6365f6d1284/pkg/sql/opt/props/func_dep.go#L420

This object expects fields to be set in the following order: - notNull: what columns are non-nullable? - consts: what columns are constant? - equivs: transitive closure of column equivalence - keys: primary and secondary keys, simplified

We use an abbreviated form to represent functional dependencies. Normally, we would encode determinant and dependency sets like (det)-->(dep). I only keep track of determinant sets, that are assumed to represent keys into the entire relation. This works for simple cases where fractional functional dependencies can be discarded. The limitation is clear when you consider joins, whose FD sets can include keys that only implicitly determine a fraction of the total input set. The first key always determines the entire relation, which seems good enough for many cases. Maintaining partials sets also requires much less bookkeeping.

TODO: We used to not track dependency sets and only add keys that determined the entire relation. One observed downside of that approach is that left joins fail to convert equivalencies on the null-extended side to lax functional dependencies. For example, in the query below, the left join loses (a) == (m) because (m) can now be NULL:

SELECT * from adbcd LEFT_JOIN mnpq WHERE a = m

But we could maintain (m)~~>(n), which higher-level null enforcement (ex: GROUPING) can reclaim as equivalence. Although we now track partial dependency sets, this may still not be supported.

func NewCrossJoinFDs added in v0.16.0

func NewCrossJoinFDs(left, right *FuncDepSet) *FuncDepSet

NewCrossJoinFDs makes functional dependencies for a cross join between two relations.

func NewFilterFDs added in v0.16.0

func NewFilterFDs(fds *FuncDepSet, notNull ColSet, constant ColSet, equiv [][2]ColumnId) *FuncDepSet

func NewInnerJoinFDs added in v0.16.0

func NewInnerJoinFDs(left, right *FuncDepSet, filters [][2]ColumnId) *FuncDepSet

NewInnerJoinFDs makes functional dependencies for an inner join between two relations.

func NewLeftJoinFDs added in v0.16.0

func NewLeftJoinFDs(left, right *FuncDepSet, filters [][2]ColumnId) *FuncDepSet

func NewLookupFDs added in v0.16.0

func NewLookupFDs(fds *FuncDepSet, idxCols ColSet, notNull ColSet, constants ColSet, equiv *EquivSets) *FuncDepSet

func NewMax1RowFDs added in v0.16.0

func NewMax1RowFDs(cols, notNull ColSet) *FuncDepSet

func NewProjectFDs added in v0.16.0

func NewProjectFDs(fds *FuncDepSet, cols ColSet, distinct bool) *FuncDepSet

NewProjectFDs returns a new functional dependency set projecting a subset of cols.

func NewTablescanFDs added in v0.16.0

func NewTablescanFDs(all ColSet, strict []ColSet, lax []ColSet, notNull ColSet) *FuncDepSet

func (*FuncDepSet) AddConstants added in v0.16.0

func (f *FuncDepSet) AddConstants(cols ColSet)

func (*FuncDepSet) AddEquiv added in v0.16.0

func (f *FuncDepSet) AddEquiv(i, j ColumnId)

func (*FuncDepSet) AddEquivSet added in v0.16.0

func (f *FuncDepSet) AddEquivSet(cols ColSet)

func (*FuncDepSet) AddKey added in v0.16.0

func (f *FuncDepSet) AddKey(k Key)

func (*FuncDepSet) AddLaxKey added in v0.16.0

func (f *FuncDepSet) AddLaxKey(cols ColSet)

func (*FuncDepSet) AddNotNullable added in v0.16.0

func (f *FuncDepSet) AddNotNullable(cols ColSet)

func (*FuncDepSet) AddStrictKey added in v0.16.0

func (f *FuncDepSet) AddStrictKey(cols ColSet)

func (*FuncDepSet) All added in v0.16.0

func (f *FuncDepSet) All() ColSet

func (*FuncDepSet) ColsAreStrictKey added in v0.16.0

func (f *FuncDepSet) ColsAreStrictKey(cols ColSet) bool

ColsAreStrictKey returns true if the set of columns acts as a primary key into a relation.

func (*FuncDepSet) Constants added in v0.16.0

func (f *FuncDepSet) Constants() ColSet

func (*FuncDepSet) CopyKeys added in v0.16.0

func (f *FuncDepSet) CopyKeys() []Key

func (*FuncDepSet) Empty added in v0.18.0

func (f *FuncDepSet) Empty() bool

func (*FuncDepSet) Equiv added in v0.16.0

func (f *FuncDepSet) Equiv() *EquivSets

func (*FuncDepSet) EquivalenceClosure added in v0.16.0

func (f *FuncDepSet) EquivalenceClosure(cols ColSet) ColSet

func (*FuncDepSet) HasMax1Row added in v0.16.0

func (f *FuncDepSet) HasMax1Row() bool

func (*FuncDepSet) LaxKey added in v0.16.0

func (f *FuncDepSet) LaxKey() (ColSet, bool)

LaxKey returns a set of columns that act as a null-safe row identifier. For example, (b) below is a lax-key for (b,c), but not a strict key. A strict key treats NULLs as equal to one-another. A lax key permits the general NULL != NULL behavior. Filtering nulls from a relation can promote a lax key into a strict key.

b     c
----------
NULL  1
NULL  NULL

func (*FuncDepSet) NotNull added in v0.16.0

func (f *FuncDepSet) NotNull() ColSet

func (*FuncDepSet) StrictKey added in v0.16.0

func (f *FuncDepSet) StrictKey() (ColSet, bool)

StrictKey returns a set of columns that act as a row identifier. No two rows can have the same identifier, like (b) below. Unique keys are only strict if all columns are non-nullable. See LaxKey() for explanation.

b  c
----
1  1
2  1

func (*FuncDepSet) String added in v0.16.0

func (f *FuncDepSet) String() string

type Function

type Function interface {
	// NewInstance returns a new instance of the function to evaluate against rows
	NewInstance([]Expression) (Expression, error)
	// FunctionName returns the name of this function
	FunctionName() string
	// contains filtered or unexported methods
}

Function is a function defined by the user that can be applied in a SQL query.

type Function0

type Function0 struct {
	Name string
	Fn   CreateFunc0Args
}

Function0 is a function with 0 arguments.

func NewFunction0

func NewFunction0(name string, fn func() Expression) Function0

func (Function0) FunctionName added in v0.11.0

func (fn Function0) FunctionName() string

func (Function0) NewInstance added in v0.9.0

func (fn Function0) NewInstance(args []Expression) (Expression, error)

type Function1

type Function1 struct {
	Name string
	Fn   CreateFunc1Args
}

Function1 is a function with 1 argument.

func (Function1) FunctionName added in v0.11.0

func (fn Function1) FunctionName() string

func (Function1) NewInstance added in v0.9.0

func (fn Function1) NewInstance(args []Expression) (Expression, error)

type Function2

type Function2 struct {
	Name string
	Fn   CreateFunc2Args
}

Function2 is a function with 2 arguments.

func (Function2) FunctionName added in v0.11.0

func (fn Function2) FunctionName() string

func (Function2) NewInstance added in v0.9.0

func (fn Function2) NewInstance(args []Expression) (Expression, error)

type Function3

type Function3 struct {
	Name string
	Fn   CreateFunc3Args
}

Function3 is a function with 3 arguments.

func (Function3) FunctionName added in v0.11.0

func (fn Function3) FunctionName() string

func (Function3) NewInstance added in v0.9.0

func (fn Function3) NewInstance(args []Expression) (Expression, error)

type Function4

type Function4 struct {
	Name string
	Fn   CreateFunc4Args
}

Function4 is a function with 4 arguments.

func (Function4) FunctionName added in v0.11.0

func (fn Function4) FunctionName() string

func (Function4) NewInstance added in v0.9.0

func (fn Function4) NewInstance(args []Expression) (Expression, error)

type Function5

type Function5 struct {
	Name string
	Fn   CreateFunc5Args
}

Function5 is a function with 5 arguments.

func (Function5) FunctionName added in v0.11.0

func (fn Function5) FunctionName() string

func (Function5) NewInstance added in v0.9.0

func (fn Function5) NewInstance(args []Expression) (Expression, error)

type Function6

type Function6 struct {
	Name string
	Fn   CreateFunc6Args
}

Function6 is a function with 6 arguments.

func (Function6) FunctionName added in v0.11.0

func (fn Function6) FunctionName() string

func (Function6) NewInstance added in v0.9.0

func (fn Function6) NewInstance(args []Expression) (Expression, error)

type Function7

type Function7 struct {
	Name string
	Fn   CreateFunc7Args
}

Function7 is a function with 7 arguments.

func (Function7) FunctionName added in v0.11.0

func (fn Function7) FunctionName() string

func (Function7) NewInstance added in v0.9.0

func (fn Function7) NewInstance(args []Expression) (Expression, error)

type FunctionExpression

type FunctionExpression interface {
	Expression
	FunctionName() string
	Description() string
}

FunctionExpression is an Expression that represents a function.

type FunctionN

type FunctionN struct {
	Name string
	Fn   CreateFuncNArgs
}

FunctionN is a function with variable number of arguments. This function is expected to return ErrInvalidArgumentNumber if the arity does not match, since the check has to be done in the implementation.

func (FunctionN) FunctionName added in v0.11.0

func (fn FunctionN) FunctionName() string

func (FunctionN) NewInstance added in v0.9.0

func (fn FunctionN) NewInstance(args []Expression) (Expression, error)

type FunctionProvider added in v0.11.0

type FunctionProvider interface {
	// Function returns the function with the name provided, case-insensitive
	Function(ctx *Context, name string) (Function, bool)
}

FunctionProvider is an interface that allows custom functions to be provided. It's usually (but not always) implemented by a DatabaseProvider.

type Histogram added in v0.14.0

type Histogram []HistogramBucket

Histogram is a collection of non-overlapping buckets that estimate the costing statistics for an index prefix. Note that a non-unique key can cross bucket boundaries.

func (Histogram) Clone added in v0.19.0

func (Histogram) DebugString added in v0.18.0

func (h Histogram) DebugString() string

func (Histogram) IsEmpty added in v0.18.0

func (h Histogram) IsEmpty() bool

func (Histogram) ToInterface added in v0.18.0

func (h Histogram) ToInterface() (interface{}, error)

type HistogramBucket added in v0.14.0

type HistogramBucket interface {
	RowCount() uint64
	DistinctCount() uint64
	NullCount() uint64
	BoundCount() uint64
	UpperBound() Row
	McvCounts() []uint64
	// Mcvs are the "most common values" (keys) in the index
	Mcvs() []Row
}

HistogramBucket contains statistics for a fragment of an index's keyspace.

type IdExpression added in v0.18.0

type IdExpression interface {
	Expression
	Id() ColumnId
	WithId(ColumnId) IdExpression
}

type IgnorableError added in v0.14.0

type IgnorableError struct {
	OffendingRow Row
}

IgnorableError is used propagate information about an error that needs to be ignored and does not interfere with any update accumulators

func NewIgnorableError added in v0.14.0

func NewIgnorableError(row Row) IgnorableError

func (IgnorableError) Error added in v0.14.0

func (e IgnorableError) Error() string

type ImmutableStatusVarValue added in v0.19.0

type ImmutableStatusVarValue struct {
	Var StatusVariable
	Val interface{}
}

func (*ImmutableStatusVarValue) Copy added in v0.19.0

func (*ImmutableStatusVarValue) Increment added in v0.19.0

func (s *ImmutableStatusVarValue) Increment(uint64) error

func (*ImmutableStatusVarValue) Set added in v0.19.0

func (s *ImmutableStatusVarValue) Set(v interface{}) error

func (*ImmutableStatusVarValue) Value added in v0.19.0

func (s *ImmutableStatusVarValue) Value() interface{}

func (*ImmutableStatusVarValue) Variable added in v0.19.0

type Index

type Index interface {
	// ID returns the identifier of the index.
	ID() string
	// Database returns the database name this index belongs to.
	Database() string
	// Table returns the table name this index belongs to.
	Table() string
	// Expressions returns the indexed expressions. If the result is more than
	// one expression, it means the index has multiple columns indexed. If it's
	// just one, it means it may be an expression or a column.
	Expressions() []string
	// IsUnique returns whether this index is unique
	IsUnique() bool
	// IsSpatial returns whether this index is a spatial index
	IsSpatial() bool
	// IsFullText returns whether this index is a Full-Text index
	IsFullText() bool
	// IsVector returns whether this index is a Full-Text index
	IsVector() bool
	// Comment returns the comment for this index
	Comment() string
	// IndexType returns the type of this index, e.g. BTREE
	IndexType() string
	// IsGenerated returns whether this index was generated. Generated indexes
	// are used for index access, but are not displayed (such as with SHOW INDEXES).
	IsGenerated() bool
	// ColumnExpressionTypes returns each expression and its associated Type.
	// Each expression string should exactly match the string returned from
	// Index.Expressions().
	ColumnExpressionTypes() []ColumnExpressionType
	// CanSupport returns whether this index supports lookups on the given
	// range filters.
	CanSupport(...Range) bool
	// CanSupportOrderBy returns whether this index can optimize ORDER BY a given expression type.
	// Verifying that the expression's children match the index columns are done separately.
	CanSupportOrderBy(expr Expression) bool

	// PrefixLengths returns the prefix lengths for each column in this index
	PrefixLengths() []uint16
}

Index is the representation of an index, and also creates an IndexLookup when given a collection of ranges.

type IndexAddressable added in v0.12.0

type IndexAddressable interface {
	// IndexedAccess returns a table that can perform scans constrained to
	// an IndexLookup on the index given, or nil if the index cannot support
	// the lookup expression.
	IndexedAccess(lookup IndexLookup) IndexedTable
	// GetIndexes returns an array of this table's Indexes
	GetIndexes(ctx *Context) ([]Index, error)
	// PreciseMatch returns whether an indexed access can substitute for filters
	PreciseMatch() bool
}

IndexAddressable is a table that can be scanned through a primary index

type IndexAddressableTable

type IndexAddressableTable interface {
	Table
	IndexAddressable
}

IndexAddressableTable is a table that can be accessed through an index

type IndexAlterableTable

type IndexAlterableTable interface {
	Table
	// CreateIndex creates an index for this table, using the provided parameters.
	// Returns an error if the index name already exists, or an index with the same columns already exists.
	CreateIndex(ctx *Context, indexDef IndexDef) error
	// DropIndex removes an index from this table, if it exists.
	// Returns an error if the removal failed or the index does not exist.
	DropIndex(ctx *Context, indexName string) error
	// RenameIndex renames an existing index to another name that is not already taken by another index on this table.
	RenameIndex(ctx *Context, fromIndexName string, toIndexName string) error
}

IndexAlterableTable represents a table that supports index modification operations.

type IndexBuildingTable added in v0.18.0

type IndexBuildingTable interface {
	IndexAlterableTable
	// ShouldBuildIndex returns whether the given index should be build via BuildIndex. Some indexes require building,
	// in which case this method is not called.
	ShouldBuildIndex(ctx *Context, indexDef IndexDef) (bool, error)
	// BuildIndex returns a RowInserter for that will be passed all existing rows of the table. The returned RowInserter
	// should use the rows provided to populate the newly created index given by the definition. When |Close| is called
	// on the RowInserter, the index should be fully populated and available for further use in the session.
	BuildIndex(ctx *Context, indexDef IndexDef) (RowInserter, error)
}

IndexBuildingTable is an optional extension to IndexAlterableTable that supports the engine's assistance in building a newly created index, or rebuilding an existing one. This interface is non-optional for tables that wish to create indexes on virtual columns, as the engine must provide a value for these columns.

type IndexClass added in v0.18.0

type IndexClass uint8

type IndexColumn

type IndexColumn struct {
	Name string
	// Length represents the index prefix length. If zero, then no length was specified.
	Length int64
}

IndexColumn is the column by which to add to an index.

type IndexConstraint

type IndexConstraint byte

IndexConstraint represents any constraints that should be applied to the index.

const (
	IndexConstraint_None IndexConstraint = iota
	IndexConstraint_Unique
	IndexConstraint_Fulltext
	IndexConstraint_Spatial
	IndexConstraint_Vector
	IndexConstraint_Primary
)

type IndexDef added in v0.15.0

type IndexDef struct {
	Name       string
	Columns    []IndexColumn
	Constraint IndexConstraint
	Storage    IndexUsing
	Comment    string
}

func (*IndexDef) ColumnNames added in v0.18.1

func (i *IndexDef) ColumnNames() []string

ColumnNames returns each column's name without the length property.

func (*IndexDef) IsFullText added in v0.18.1

func (i *IndexDef) IsFullText() bool

func (*IndexDef) IsPrimary added in v0.18.1

func (i *IndexDef) IsPrimary() bool

func (*IndexDef) IsSpatial added in v0.18.1

func (i *IndexDef) IsSpatial() bool

func (*IndexDef) IsUnique added in v0.18.1

func (i *IndexDef) IsUnique() bool

func (*IndexDef) IsVector added in v0.19.0

func (i *IndexDef) IsVector() bool

func (*IndexDef) String added in v0.18.1

func (i *IndexDef) String() string

type IndexDefs added in v0.18.1

type IndexDefs []*IndexDef

type IndexDriver

type IndexDriver interface {
	// ID returns the unique name of the driver.
	ID() string
	// Create a new index. If exprs is more than one expression, it means the
	// index has multiple columns indexed. If it's just one, it means it may
	// be an expression or a column.
	Create(db, table, id string, expressions []Expression, config map[string]string) (DriverIndex, error)
	// LoadAll loads all indexes for given db and table.
	LoadAll(ctx *Context, db, table string) ([]DriverIndex, error)
	// Save the given index for all partitions.
	Save(*Context, DriverIndex, PartitionIndexKeyValueIter) error
	// Delete the given index for all partitions in the iterator.
	Delete(DriverIndex, PartitionIter) error
}

IndexDriver manages the coordination between the indexes and their representation on disk.

type IndexKeyValueIter

type IndexKeyValueIter interface {
	// Next returns the next tuple of index key values. The length of the
	// returned slice will be the same as the number of columns used to
	// create this iterator. The second returned parameter is a repo's location.
	Next(*Context) ([]interface{}, []byte, error)
	Closer
}

IndexKeyValueIter is an iterator of index key values, that is, a tuple of the values that will be index keys.

type IndexLookup

type IndexLookup struct {
	Index  Index
	Ranges RangeCollection
	// IsPointLookup is true if the lookup will return one or zero
	// values; the range is null safe, the index is unique, every index
	// column has a range expression, and every range expression is an
	// exact equality.
	IsPointLookup       bool
	IsEmptyRange        bool
	IsSpatialLookup     bool
	IsReverse           bool
	VectorOrderAndLimit OrderAndLimit
}

IndexLookup is the implementation-specific definition of an index lookup. The IndexLookup must contain all necessary information to retrieve exactly the rows in the table as specified by the ranges given to their parent index. Implementors are responsible for all semantics of correctly returning rows that match an index lookup.

func NewIndexLookup added in v0.18.0

func NewIndexLookup(idx Index, ranges MySQLRangeCollection, isPointLookup, isEmptyRange, isSpatialLookup, isReverse bool) IndexLookup

func (IndexLookup) DebugString added in v0.14.0

func (il IndexLookup) DebugString() string

func (IndexLookup) IsEmpty added in v0.14.0

func (il IndexLookup) IsEmpty() bool

func (IndexLookup) String added in v0.14.0

func (il IndexLookup) String() string

type IndexOrder added in v0.12.0

type IndexOrder byte
const (
	IndexOrderNone IndexOrder = iota
	IndexOrderAsc
	IndexOrderDesc
)

type IndexRegistry

type IndexRegistry struct {
	// Root path where all the data of the indexes is stored on disk.
	Root string
	// contains filtered or unexported fields
}

IndexRegistry keeps track of all driver-provided indexes in the engine.

func NewIndexRegistry

func NewIndexRegistry() *IndexRegistry

NewIndexRegistry returns a new Index Registry.

func (*IndexRegistry) AddIndex

func (r *IndexRegistry) AddIndex(
	idx DriverIndex,
) (created chan<- struct{}, ready <-chan struct{}, err error)

AddIndex adds the given index to the registry. The added index will be marked as creating, so nobody can register two indexes with the same expression or id while the other is still being created. When something is sent through the returned channel, it means the index has finished its creation and will be marked as ready. Another channel is returned to notify the user when the index is ready.

func (*IndexRegistry) CanRemoveIndex

func (r *IndexRegistry) CanRemoveIndex(idx Index) bool

CanRemoveIndex returns whether the given index is ready to be removed.

func (*IndexRegistry) CanUseIndex

func (r *IndexRegistry) CanUseIndex(idx Index) bool

CanUseIndex returns whether the given index is ready to use or not.

func (*IndexRegistry) DefaultIndexDriver

func (r *IndexRegistry) DefaultIndexDriver() IndexDriver

DefaultIndexDriver returns the default index driver, which is the only driver when there is 1 driver in the registry. If there are more than 1 drivers in the registry, this will return the empty string, as there is no clear default driver.

func (*IndexRegistry) DeleteIndex

func (r *IndexRegistry) DeleteIndex(db, id string, force bool) (<-chan struct{}, error)

DeleteIndex deletes an index from the registry by its id. First, it marks the index for deletion but does not remove it, so queries that are using it may still do so. The returned channel will send a message when the index can be deleted from disk. If force is true, it will delete the index even if it's not ready for usage. Only use that parameter if you know what you're doing.

func (*IndexRegistry) ExpressionsWithIndexes

func (r *IndexRegistry) ExpressionsWithIndexes(
	db string,
	exprs ...Expression,
) [][]Expression

ExpressionsWithIndexes finds all the combinations of expressions with matching indexes. This only matches multi-column indexes.

func (*IndexRegistry) HasIndexes

func (r *IndexRegistry) HasIndexes() bool

HasIndexes returns whether the index registry has any registered indexes. Not thread safe, so the answer is approximate in the face of drivers and indexes being added and removed.

func (*IndexRegistry) Index

func (r *IndexRegistry) Index(db, id string) DriverIndex

Index returns the index with the given id. It may return nil if the index is not found.

func (*IndexRegistry) IndexDriver

func (r *IndexRegistry) IndexDriver(id string) IndexDriver

IndexDriver returns the IndexDriver with the given ID.

func (*IndexRegistry) IndexesByTable

func (r *IndexRegistry) IndexesByTable(db, table string) []DriverIndex

IndexesByTable returns a slice of all the indexes existing on the given table.

func (*IndexRegistry) LoadIndexes

func (r *IndexRegistry) LoadIndexes(ctx *Context, dbs []Database) error

LoadIndexes creates load functions for all indexes for all dbs, tables and drivers. These functions are called as needed by the query

func (*IndexRegistry) MarkOutdated

func (r *IndexRegistry) MarkOutdated(idx Index)

MarkOutdated sets the index status as outdated. This method is not thread safe and should not be used directly except for testing.

func (*IndexRegistry) MatchingIndex added in v0.12.0

func (r *IndexRegistry) MatchingIndex(ctx *Context, db string, expr ...Expression) (index Index, prefixCount int, err error)

MatchingIndex returns the index that best fits the given expressions. See analyzer.MatchingIndexes for the rules regarding which index is considered the best. If no index matches then returns nil.

func (*IndexRegistry) RegisterIndexDriver

func (r *IndexRegistry) RegisterIndexDriver(driver IndexDriver)

RegisterIndexDriver registers a new index driver.

func (*IndexRegistry) ReleaseIndex

func (r *IndexRegistry) ReleaseIndex(idx Index)

ReleaseIndex releases an index after it's been used.

type IndexRequired added in v0.18.0

type IndexRequired interface {
	IndexAddressable
	// RequiredPredicates returns a list of columns that need IndexedTableAccess
	RequiredPredicates() []string
}

IndexRequired tables cannot be executed without index lookups on certain columns. Join planning uses this interface to maintain plan correctness for these nodes

type IndexSearchable added in v0.18.0

type IndexSearchable interface {
	// SkipIndexCosting avoids falling back default costing logic when
	// the integrator fails to match an index.
	SkipIndexCosting() bool
	// LookupForExpressions returns a sql.IndexLookup for a set of expression.
	LookupForExpressions(*Context, ...Expression) (IndexLookup, *FuncDepSet, Expression, bool, error)
}

IndexSearchable lets a node use custom logic to create *plan.IndexedTableAccess

type IndexSearchableTable added in v0.18.0

type IndexSearchableTable interface {
	IndexAddressableTable
	IndexSearchable
}

IndexSearchableTable is a Table supports custom index generation.

type IndexStatus

type IndexStatus byte

IndexStatus represents the current status in which the index is.

const (
	// IndexNotReady means the index is not ready to be used.
	IndexNotReady IndexStatus = iota
	// IndexReady means the index can be used.
	IndexReady
	// IndexOutdated means the index is loaded but will not be used because the
	// contents in it are outdated.
	IndexOutdated
)

func (IndexStatus) IsUsable

func (s IndexStatus) IsUsable() bool

IsUsable returns whether the index can be used or not based on the status.

func (IndexStatus) String

func (s IndexStatus) String() string

type IndexUsing

type IndexUsing byte

IndexUsing is the desired storage type.

const (
	IndexUsing_Default IndexUsing = iota
	IndexUsing_BTree
	IndexUsing_Hash
)

type IndexValueIter

type IndexValueIter interface {
	// Next returns the next value (repo's location) - see IndexKeyValueIter.
	Next(*Context) ([]byte, error)
	Closer
}

IndexValueIter is an iterator of index values.

type IndexedTable

type IndexedTable interface {
	Table
	// LookupPartitions returns partitions scanned by the given IndexLookup
	LookupPartitions(*Context, IndexLookup) (PartitionIter, error)
}

IndexedTable is a table with an index chosen for range scans

type IndexedTableCreator added in v0.15.0

type IndexedTableCreator interface {
	Database
	// CreateIndexedTable creates the table with the given name and schema using the index definition provided for its
	// primary key index.
	CreateIndexedTable(ctx *Context, name string, schema PrimaryKeySchema, idxDef IndexDef, collation CollationID) error
}

IndexedTableCreator is a Database that can create new tables which have a Primary Key with columns that have prefix lengths.

type InsertableTable

type InsertableTable interface {
	Table
	// Inserter returns an Inserter for this table. The Inserter will get one call to Insert() for each row to be
	// inserted, and will end with a call to Close() to finalize the insert operation.
	Inserter(*Context) RowInserter
}

InsertableTable is a table that can process insertion of new rows.

type JSONWrapper added in v0.18.0

type JSONWrapper interface {
	// Clone creates a new value that can be mutated without affecting the original.
	Clone(ctx context.Context) JSONWrapper
	// ToInterface converts a JSONWrapper to an interface{} of simple types
	ToInterface() (interface{}, error)
}

JSONWrapper is an integrator specific implementation of a JSON field value. The query engine can utilize these optimized access methods improve performance by minimizing the need to unmarshall a JSONWrapper into a JSONDocument.

type Key added in v0.16.0

type Key struct {
	// contains filtered or unexported fields
}

Key maintains a strict or lax dependency

func (*Key) Empty added in v0.16.0

func (k *Key) Empty() bool

type KeyValueCache

type KeyValueCache interface {
	// Put a new value in the cache.
	Put(uint64, interface{}) error
	// Get the value with the given key. An error is returned if the specified key does not exist.
	Get(uint64) (interface{}, error)
	// Size returns the number of elements in the cache.
	Size() int
}

KeyValueCache is a cache of key value pairs.

type LockState

type LockState int

LockState represents the different states a lock can be in

const (
	// LockDoesNotExist is the state where a lock has never been created
	LockDoesNotExist LockState = iota
	// LockInUse is the state where a lock has been acquired by a user
	LockInUse
	// LockFree is the state where a lock has been created, but is not currently owned by any user
	LockFree
)

type LockSubsystem

type LockSubsystem struct {
	// contains filtered or unexported fields
}

LockSubsystem manages reentrant named locks

func NewLockSubsystem

func NewLockSubsystem() *LockSubsystem

NewLockSubsystem creates a LockSubsystem object

func (*LockSubsystem) GetLockState

func (ls *LockSubsystem) GetLockState(name string) (state LockState, owner uint32)

GetLockState returns the LockState and owner ID for a lock with a given name.

func (*LockSubsystem) Lock

func (ls *LockSubsystem) Lock(ctx *Context, name string, timeout time.Duration) error

Lock attempts to acquire a lock with a given name for the Id associated with the given ctx.Session within the given timeout

func (*LockSubsystem) ReleaseAll

func (ls *LockSubsystem) ReleaseAll(ctx *Context) (int, error)

ReleaseAll releases all locks the ID associated with the given ctx.Session, and returns the number of locks that were succeessfully released.

func (*LockSubsystem) Unlock

func (ls *LockSubsystem) Unlock(ctx *Context, name string) error

Unlock releases a lock with a given name for the ID associated with the given ctx.Session

type Lockable

type Lockable interface {
	Nameable
	// Lock locks the table either for reads or writes. Any session clients can
	// read while the table is locked for read, but not write.
	// When the table is locked for write, nobody can write except for the
	// session client that requested the lock.
	Lock(ctx *Context, write bool) error
	// Unlock releases the lock for the current session client. It blocks until
	// all reads or writes started during the lock are finished.
	// Context may be nil if the unlock it's because the connection was closed.
	// The id will always be provided, since in some cases context is not
	// available.
	Unlock(ctx *Context, id uint32) error
}

Lockable should be implemented by tables that can be locked and unlocked.

type MapCatalog added in v0.17.0

type MapCatalog struct {
	Tables map[string]Table
	Funcs  map[string]Function

	Databases map[string]Database
	// contains filtered or unexported fields
}

func (MapCatalog) AllDatabases added in v0.17.0

func (t MapCatalog) AllDatabases(ctx *Context) []Database

func (MapCatalog) AuthorizationHandler added in v0.19.0

func (t MapCatalog) AuthorizationHandler() AuthorizationHandler

func (MapCatalog) CreateDatabase added in v0.17.0

func (t MapCatalog) CreateDatabase(ctx *Context, dbName string, collation CollationID) error

func (MapCatalog) DataLength added in v0.18.0

func (t MapCatalog) DataLength(ctx *Context, db string, table Table) (uint64, error)

func (MapCatalog) Database added in v0.17.0

func (t MapCatalog) Database(ctx *Context, name string) (Database, error)

func (MapCatalog) DatabaseTable added in v0.17.0

func (t MapCatalog) DatabaseTable(ctx *Context, db Database, tableName string) (Table, Database, error)

func (MapCatalog) DatabaseTableAsOf added in v0.17.0

func (t MapCatalog) DatabaseTableAsOf(ctx *Context, db Database, tableName string, asOf interface{}) (Table, Database, error)

func (MapCatalog) DropDbStats added in v0.18.0

func (t MapCatalog) DropDbStats(ctx *Context, db string, flush bool) error

func (MapCatalog) DropStats added in v0.18.0

func (t MapCatalog) DropStats(ctx *Context, qual StatQualifier, cols []string) error

func (MapCatalog) ExternalStoredProcedure added in v0.17.0

func (t MapCatalog) ExternalStoredProcedure(ctx *Context, name string, numOfParams int) (*ExternalStoredProcedureDetails, error)

func (MapCatalog) ExternalStoredProcedures added in v0.17.0

func (t MapCatalog) ExternalStoredProcedures(ctx *Context, name string) ([]ExternalStoredProcedureDetails, error)

func (MapCatalog) Function added in v0.17.0

func (t MapCatalog) Function(ctx *Context, name string) (Function, bool)

func (MapCatalog) GetStats added in v0.18.0

func (t MapCatalog) GetStats(ctx *Context, qual StatQualifier, cols []string) (Statistic, bool)

func (MapCatalog) GetTableStats added in v0.18.0

func (t MapCatalog) GetTableStats(ctx *Context, db string, table Table) ([]Statistic, error)

func (MapCatalog) HasDatabase added in v0.17.0

func (t MapCatalog) HasDatabase(ctx *Context, name string) bool

func (MapCatalog) LockTable added in v0.17.0

func (t MapCatalog) LockTable(ctx *Context, table string)

func (MapCatalog) RefreshTableStats added in v0.18.0

func (t MapCatalog) RefreshTableStats(ctx *Context, table Table, db string) error

func (MapCatalog) RegisterFunction added in v0.17.0

func (t MapCatalog) RegisterFunction(ctx *Context, fns ...Function)

func (MapCatalog) RemoveDatabase added in v0.17.0

func (t MapCatalog) RemoveDatabase(ctx *Context, dbName string) error

func (MapCatalog) RowCount added in v0.18.0

func (t MapCatalog) RowCount(ctx *Context, db string, table Table) (uint64, error)

func (MapCatalog) SetStats added in v0.18.0

func (t MapCatalog) SetStats(ctx *Context, stats Statistic) error

func (MapCatalog) Table added in v0.17.0

func (t MapCatalog) Table(ctx *Context, dbName, tableName string) (Table, Database, error)

func (MapCatalog) TableAsOf added in v0.17.0

func (t MapCatalog) TableAsOf(ctx *Context, dbName, tableName string, asOf interface{}) (Table, Database, error)

func (MapCatalog) TableFunction added in v0.17.0

func (t MapCatalog) TableFunction(ctx *Context, name string) (TableFunction, bool)

func (MapCatalog) UnlockTables added in v0.17.0

func (t MapCatalog) UnlockTables(ctx *Context, id uint32) error

func (MapCatalog) WithTableFunctions added in v0.18.0

func (t MapCatalog) WithTableFunctions(fns ...TableFunction) (TableFunctionProvider, error)

type MemoryManager

type MemoryManager struct {
	// contains filtered or unexported fields
}

MemoryManager is in charge of keeping track and managing all the components that operate in memory. There should only be one instance of a memory manager running at the same time in each process.

func NewMemoryManager

func NewMemoryManager(r Reporter) *MemoryManager

NewMemoryManager creates a new manager with the given memory reporter. If nil is given, then the Process reporter will be used by default.

func (*MemoryManager) Free

func (m *MemoryManager) Free()

Free the memory of all freeable caches.

func (*MemoryManager) HasAvailable

func (m *MemoryManager) HasAvailable() bool

HasAvailable reports whether the memory manager has any available memory.

func (*MemoryManager) NewHistoryCache

func (m *MemoryManager) NewHistoryCache() (KeyValueCache, DisposeFunc)

NewHistoryCache returns an empty history cache and a function to dispose it when it's no longer needed.

func (*MemoryManager) NewLRUCache

func (m *MemoryManager) NewLRUCache(size uint) (KeyValueCache, DisposeFunc)

NewLRUCache returns an empty LRU cache and a function to dispose it when it's no longer needed.

func (*MemoryManager) NewRows2Cache added in v0.12.0

func (m *MemoryManager) NewRows2Cache() (Rows2Cache, DisposeFunc)

NewRowsCache returns an empty rows cache and a function to dispose it when it's no longer needed.

func (*MemoryManager) NewRowsCache

func (m *MemoryManager) NewRowsCache() (RowsCache, DisposeFunc)

NewRowsCache returns an empty rows cache and a function to dispose it when it's no longer needed.

func (*MemoryManager) NumCaches added in v0.11.0

func (m *MemoryManager) NumCaches() int

type MultiDatabaser added in v0.12.0

type MultiDatabaser interface {
	// DatabaseProvider returns the current DatabaseProvider.
	DatabaseProvider() DatabaseProvider
	// WithDatabaseProvider returns a new node instance with the database provider replaced with the one given as parameter.
	WithDatabaseProvider(DatabaseProvider) (Node, error)
}

MultiDatabaser is a node that contains a reference to a database provider. This interface is intended for very specific nodes that must resolve databases during execution time rather than during analysis, such as block statements where the execution of a nested statement in the block may affect future statements within that same block.

type MutableDatabaseProvider added in v0.11.0

type MutableDatabaseProvider interface {
	DatabaseProvider

	// CreateDatabase creates a database and adds it to the provider's collection.
	CreateDatabase(ctx *Context, name string) error

	// DropDatabase removes a database from the provider's collection.
	DropDatabase(ctx *Context, name string) error
}

MutableDatabaseProvider is a DatabaseProvider that can create and drop databases.

type MutableRowIter added in v0.19.0

type MutableRowIter interface {
	RowIter
	GetChildIter() RowIter
	WithChildIter(childIter RowIter) RowIter
}

MutableRowIter is an extension of RowIter for integrators that wrap RowIters. It allows for analysis rules to inspect the underlying RowIters.

type MutableStatistic added in v0.18.0

type MutableStatistic interface {
	WithColSet(ColSet) Statistic
	WithFuncDeps(*FuncDepSet) Statistic
	WithHistogram(Histogram) (Statistic, error)
	WithDistinctCount(uint64) Statistic
	WithRowCount(uint64) Statistic
	WithNullCount(uint64) Statistic
	WithAvgSize(uint64) Statistic
	WithLowerBound(Row) Statistic
}

type MutableStatusVarValue added in v0.19.0

type MutableStatusVarValue struct {
	Var StatusVariable
	Val *atomic.Uint64
}

MutableStatusVarValue is a StatusVariable with a value.

func (*MutableStatusVarValue) Copy added in v0.19.0

func (*MutableStatusVarValue) Increment added in v0.19.0

func (s *MutableStatusVarValue) Increment(v uint64) error

func (*MutableStatusVarValue) Set added in v0.19.0

func (s *MutableStatusVarValue) Set(v interface{}) error

func (*MutableStatusVarValue) Value added in v0.19.0

func (s *MutableStatusVarValue) Value() interface{}

func (*MutableStatusVarValue) Variable added in v0.19.0

func (s *MutableStatusVarValue) Variable() StatusVariable

type MutableTableNode added in v0.18.0

type MutableTableNode interface {
	TableNode
	// WithTable returns a new TableNode with the table given. If the MutableTableNode has a MutableTableWrapper, it must
	// re-wrap the table given with this wrapper.
	WithTable(Table) (MutableTableNode, error)
	// ReplaceTable replaces the table with the table given, with no re-wrapping semantics.
	ReplaceTable(table Table) (MutableTableNode, error)
	// WrappedTable returns the Table this node wraps, without unwinding any additional layers of wrapped tables.
	WrappedTable() Table
}

MutableTableNode is a TableNode that can update its underlying table. Different methods are provided to accommodate different use cases that require working with base-level tables v. wrappers on top of them. Some uses of these methods might require that return values that implement all the same subinterfaces as the wrapped table, e.g. IndexedTable, ProjectableTable, etc. Callers of these methods should verify that the MutableTableNode's new table respects this contract.

type MutableTableWrapper added in v0.18.0

type MutableTableWrapper interface {
	TableWrapper
	WithUnderlying(Table) Table
}

MutableTableWrapper is a TableWrapper that can change its underlying table.

type MySQLIndexBuilder added in v0.19.0

type MySQLIndexBuilder struct {
	// contains filtered or unexported fields
}

MySQLIndexBuilder builds ranges based on the combination of calls made for the given index, and then relies on the Index to return an IndexLookup from the created ranges.

func NewMySQLIndexBuilder added in v0.19.0

func NewMySQLIndexBuilder(idx Index) *MySQLIndexBuilder

NewMySQLIndexBuilder returns a new MySQLIndexBuilder. Used internally to construct a range that will later be passed to integrators through the Index function NewLookup.

func (*MySQLIndexBuilder) Build added in v0.19.0

func (b *MySQLIndexBuilder) Build(ctx *Context) (IndexLookup, error)

Build constructs a new IndexLookup based on the ranges that have been built internally by this builder.

func (*MySQLIndexBuilder) Equals added in v0.19.0

func (b *MySQLIndexBuilder) Equals(ctx *Context, colExpr string, keys ...interface{}) *MySQLIndexBuilder

Equals represents colExpr = key. For IN expressions, pass all of them in the same Equals call.

func (*MySQLIndexBuilder) GreaterOrEqual added in v0.19.0

func (b *MySQLIndexBuilder) GreaterOrEqual(ctx *Context, colExpr string, key interface{}) *MySQLIndexBuilder

GreaterOrEqual represents colExpr >= key.

func (*MySQLIndexBuilder) GreaterThan added in v0.19.0

func (b *MySQLIndexBuilder) GreaterThan(ctx *Context, colExpr string, key interface{}) *MySQLIndexBuilder

GreaterThan represents colExpr > key.

func (*MySQLIndexBuilder) IsNotNull added in v0.19.0

func (b *MySQLIndexBuilder) IsNotNull(ctx *Context, colExpr string) *MySQLIndexBuilder

IsNotNull represents colExpr != nil

func (*MySQLIndexBuilder) IsNull added in v0.19.0

func (b *MySQLIndexBuilder) IsNull(ctx *Context, colExpr string) *MySQLIndexBuilder

IsNull represents colExpr = nil

func (*MySQLIndexBuilder) LessOrEqual added in v0.19.0

func (b *MySQLIndexBuilder) LessOrEqual(ctx *Context, colExpr string, key interface{}) *MySQLIndexBuilder

LessOrEqual represents colExpr <= key.

func (*MySQLIndexBuilder) LessThan added in v0.19.0

func (b *MySQLIndexBuilder) LessThan(ctx *Context, colExpr string, key interface{}) *MySQLIndexBuilder

LessThan represents colExpr < key.

func (*MySQLIndexBuilder) NotEquals added in v0.19.0

func (b *MySQLIndexBuilder) NotEquals(ctx *Context, colExpr string, key interface{}) *MySQLIndexBuilder

NotEquals represents colExpr <> key.

func (*MySQLIndexBuilder) Ranges added in v0.19.0

Ranges returns all ranges for this index builder. If the builder is in an error state then this returns nil.

type MySQLRange added in v0.19.0

type MySQLRange []MySQLRangeColumnExpr

MySQLRange is a collection of RangeColumns that are ordered by the column expressions as returned by their parent index. A single range represents a set of values intended for iteration by an integrator's index.

func IntersectRanges added in v0.12.0

func IntersectRanges(ranges ...MySQLRange) MySQLRange

IntersectRanges intersects each MySQLRange for each column expression. If a MySQLRangeColumnExpr ends up with no valid ranges then a nil is returned.

func SortRanges added in v0.12.0

func SortRanges(ranges ...MySQLRange) ([]MySQLRange, error)

SortRanges sorts the given ranges, returning a new slice of ranges.

func (MySQLRange) AsEmpty added in v0.19.0

func (rang MySQLRange) AsEmpty() MySQLRange

AsEmpty returns a MySQLRange full of empty RangeColumns with the same types as the calling MySQLRange.

func (MySQLRange) Compare added in v0.19.0

func (rang MySQLRange) Compare(otherRange MySQLRange) (int, error)

Compare returns an integer stating the relative position of the calling MySQLRange to the given MySQLRange.

func (MySQLRange) Copy added in v0.19.0

func (rang MySQLRange) Copy() MySQLRange

Copy returns a duplicate of this MySQLRange.

func (MySQLRange) DebugString added in v0.19.0

func (rang MySQLRange) DebugString() string

DebugString returns this MySQLRange as a string for debugging purposes.

func (MySQLRange) Equals added in v0.19.0

func (rang MySQLRange) Equals(other Range) (bool, error)

Equals evaluates whether the calling Range is equivalent to the given Range.

func (MySQLRange) ExpressionByColumnName added in v0.19.0

func (rang MySQLRange) ExpressionByColumnName(idx Index, colExpr string) (MySQLRangeColumnExpr, bool)

ExpressionByColumnName returns the MySQLRangeColumnExpr that belongs to the given column expression. If an index does not contain the column expression then false is returned.

func (MySQLRange) Intersect added in v0.19.0

func (rang MySQLRange) Intersect(otherRange MySQLRange) (MySQLRange, error)

Intersect intersects the given MySQLRange with the calling MySQLRange.

func (MySQLRange) IsConnected added in v0.19.0

func (rang MySQLRange) IsConnected(otherRange MySQLRange) (bool, error)

IsConnected returns whether the calling MySQLRange and given MySQLRange have overlapping values, which would result in the same values being returned from some subset of both ranges.

func (MySQLRange) IsEmpty added in v0.19.0

func (rang MySQLRange) IsEmpty() (bool, error)

func (MySQLRange) IsSubsetOf added in v0.19.0

func (rang MySQLRange) IsSubsetOf(otherRange MySQLRange) (bool, error)

IsSubsetOf evaluates whether the calling MySQLRange is fully encompassed by the given MySQLRange.

func (MySQLRange) IsSupersetOf added in v0.19.0

func (rang MySQLRange) IsSupersetOf(otherRange MySQLRange) (bool, error)

IsSupersetOf evaluates whether the calling MySQLRange fully encompasses the given MySQLRange.

func (MySQLRange) Overlaps added in v0.19.0

func (rang MySQLRange) Overlaps(otherRange MySQLRange) (bool, error)

Overlaps returns whether the calling MySQLRange and given MySQLRange have overlapping values, which would result in the same values being returned from some subset of both ranges.

func (MySQLRange) RemoveOverlap added in v0.19.0

func (rang MySQLRange) RemoveOverlap(otherRange MySQLRange) ([]MySQLRange, bool, error)

RemoveOverlap removes any overlap that the given MySQLRange may have with the calling MySQLRange. If the two ranges do not overlap and are not mergeable then they're both returned. If one is a subset of the other or is mergeable then only one MySQLRange is returned. Otherwise, this returns a collection of ranges that do not overlap with each other, and covers the entirety of the original ranges (and nothing more). If the two ranges do not overlap and are not mergeable then false is returned, otherwise returns true.

func (MySQLRange) String added in v0.19.0

func (rang MySQLRange) String() string

String returns this MySQLRange as a string for display purposes.

func (MySQLRange) TryMerge added in v0.19.0

func (rang MySQLRange) TryMerge(otherRange MySQLRange) (MySQLRange, bool, error)

TryMerge attempts to merge the given MySQLRange with the calling MySQLRange. This can only do a merge if one MySQLRange is a subset of the other, or if all columns except for one are equivalent, upon which a union is attempted on that column. Returns true if the merge was successful.

type MySQLRangeBoundType added in v0.19.0

type MySQLRangeBoundType int

MySQLRangeBoundType is the bound of the MySQLRangeCut.

const (
	// Open bounds represent exclusion.
	Open MySQLRangeBoundType = iota
	// Closed bounds represent inclusion.
	Closed
)

func (MySQLRangeBoundType) Inclusive added in v0.19.0

func (bt MySQLRangeBoundType) Inclusive() bool

Inclusive returns whether the bound represents inclusion.

type MySQLRangeCollection added in v0.19.0

type MySQLRangeCollection []MySQLRange

MySQLRangeCollection is a collection of MySQL ranges that represent different (non-overlapping) filter expressions.

func RemoveOverlappingRanges added in v0.12.0

func RemoveOverlappingRanges(ranges ...MySQLRange) (MySQLRangeCollection, error)

RemoveOverlappingRanges removes all overlap between all ranges.

func (MySQLRangeCollection) DebugString added in v0.19.0

func (ranges MySQLRangeCollection) DebugString() string

DebugString returns this RangeCollection as a string for debugging purposes.

func (MySQLRangeCollection) Equals added in v0.19.0

func (ranges MySQLRangeCollection) Equals(other RangeCollection) (bool, error)

Equals returns whether the given RangeCollection matches the calling RangeCollection. The order of each Range is important, therefore it is recommended to sort two collections beforehand.

func (MySQLRangeCollection) Intersect added in v0.19.0

func (ranges MySQLRangeCollection) Intersect(otherRanges MySQLRangeCollection) (MySQLRangeCollection, error)

Intersect attempts to intersect the given MySQLRangeCollection with the calling MySQLRangeCollection. This ensures that each MySQLRange belonging to the same collection is treated as a union with respect to that same collection, rather than attempting to intersect ranges that are a part of the same collection.

func (MySQLRangeCollection) Len added in v0.19.0

func (ranges MySQLRangeCollection) Len() int

Len returns the number of ranges in the collection.

func (MySQLRangeCollection) String added in v0.19.0

func (ranges MySQLRangeCollection) String() string

String returns this RangeCollection as a string for display purposes.

func (MySQLRangeCollection) ToRanges added in v0.19.0

func (ranges MySQLRangeCollection) ToRanges() []Range

ToRanges returns the ranges contained in this collection.

type MySQLRangeColumnExpr added in v0.19.0

type MySQLRangeColumnExpr struct {
	LowerBound MySQLRangeCut
	UpperBound MySQLRangeCut
	Typ        Type
}

MySQLRangeColumnExpr represents the contiguous set of values on a specific column.

func AllRangeColumnExpr added in v0.12.0

func AllRangeColumnExpr(typ Type) MySQLRangeColumnExpr

AllRangeColumnExpr returns a MySQLRangeColumnExpr representing all values.

func ClosedRangeColumnExpr added in v0.12.0

func ClosedRangeColumnExpr(lower, upper interface{}, typ Type) MySQLRangeColumnExpr

ClosedRangeColumnExpr returns a MySQLRangeColumnExpr representing {l <= x <= u}.

func CustomRangeColumnExpr added in v0.12.0

func CustomRangeColumnExpr(lower, upper interface{}, lowerBound, upperBound MySQLRangeBoundType, typ Type) MySQLRangeColumnExpr

CustomRangeColumnExpr returns a MySQLRangeColumnExpr defined by the bounds given.

func EmptyRangeColumnExpr added in v0.12.0

func EmptyRangeColumnExpr(typ Type) MySQLRangeColumnExpr

EmptyRangeColumnExpr returns the empty MySQLRangeColumnExpr for the given type.

func GreaterOrEqualRangeColumnExpr added in v0.12.0

func GreaterOrEqualRangeColumnExpr(lower interface{}, typ Type) MySQLRangeColumnExpr

GreaterOrEqualRangeColumnExpr returns a MySQLRangeColumnExpr representing {x >= l}.

func GreaterThanRangeColumnExpr added in v0.12.0

func GreaterThanRangeColumnExpr(lower interface{}, typ Type) MySQLRangeColumnExpr

GreaterThanRangeColumnExpr returns a MySQLRangeColumnExpr representing {x > l}.

func LessOrEqualRangeColumnExpr added in v0.12.0

func LessOrEqualRangeColumnExpr(upper interface{}, typ Type) MySQLRangeColumnExpr

LessOrEqualRangeColumnExpr returns a MySQLRangeColumnExpr representing {x <= u}.

func LessThanRangeColumnExpr added in v0.12.0

func LessThanRangeColumnExpr(upper interface{}, typ Type) MySQLRangeColumnExpr

LessThanRangeColumnExpr returns a MySQLRangeColumnExpr representing {x < u}.

func NotNullRangeColumnExpr added in v0.12.0

func NotNullRangeColumnExpr(typ Type) MySQLRangeColumnExpr

NotNullRangeColumnExpr returns the not null MySQLRangeColumnExpr for the given type.

func NullRangeColumnExpr added in v0.12.0

func NullRangeColumnExpr(typ Type) MySQLRangeColumnExpr

NullRangeColumnExpr returns the null MySQLRangeColumnExpr for the given type.

func OpenRangeColumnExpr added in v0.12.0

func OpenRangeColumnExpr(lower, upper interface{}, typ Type) MySQLRangeColumnExpr

OpenRangeColumnExpr returns a MySQLRangeColumnExpr representing {l < x < u}.

func SimplifyRangeColumn added in v0.12.0

func SimplifyRangeColumn(rces ...MySQLRangeColumnExpr) ([]MySQLRangeColumnExpr, error)

SimplifyRangeColumn combines all RangeColumnExprs that are connected and returns a new slice.

func (MySQLRangeColumnExpr) DebugString added in v0.19.0

func (r MySQLRangeColumnExpr) DebugString() string

DebugString returns this MySQLRangeColumnExpr as a string for debugging purposes.

func (MySQLRangeColumnExpr) Equals added in v0.19.0

Equals checks for equality with the given MySQLRangeColumnExpr.

func (MySQLRangeColumnExpr) HasLowerBound added in v0.19.0

func (r MySQLRangeColumnExpr) HasLowerBound() bool

HasLowerBound returns whether this MySQLRangeColumnExpr has a value for the lower bound.

func (MySQLRangeColumnExpr) HasUpperBound added in v0.19.0

func (r MySQLRangeColumnExpr) HasUpperBound() bool

HasUpperBound returns whether this MySQLRangeColumnExpr has a value for the upper bound.

func (MySQLRangeColumnExpr) IsConnected added in v0.19.0

func (r MySQLRangeColumnExpr) IsConnected(other MySQLRangeColumnExpr) (bool, error)

IsConnected evaluates whether the given MySQLRangeColumnExpr overlaps or is adjacent to the calling MySQLRangeColumnExpr.

func (MySQLRangeColumnExpr) IsEmpty added in v0.19.0

func (r MySQLRangeColumnExpr) IsEmpty() (bool, error)

IsEmpty returns whether this MySQLRangeColumnExpr is empty.

func (MySQLRangeColumnExpr) IsSubsetOf added in v0.19.0

func (r MySQLRangeColumnExpr) IsSubsetOf(other MySQLRangeColumnExpr) (bool, error)

IsSubsetOf evaluates whether the calling MySQLRangeColumnExpr is fully encompassed by the given MySQLRangeColumnExpr.

func (MySQLRangeColumnExpr) IsSupersetOf added in v0.19.0

func (r MySQLRangeColumnExpr) IsSupersetOf(other MySQLRangeColumnExpr) (bool, error)

IsSupersetOf evaluates whether the calling MySQLRangeColumnExpr fully encompasses the given MySQLRangeColumnExpr.

func (MySQLRangeColumnExpr) Overlaps added in v0.19.0

Overlaps evaluates whether the given MySQLRangeColumnExpr overlaps the calling MySQLRangeColumnExpr. If they do, returns the overlapping region as a MySQLRangeColumnExpr.

func (MySQLRangeColumnExpr) RepresentsEquals added in v0.19.0

func (r MySQLRangeColumnExpr) RepresentsEquals() (bool, error)

RepresentsEquals returns whether this MySQLRangeColumnExpr represents an "equals". An "equals" is a special kind of RangeType_ClosedClosed that iterates over a single value (or the specific prefix of some value).

func (MySQLRangeColumnExpr) String added in v0.19.0

func (r MySQLRangeColumnExpr) String() string

String returns this MySQLRangeColumnExpr as a string for display purposes.

func (MySQLRangeColumnExpr) Subtract added in v0.19.0

Subtract removes the given MySQLRangeColumnExpr from the calling MySQLRangeColumnExpr. In the event that the given MySQLRangeColumnExpr is a strict subset of the calling MySQLRangeColumnExpr, two RangeColumnExprs will be returned. If the given MySQLRangeColumnExpr does not overlap the calling MySQLRangeColumnExpr, then the calling MySQLRangeColumnExpr is returned. If the calling MySQLRangeColumnExpr is a strict subset (or equivalent) of the given MySQLRangeColumnExpr, then an empty slice is returned. In all other cases, a slice with a single MySQLRangeColumnExpr will be returned.

func (MySQLRangeColumnExpr) TryIntersect added in v0.19.0

TryIntersect attempts to intersect the given MySQLRangeColumnExpr with the calling MySQLRangeColumnExpr. Returns true if the intersection result is not the empty MySQLRangeColumnExpr, however a valid MySQLRangeColumnExpr is always returned if the error is nil.

func (MySQLRangeColumnExpr) TryUnion added in v0.19.0

TryUnion attempts to combine the given MySQLRangeColumnExpr with the calling MySQLRangeColumnExpr. Returns true if the union was a success.

func (MySQLRangeColumnExpr) Type added in v0.19.0

Type returns this MySQLRangeColumnExpr's RangeType.

type MySQLRangeColumnExprTree added in v0.19.0

type MySQLRangeColumnExprTree struct {
	// contains filtered or unexported fields
}

MySQLRangeColumnExprTree represents a red-black tree over a range column expression. To represent an entire range, each node has both an upper bound and lower bound that represents a single column expression. If the Range has another dimension, then the node will have an inner tree representing the nested dimension ad infinitum. This implicitly means that all column expressions on the lower dimension share the same column expression in the higher dimensions. This way, a Range is deconstructed and sorted by its column expressions, but may easily be retrieved by walking down a tree and all of its inner trees.

func NewMySQLRangeColumnExprTree added in v0.19.0

func NewMySQLRangeColumnExprTree(initialRange MySQLRange, columnExprTypes []Type) (*MySQLRangeColumnExprTree, error)

NewMySQLRangeColumnExprTree creates a new MySQLRangeColumnExprTree constructed from an initial range. As the initial Range may contain column expressions that have a NULL type, the expected non-NULL type for each column expression is given separately. If all column expressions for a specific column will be NULL, then it is valid to use the NULL type. Returns an error if the number of column expressions do not equal the number of types, or if the Range has a length of zero.

func (*MySQLRangeColumnExprTree) FindConnections added in v0.19.0

func (tree *MySQLRangeColumnExprTree) FindConnections(rang MySQLRange, colExprIdx int) (MySQLRangeCollection, error)

FindConnections returns all connecting Ranges found in the tree. They may or may not be mergeable or overlap.

func (*MySQLRangeColumnExprTree) GetRangeCollection added in v0.19.0

func (tree *MySQLRangeColumnExprTree) GetRangeCollection() (MySQLRangeCollection, error)

GetRangeCollection returns every Range that this tree contains.

func (*MySQLRangeColumnExprTree) Insert added in v0.19.0

func (tree *MySQLRangeColumnExprTree) Insert(rang MySQLRange) error

Insert adds the given Range into the tree.

func (*MySQLRangeColumnExprTree) Iterator added in v0.19.0

func (tree *MySQLRangeColumnExprTree) Iterator() *rangeTreeIter

Iterator returns an iterator over the calling tree. Does not handle any inner trees.

func (*MySQLRangeColumnExprTree) Remove added in v0.19.0

func (tree *MySQLRangeColumnExprTree) Remove(rang MySQLRange) error

Remove removes the given Range from the tree (and subtrees if applicable).

func (*MySQLRangeColumnExprTree) String added in v0.19.0

func (tree *MySQLRangeColumnExprTree) String() string

String returns the tree as a formatted string. Does not display the inner trees.

type MySQLRangeCut added in v0.19.0

type MySQLRangeCut interface {
	// Compare returns an integer stating the relative position of the calling MySQLRangeCut to the given MySQLRangeCut.
	Compare(MySQLRangeCut, Type) (int, error)
	// String returns the MySQLRangeCut as a string for display purposes.
	String() string
	// TypeAsLowerBound returns the bound type if the calling MySQLRangeCut is the lower bound of a range.
	TypeAsLowerBound() MySQLRangeBoundType
	// TypeAsUpperBound returns the bound type if the calling MySQLRangeCut is the upper bound of a range.
	TypeAsUpperBound() MySQLRangeBoundType
}

MySQLRangeCut represents a position on the line of all possible values.

func GetMySQLRangeCutMax added in v0.19.0

func GetMySQLRangeCutMax(typ Type, cuts ...MySQLRangeCut) (MySQLRangeCut, error)

GetMySQLRangeCutMax returns the MySQLRangeCut with the highest value.

func GetMySQLRangeCutMin added in v0.19.0

func GetMySQLRangeCutMin(typ Type, cuts ...MySQLRangeCut) (MySQLRangeCut, error)

GetMySQLRangeCutMin returns the MySQLRangeCut with the lowest value.

type MySQLStatusVariable added in v0.18.1

type MySQLStatusVariable struct {
	Name    string
	Scope   StatusVariableScope
	Type    Type
	Default interface{}
}

MySQLStatusVariable represents a mysql status variable.

func (*MySQLStatusVariable) GetDefault added in v0.18.1

func (m *MySQLStatusVariable) GetDefault() interface{}

GetDefault implements StatusVariable.

func (*MySQLStatusVariable) GetName added in v0.18.1

func (m *MySQLStatusVariable) GetName() string

GetName implements StatusVariable.

func (*MySQLStatusVariable) GetScope added in v0.18.1

GetScope implements StatusVariable.

func (*MySQLStatusVariable) GetType added in v0.18.1

func (m *MySQLStatusVariable) GetType() Type

GetType implements StatusVariable.

type MysqlConnectionUser added in v0.18.1

type MysqlConnectionUser struct {
	User string
	Host string
}

MysqlConnectionUser is stored in mysql's connection as UserData once a connection has been authenticated.

func (MysqlConnectionUser) Get added in v0.18.1

Get implements the interface mysql.Getter.

type MysqlParser added in v0.19.0

type MysqlParser struct{}

MysqlParser is a mysql syntax parser used as parser in the engine for Dolt.

func NewMysqlParser added in v0.19.0

func NewMysqlParser() *MysqlParser

NewMysqlParser creates new MysqlParser

func (*MysqlParser) Parse added in v0.19.0

func (m *MysqlParser) Parse(ctx *Context, query string, multi bool) (ast.Statement, string, string, error)

Parse implements Parser interface.

func (*MysqlParser) ParseOneWithOptions added in v0.19.0

func (m *MysqlParser) ParseOneWithOptions(ctx context.Context, s string, options ast.ParserOptions) (ast.Statement, int, error)

ParseOneWithOptions implements Parser interface.

func (*MysqlParser) ParseSimple added in v0.19.0

func (m *MysqlParser) ParseSimple(query string) (ast.Statement, error)

ParseSimple implements Parser interface.

func (*MysqlParser) ParseWithOptions added in v0.19.0

func (m *MysqlParser) ParseWithOptions(ctx context.Context, query string, delimiter rune, multi bool, options ast.ParserOptions) (stmt ast.Statement, parsed, remainder string, err error)

ParseWithOptions implements Parser interface.

type MysqlSVScopeType added in v0.18.1

type MysqlSVScopeType byte

MysqlSVScopeType represents the scope of a system variable.

const (
	// SystemVariableScope_Global is set when the system variable exists only in the global context.
	SystemVariableScope_Global MysqlSVScopeType = iota
	// SystemVariableScope_Session is set when the system variable exists only in the session context.
	SystemVariableScope_Session
	// SystemVariableScope_Both is set when the system variable exists in both the global and session contexts.
	SystemVariableScope_Both
	// SystemVariableScope_Persist is set when the system variable is global and persisted.
	SystemVariableScope_Persist
	// SystemVariableScope_PersistOnly is set when the system variable is persisted outside of server context.
	SystemVariableScope_PersistOnly
	// SystemVariableScope_ResetPersist is used to remove a persisted variable
	SystemVariableScope_ResetPersist
)

func (MysqlSVScopeType) String added in v0.18.1

func (s MysqlSVScopeType) String() string

String returns the scope as an uppercase string.

type MysqlScope added in v0.18.1

type MysqlScope struct {
	Type MysqlSVScopeType
}

MysqlScope represents the scope of a MySQL system variable.

func GetMysqlScope added in v0.18.1

func GetMysqlScope(t MysqlSVScopeType) *MysqlScope

func (*MysqlScope) GetValue added in v0.18.1

func (m *MysqlScope) GetValue(ctx *Context, name string, collation CollationID) (any, error)

func (*MysqlScope) IsGlobalOnly added in v0.18.1

func (m *MysqlScope) IsGlobalOnly() bool

func (*MysqlScope) IsSessionOnly added in v0.18.1

func (m *MysqlScope) IsSessionOnly() bool

func (*MysqlScope) SetValue added in v0.18.1

func (m *MysqlScope) SetValue(ctx *Context, name string, val any) error

type MysqlSystemVariable added in v0.18.1

type MysqlSystemVariable struct {
	// Name is the name of the system variable.
	Name string
	// Scope defines the scope of the system variable, which is either Global, Session, or Both.
	Scope *MysqlScope
	// Dynamic defines whether the variable may be written to during runtime. Variables with this set to `false` will
	// return an error if a user attempts to set a value.
	Dynamic bool
	// SetVarHintApplies defines if the variable may be set for a single query using SET_VAR().
	// https://dev.mysql.com/doc/refman/8.0/en/optimizer-hints.html#optimizer-hints-set-var
	SetVarHintApplies bool
	// Type defines the type of the system variable. This may be a special type not accessible to standard MySQL operations.
	Type Type
	// Default defines the default value of the system variable.
	Default interface{}
	// NotifyChanged is called by the engine if the value of this variable
	// changes during runtime.  It is typically |nil|, but can be used for
	// system variables which control the behavior of the running server.
	// For example, replication threads might need to be started or stopped
	// when replication is enabled or disabled. This provides a scalable
	// alternative to polling.
	//
	// Calls to NotifyChanged are serialized for a given system variable in
	// the global context and in a particular session. They should never
	// block.  NotifyChanged is not called when a new system variable is
	// registered.
	NotifyChanged func(SystemVariableScope, SystemVarValue) error
	// ValueFunction defines an optional function that is executed to provide
	// the value of this system variable whenever it is requested. System variables
	// that provide a ValueFunction should also set Dynamic to false, since they
	// cannot be assigned a value and will return a read-only error if tried.
	ValueFunction func() (interface{}, error)
}

MysqlSystemVariable represents a mysql system variable.

func (*MysqlSystemVariable) DisplayString added in v0.18.1

func (m *MysqlSystemVariable) DisplayString(specifiedScope string) string

DisplayString implements SystemVariable.

func (*MysqlSystemVariable) GetDefault added in v0.18.1

func (m *MysqlSystemVariable) GetDefault() any

GetDefault implements SystemVariable.

func (*MysqlSystemVariable) GetName added in v0.18.1

func (m *MysqlSystemVariable) GetName() string

GetName implements SystemVariable.

func (*MysqlSystemVariable) GetSessionScope added in v0.18.1

func (m *MysqlSystemVariable) GetSessionScope() SystemVariableScope

GetSessionScope implements SystemVariable.

func (*MysqlSystemVariable) GetType added in v0.18.1

func (m *MysqlSystemVariable) GetType() Type

GetType implements SystemVariable.

func (*MysqlSystemVariable) InitValue added in v0.18.1

func (m *MysqlSystemVariable) InitValue(val any, global bool) (SystemVarValue, error)

InitValue implements SystemVariable.

func (*MysqlSystemVariable) IsGlobalOnly added in v0.18.1

func (m *MysqlSystemVariable) IsGlobalOnly() bool

IsGlobalOnly implements SystemVariable.

func (*MysqlSystemVariable) IsReadOnly added in v0.18.1

func (m *MysqlSystemVariable) IsReadOnly() bool

IsReadOnly implements SystemVariable.

func (*MysqlSystemVariable) SetDefault added in v0.18.1

func (m *MysqlSystemVariable) SetDefault(a any)

SetDefault implements SystemVariable.

func (*MysqlSystemVariable) SetValue added in v0.18.1

func (m *MysqlSystemVariable) SetValue(val any, global bool) (SystemVarValue, error)

SetValue implements SystemVariable.

type Nameable

type Nameable interface {
	// Name returns the name.
	Name() string
}

Nameable is something that has a name.

type NameableNode added in v0.15.0

type NameableNode interface {
	Nameable
	Node
}

type Node

type Node interface {
	Resolvable
	fmt.Stringer
	// Schema of the node.
	Schema() Schema
	// Children nodes.
	Children() []Node
	// WithChildren returns a copy of the node with children replaced.
	// It will return an error if the number of children is different than
	// the current number of children. They must be given in the same order
	// as they are returned by Children.
	WithChildren(children ...Node) (Node, error)
	// IsReadOnly returns whether the node is read-only.
	IsReadOnly() bool
}

Node is a node in the execution plan tree.

type NodeExecBuilder added in v0.15.0

type NodeExecBuilder interface {
	Build(ctx *Context, n Node, r Row) (RowIter, error)
}

NodeExecBuilder converts a sql.Node tree into a RowIter.

type NodeVisitor

type NodeVisitor interface {
	// Visit method is invoked for each expr encountered by Walk. If the result Visitor is not nil, Walk visits each of
	// the children of the expr with that visitor, followed by a call of Visit(nil, nil) to the returned visitor.
	Visit(node Node, expression Expression) NodeVisitor
}

NodeVisitor visits expressions in an expression tree. Like Visitor, but with the added context of the node in which an expression is embedded. See WalkExpressionsWithNode in the plan package.

type NonDeterministicExpression

type NonDeterministicExpression interface {
	Expression
	// IsNonDeterministic returns whether this expression returns a non-deterministic result. An expression is
	// non-deterministic if it can return different results on subsequent evaluations.
	IsNonDeterministic() bool
}

NonDeterministicExpression allows a way for expressions to declare that they are non-deterministic, which will signal the engine to not cache their results when this would otherwise appear to be safe.

type NullOrdering added in v0.9.0

type NullOrdering byte

NullOrdering represents how to order based on null values.

const (
	// NullsFirst puts the null values before any other values.
	NullsFirst NullOrdering = iota
	// NullsLast puts the null values after all other values.
	NullsLast NullOrdering = 2
)

type NullType

type NullType interface {
	Type
}

NullType represents the type of NULL values

type NumberType

type NumberType interface {
	Type
	IsSigned() bool
	IsFloat() bool
	DisplayWidth() int
}

NumberType represents all integer and floating point types. https://dev.mysql.com/doc/refman/8.0/en/integer-types.html https://dev.mysql.com/doc/refman/8.0/en/floating-point-types.html The type of the returned value is one of the following: int8, int16, int32, int64, uint8, uint16, uint32, uint64, float32, float64.

type OpaqueNode

type OpaqueNode interface {
	Node
	// Opaque reports whether the node is opaque or not.
	Opaque() bool
}

OpaqueNode is a node that doesn't allow transformations to its children and acts as a black box.

type OrderAndLimit added in v0.19.0

type OrderAndLimit struct {
	OrderBy       Expression
	Limit         Expression
	Literal       Expression
	CalcFoundRows bool
}

OrderAndLimit stores the context of an ORDER BY ... LIMIT statement, and is used by index lookups and iterators.

func (OrderAndLimit) DebugString added in v0.19.0

func (v OrderAndLimit) DebugString() string

func (OrderAndLimit) String added in v0.19.0

func (v OrderAndLimit) String() string

type OrderedIndex added in v0.12.0

type OrderedIndex interface {
	Index
	// Order returns the order of results for reads from this index
	Order() IndexOrder
	// Reversible returns whether or not this index can be iterated on backwards
	Reversible() bool
}

OrderedIndex is an extension of |Index| that allows indexes to declare their return order. The query engine can optimize certain queries if the order of an index is guaranteed, e.g. removing a sort operation.

type Parser added in v0.19.0

type Parser interface {
	// ParseSimple takes a |query| and returns the parsed statement. If |query| represents a no-op statement,
	// such as ";" or "-- comment", then implementations must return Vitess' ErrEmpty error.
	ParseSimple(query string) (ast.Statement, error)
	// Parse parses |query| using the default parser options of the ctx and returns the parsed statement
	// along with the query string and remainder string if it's multiple queries. If |query| represents a
	// no-op statement, such as ";" or "-- comment", then implementations must return Vitess' ErrEmpty error.
	Parse(ctx *Context, query string, multi bool) (ast.Statement, string, string, error)
	// ParseWithOptions parses |query| using the given parser |options| and specified |delimiter|. The parsed statement
	// is returned, along with the query string and remainder string if |multi| has been set to true and there are
	// multiple statements in |query|. If |query| represents a no-op statement, such as ";" or "-- comment", then
	// implementations must return Vitess' ErrEmpty error.
	ParseWithOptions(ctx context.Context, query string, delimiter rune, multi bool, options ast.ParserOptions) (ast.Statement, string, string, error)
	// ParseOneWithOptions parses the first query using specified parsing returns the parsed statement along with
	// the index of the start of the next query. If |query| represents a no-op statement, such as ";" or "-- comment",
	// then implementations must return Vitess' ErrEmpty error.
	ParseOneWithOptions(context.Context, string, ast.ParserOptions) (ast.Statement, int, error)
}
var GlobalParser Parser = NewMysqlParser()

GlobalParser is a temporary variable to expose Doltgres parser. It defaults to MysqlParser.

type Partition

type Partition interface {
	Key() []byte
}

Partition represents a partition from a SQL table.

type PartitionCounter

type PartitionCounter interface {
	// PartitionCount returns the number of partitions.
	PartitionCount(*Context) (int64, error)
}

PartitionCounter can return the number of partitions.

type PartitionIndexKeyValueIter

type PartitionIndexKeyValueIter interface {
	// Next returns the next partition and the IndexKeyValueIter for that
	// partition.
	Next(*Context) (Partition, IndexKeyValueIter, error)
	Closer
}

PartitionIndexKeyValueIter is an iterator of partitions that will return the partition and the IndexKeyValueIter of that partition.

type PartitionIter

type PartitionIter interface {
	Closer
	Next(*Context) (Partition, error)
}

PartitionIter is an iterator that retrieves partitions.

func PartitionsToPartitionIter added in v0.12.0

func PartitionsToPartitionIter(partitions ...Partition) PartitionIter

PartitionsToPartitionIter creates a PartitionIter that iterates over the given partitions.

type PartitionProgress

type PartitionProgress struct {
	Progress
}

PartitionProgress keeps track of a partition progress

func (PartitionProgress) String

func (p PartitionProgress) String() string

type PersistableSession added in v0.12.0

type PersistableSession interface {
	Session
	// PersistGlobal writes to the persisted global system variables file
	PersistGlobal(sysVarName string, value interface{}) error
	// RemovePersistedGlobal deletes a variable from the persisted globals file
	RemovePersistedGlobal(sysVarName string) error
	// RemoveAllPersistedGlobals clears the contents of the persisted globals file
	RemoveAllPersistedGlobals() error
	// GetPersistedValue returns persisted value for a global system variable
	GetPersistedValue(k string) (interface{}, error)
}

PersistableSession supports serializing/deserializing global system variables/

type PrimaryKeyAlterableTable added in v0.11.0

type PrimaryKeyAlterableTable interface {
	Table
	// CreatePrimaryKey creates a primary key for this table, using the provided parameters.
	// Returns an error if the new primary key set is not compatible with the current table data.
	CreatePrimaryKey(ctx *Context, columns []IndexColumn) error
	// DropPrimaryKey drops a primary key on a table. Returns an error if that table does not have a key.
	DropPrimaryKey(ctx *Context) error
}

PrimaryKeyAlterableTable represents a table that supports primary key changes.

type PrimaryKeySchema added in v0.12.0

type PrimaryKeySchema struct {
	Schema
	PkOrdinals []int
}

PrimaryKeySchema defines table metadata for columns and primary key ordering

func NewPrimaryKeySchema added in v0.12.0

func NewPrimaryKeySchema(s Schema, pkOrds ...int) PrimaryKeySchema

NewPrimaryKeySchema constructs a new PrimaryKeySchema. PK ordinals default to the in-order set read from the Schema.

func SchemaToPrimaryKeySchema added in v0.12.0

func SchemaToPrimaryKeySchema(table Table, sch Schema, renames ...ColumnRename) PrimaryKeySchema

SchemaToPrimaryKeySchema adapts the schema given to a PrimaryKey schema using the primary keys of the table given, if present. The resulting PrimaryKeySchema may have an empty key set if the table has no primary keys. Matching for ordinals is performed by column name, with the aid of |renames| when provided.

type PrimaryKeySchemaTarget added in v0.12.0

type PrimaryKeySchemaTarget interface {
	SchemaTarget
	WithPrimaryKeySchema(schema PrimaryKeySchema) (Node, error)
}

PrimaryKeySchemaTarget is a node that has a primary key target schema that can be set

type PrimaryKeyTable added in v0.12.0

type PrimaryKeyTable interface {
	// PrimaryKeySchema returns this table's PrimaryKeySchema
	PrimaryKeySchema() PrimaryKeySchema
}

PrimaryKeyTable is a table with a primary key.

type PrivilegeCheckSubject added in v0.18.0

type PrivilegeCheckSubject struct {
	Database    string
	Table       string
	Column      string
	Routine     string
	IsProcedure bool // true if the routine is a procedure, false if it's a function
}

PrivilegeCheckSubject is a struct that contains the entity information for an access check. It's specifically what is being accessed - but not what operation is being attempted.

type PrivilegeSet added in v0.15.0

type PrivilegeSet interface {
	// Has returns whether the given global privilege(s) exists.
	Has(privileges ...PrivilegeType) bool
	// HasPrivileges returns whether this PrivilegeSet has any privileges at any level.
	HasPrivileges() bool
	// Count returns the number of global privileges.
	Count() int
	// Database returns the set of privileges for the given database. Returns an empty set if the database does not exist.
	Database(dbName string) PrivilegeSetDatabase
	// GetDatabases returns all databases.
	GetDatabases() []PrivilegeSetDatabase
	// Equals returns whether the given set of privileges is equivalent to the calling set.
	Equals(otherPs PrivilegeSet) bool
	// ToSlice returns all of the global privileges contained as a sorted slice.
	ToSlice() []PrivilegeType
}

PrivilegeSet is a set containing privileges. Integrators should not implement this interface.

type PrivilegeSetColumn added in v0.15.0

type PrivilegeSetColumn interface {
	// Name returns the name of the column that this privilege set belongs to.
	Name() string
	// Has returns whether the given column privilege(s) exists.
	Has(privileges ...PrivilegeType) bool
	// Count returns the number of column privileges.
	Count() int
	// Equals returns whether the given set of privileges is equivalent to the calling set.
	Equals(otherPs PrivilegeSetColumn) bool
	// ToSlice returns all of the column privileges contained as a sorted slice.
	ToSlice() []PrivilegeType
}

PrivilegeSetColumn is a set containing column privileges. Integrators should not implement this interface.

type PrivilegeSetDatabase added in v0.15.0

type PrivilegeSetDatabase interface {
	// Name returns the name of the database that this privilege set belongs to.
	Name() string
	// Has returns whether the given database privilege(s) exists.
	Has(privileges ...PrivilegeType) bool
	// HasPrivileges returns whether this database has either database-level privileges, or privileges on a table or
	// column contained within this database.
	HasPrivileges() bool
	// Count returns the number of database privileges.
	Count() int
	// Table returns the set of privileges for the given table. Returns an empty set if the table does not exist.
	Table(tblName string) PrivilegeSetTable
	// GetTables returns all tables.
	GetTables() []PrivilegeSetTable
	// Routine returns the set of privileges for the given routine. Returns an empty set if the routine does not exist.
	Routine(routineName string, isProcedure bool) PrivilegeSetRoutine
	// GetRoutines returns all routines.
	GetRoutines() []PrivilegeSetRoutine
	// Equals returns whether the given set of privileges is equivalent to the calling set.
	Equals(otherPs PrivilegeSetDatabase) bool
	// ToSlice returns all of the database privileges contained as a sorted slice.
	ToSlice() []PrivilegeType
}

PrivilegeSetDatabase is a set containing database-level privileges. Integrators should not implement this interface.

type PrivilegeSetRoutine added in v0.18.0

type PrivilegeSetRoutine interface {
	// RoutineName returns the name of the routine that this privilege set belongs to.
	RoutineName() string
	// RoutineType returns "FUNCTION" or "PROCEDURE".
	RoutineType() string
	// Has returns true if all PrivilegeTypes are present in the PrivilegeSet.
	Has(privileges ...PrivilegeType) bool
	// HasPrivileges returns whether this routine has any privileges.
	HasPrivileges() bool
	// Count returns the number of privileges on the routine
	Count() int
	// Equals returns whether the given set of privileges is equivalent to the calling set.
	Equals(otherPs PrivilegeSetRoutine) bool
	// ToSlice returns all of the routines privileges as a sorted slice.
	ToSlice() []PrivilegeType
}

PrivilegeSetRoutine is a set containing routine privileges. Routines are either functions or procedures, and permissions for them are handled identically.

type PrivilegeSetTable added in v0.15.0

type PrivilegeSetTable interface {
	// Name returns the name of the table that this privilege set belongs to.
	Name() string
	// Has returns whether the given table privilege(s) exists.
	Has(privileges ...PrivilegeType) bool
	// HasPrivileges returns whether this table has either table-level privileges, or privileges on a column contained
	// within this table.
	HasPrivileges() bool
	// Count returns the number of table privileges.
	Count() int
	// Column returns the set of privileges for the given column. Returns an empty set if the column does not exist.
	Column(colName string) PrivilegeSetColumn
	// GetColumns returns all columns.
	GetColumns() []PrivilegeSetColumn
	// Equals returns whether the given set of privileges is equivalent to the calling set.
	Equals(otherPs PrivilegeSetTable) bool
	// ToSlice returns all of the table privileges contained as a sorted slice.
	ToSlice() []PrivilegeType
}

PrivilegeSetTable is a set containing table-level privileges. Integrators should not implement this interface.

type PrivilegeType added in v0.12.0

type PrivilegeType int

PrivilegeType represents a privilege.

const (
	PrivilegeType_Select PrivilegeType = iota
	PrivilegeType_Insert
	PrivilegeType_Update
	PrivilegeType_Delete
	PrivilegeType_Create
	PrivilegeType_Drop
	PrivilegeType_Reload
	PrivilegeType_Shutdown
	PrivilegeType_Process
	PrivilegeType_File
	PrivilegeType_GrantOption
	PrivilegeType_References
	PrivilegeType_Index
	PrivilegeType_Alter
	PrivilegeType_ShowDB
	PrivilegeType_Super
	PrivilegeType_CreateTempTable
	PrivilegeType_LockTables
	PrivilegeType_Execute
	PrivilegeType_ReplicationSlave
	PrivilegeType_ReplicationClient
	PrivilegeType_CreateView
	PrivilegeType_ShowView
	PrivilegeType_CreateRoutine
	PrivilegeType_AlterRoutine
	PrivilegeType_CreateUser
	PrivilegeType_Event
	PrivilegeType_Trigger
	PrivilegeType_CreateTablespace
	PrivilegeType_CreateRole
	PrivilegeType_DropRole
)

func PrivilegeTypeFromString added in v0.12.0

func PrivilegeTypeFromString(privilegeType string) (PrivilegeType, bool)

PrivilegeTypeFromString returns the matching PrivilegeType for the given string. If there is no match, returns false.

func (PrivilegeType) String added in v0.12.0

func (pt PrivilegeType) String() string

String returns the sql.PrivilegeType as a string, for display in places such as "SHOW GRANTS".

type PrivilegedOperation added in v0.12.0

type PrivilegedOperation struct {
	Database          string
	Table             string
	Column            string
	Routine           string
	IsProcedure       bool // true if the routine is a procedure, false if it's a function
	StaticPrivileges  []PrivilegeType
	DynamicPrivileges []string
}

PrivilegedOperation represents an operation that requires privileges to execute.

func NewDynamicPrivilegedOperation added in v0.15.0

func NewDynamicPrivilegedOperation(privs ...string) PrivilegedOperation

NewDynamicPrivilegedOperation returns a new PrivilegedOperation for the specified dynamic privileges. Dynamic privileges may only be applied globally, so you cannot specify a database, table, or column.

func NewPrivilegedOperation added in v0.12.0

func NewPrivilegedOperation(subject PrivilegeCheckSubject, privs ...PrivilegeType) PrivilegedOperation

NewPrivilegedOperation returns a new PrivilegedOperation with the given parameters.

type PrivilegedOperationChecker added in v0.12.0

type PrivilegedOperationChecker interface {
	// UserHasPrivileges fetches the User, and returns whether they have the desired privileges necessary to perform the
	// privileged operation(s). This takes into account the active roles, which are set in the context, therefore both
	// the user and the active roles are pulled from the context. This method is sufficient for all MySQL behaviors.
	// The one exception, currently, is for stored procedures and functions, which have a more fine-grained permission
	// due to Dolt's use of the AdminOnly flag in procedure definitions.
	UserHasPrivileges(ctx *Context, operations ...PrivilegedOperation) bool
	// RoutineAdminCheck fetches the User from the context, and specifically evaluates, the permission check
	// assuming the operation is for a stored procedure or function. This allows us to have more fine grain control over
	// permissions for stored procedures (many of which are critical to Dolt). This method specifically checks exists
	// for the use of AdminOnly procedures which require more fine-grained access control. For procedures which are
	// not AdminOnly, then |UserHasPrivileges| should be used instead.
	RoutineAdminCheck(ctx *Context, operations ...PrivilegedOperation) bool
}

PrivilegedOperationChecker contains the necessary data to check whether the operation should succeed based on the privileges contained by the user. The user is retrieved from the context, along with their active roles.

type Process

type Process struct {
	Connection uint32
	Host       string
	Database   string
	User       string
	Command    ProcessCommand

	// The time of the last Command transition...
	StartedAt time.Time

	QueryPid uint64
	Query    string
	Progress map[string]TableProgress
	Kill     context.CancelFunc
}

Process represents a process in the SQL server.

func (*Process) Done

func (p *Process) Done()

Done needs to be called when this process has finished.

func (*Process) Seconds

func (p *Process) Seconds() uint64

Seconds returns the number of seconds this process has been running.

type ProcessCommand added in v0.15.0

type ProcessCommand string
const (
	// During initial connection and handshake.
	ProcessCommandConnect ProcessCommand = "Connect"
	// Connected, not running a query.
	ProcessCommandSleep ProcessCommand = "Sleep"
	// Currently running a query, possibly streaming the response.
	ProcessCommandQuery ProcessCommand = "Query"
)

type ProcessList

type ProcessList interface {
	// Processes returns the list of current running processes
	Processes() []Process

	// AddConnection adds a new connection to the process list. Must be matched with RemoveConnection.
	AddConnection(connID uint32, addr string)

	// Transitions a connection from Connect to Sleep.
	ConnectionReady(sess Session)

	// RemoveConnection removes the connection from the process list.
	RemoveConnection(connID uint32)

	// BeginQuery transitions an existing connection in the processlist from Command "Sleep" to Command "Query".
	// Returns a new context which will be canceled when this query is done.
	BeginQuery(ctx *Context, query string) (*Context, error)

	// EndQuery transitions a previously transitioned connection from Command "Query" to Command "Sleep".
	EndQuery(ctx *Context)

	// Kill terminates all queries for a given connection id
	Kill(connID uint32)

	// UpdateTableProgress updates the progress of the table with the given name for the
	// process with the given pid.
	UpdateTableProgress(pid uint64, name string, delta int64)

	// UpdatePartitionProgress updates the progress of the table partition with the
	// given name for the process with the given pid.
	UpdatePartitionProgress(pid uint64, tableName, partitionName string, delta int64)

	// AddTableProgress adds a new item to track progress from to the process with
	// the given pid. If the pid does not exist, it will do nothing.
	AddTableProgress(pid uint64, name string, total int64)

	// AddPartitionProgress adds a new item to track progress from to the process with
	// the given pid. If the pid or the table does not exist, it will do nothing.
	AddPartitionProgress(pid uint64, tableName, partitionName string, total int64)

	// RemoveTableProgress removes an existing item tracking progress from the
	// process with the given pid, if it exists.
	RemoveTableProgress(pid uint64, name string)

	// RemovePartitionProgress removes an existing partition tracking progress from the
	// process with the given pid, if it exists.
	RemovePartitionProgress(pid uint64, tableName, partitionName string)
}

type Progress

type Progress struct {
	Name  string
	Done  int64
	Total int64
}

Progress between done items and total items

type ProjectedTable

type ProjectedTable interface {
	Table
	// WithProjections returns a version of this table with only the subset of columns named. Calls to Schema must
	// only include these columns. A zero-length slice of column names is valid and indicates that rows from this table
	// should be spooled, but no columns should be returned. A nil slice will never be provided.
	WithProjections(colNames []string) Table
	// Projections returns the names of the column projections applied to this table, or nil if no projection is applied
	// and all columns of the schema will be returned.
	Projections() []string
}

ProjectedTable is a table that can return only a subset of its columns from RowIter. This provides a very large efficiency gain during table scans. Tables that implement this interface must return only the projected columns in future calls to Schema.

type Projector added in v0.14.0

type Projector interface {
	// ProjectedExprs returns the list of expressions projected by this node.
	ProjectedExprs() []Expression
}

Projector is a node that projects expressions for parent nodes to consume (i.e. GroupBy, Window, Project).

type QueryFlags added in v0.19.0

type QueryFlags struct {
	Flags FastIntSet
}

func (*QueryFlags) DmlIsSet added in v0.19.0

func (qp *QueryFlags) DmlIsSet() bool

func (*QueryFlags) IsSet added in v0.19.0

func (qp *QueryFlags) IsSet(flag int) bool

func (*QueryFlags) JoinIsSet added in v0.19.0

func (qp *QueryFlags) JoinIsSet() bool

func (*QueryFlags) Set added in v0.19.0

func (qp *QueryFlags) Set(flag int)

func (*QueryFlags) SubqueryIsSet added in v0.19.0

func (qp *QueryFlags) SubqueryIsSet() bool

func (*QueryFlags) Unset added in v0.19.0

func (qp *QueryFlags) Unset(flag int)

type Range added in v0.12.0

type Range interface {
	DebugStringer
	fmt.Stringer
	Equals(other Range) (bool, error)
}

Range represents a set iteration over an integrator's index. Ranges are not required to be contiguous, although they are expected to not overlap.

type RangeCollection added in v0.12.0

type RangeCollection interface {
	DebugStringer
	fmt.Stringer
	Equals(otherCollection RangeCollection) (bool, error)
	Len() int
	ToRanges() []Range
}

RangeCollection is a collection of ranges that represent different (non-overlapping) filter expressions.

type RangeType added in v0.12.0

type RangeType int

RangeType returns what a MySQLRangeColumnExpr represents, such as a GreaterThan on some column, or a column set between two bounds.

const (
	RangeType_Invalid           RangeType = iota // This range is invalid, which should not be possible. Please create a GitHub issue if this is ever returned.
	RangeType_Empty                              // This range represents the empty set of values.
	RangeType_All                                // This range represents every possible value.
	RangeType_GreaterThan                        // This range is equivalent to checking for all values greater than the lowerbound.
	RangeType_GreaterOrEqual                     // This range is equivalent to checking for all values greater than or equal to the lowerbound.
	RangeType_LessThanOrNull                     // This range is equivalent to checking for all values less than the upperbound.
	RangeType_LessOrEqualOrNull                  // This range is equivalent to checking for all values less than or equal to the upperbound.
	RangeType_ClosedClosed                       // This range covers a finite set of values with the lower and upperbounds inclusive.
	RangeType_OpenOpen                           // This range covers a finite set of values with the lower and upperbounds exclusive.
	RangeType_OpenClosed                         // This range covers a finite set of values with the lowerbound exclusive and upperbound inclusive.
	RangeType_ClosedOpen                         // This range covers a finite set of values with the lowerbound inclusive and upperbound exclusive.
	RangeType_EqualNull                          // A range matching only NULL.
)

type ReadOnlyDatabase added in v0.11.0

type ReadOnlyDatabase interface {
	Database
	// IsReadOnly returns whether this database is read-only.
	IsReadOnly() bool
}

ReadOnlyDatabase is an extension of Database that may declare itself read-only, which will disallow any DDL or DML statements from executing.

type ReferenceChecker added in v0.18.0

type ReferenceChecker interface {
	SetReferenceCheck() error
}

ReferenceChecker is usually an IndexAddressableTable that does key lookups for existence checks. Indicating that the engine is performing a reference check lets the integrator avoid expensive deserialization steps.

type RenameableNode added in v0.15.0

type RenameableNode interface {
	Nameable
	Node
	// WithName returns a copy of the node with the name changed.
	WithName(string) Node
}

RenameableNode is a Node that can be renamed.

type ReplaceableTable

type ReplaceableTable interface {
	Table
	// Replacer returns a RowReplacer for this table. The RowReplacer will have Insert and optionally Delete called once
	// for each row, followed by a call to Close() when all rows have been processed.
	Replacer(ctx *Context) RowReplacer
}

ReplaceableTable allows rows to be replaced through a Delete (if applicable) then Insert.

type Reporter

type Reporter interface {
	// MaxMemory returns the maximum number of memory allowed in bytes.
	MaxMemory() uint64
	// UsedMemory returns the memory in use in bytes.
	UsedMemory() uint64
}

Reporter is a component that gives information about the memory usage.

var ProcessMemory Reporter = new(processReporter)

ProcessMemory is a reporter for the memory used by the process and the maximum amount of memory allowed controlled by the MAX_MEMORY environment variable.

type Resolvable

type Resolvable interface {
	// Resolved returns whether the node is resolved.
	Resolved() bool
}

Resolvable is something that can be resolved or not.

type RewritableTable added in v0.12.0

type RewritableTable interface {
	Table
	AlterableTable

	// ShouldRewriteTable returns whether this table should be rewritten because of a schema change. The old and new
	// versions of the schema and modified column are provided. For some operations, one or both of |oldColumn| or
	// |newColumn| may be nil.
	// The engine may decide to rewrite tables regardless in some cases, such as when a new non-nullable column is added.
	ShouldRewriteTable(ctx *Context, oldSchema, newSchema PrimaryKeySchema, oldColumn, newColumn *Column) bool

	// RewriteInserter returns a RowInserter for the new schema. Rows from the current table, with the old schema, will
	// be streamed from the table and passed to this RowInserter. Implementor tables must still return rows in the
	// current schema until the rewrite operation completes. |Close| will be called on RowInserter when all rows have
	// been inserted.
	RewriteInserter(ctx *Context, oldSchema, newSchema PrimaryKeySchema, oldColumn, newColumn *Column, idxCols []IndexColumn) (RowInserter, error)
}

RewritableTable is an extension to Table that makes it simpler for integrators to adapt to schema changes that must rewrite every row of the table. In this case, rows are streamed from the existing table in the old schema, transformed / updated appropriately, and written with the new format.

type Row

type Row []interface{}

Row is a tuple of values.

func NewRow

func NewRow(values ...interface{}) Row

NewRow creates a row from the given values.

func RowIterToRows

func RowIterToRows(ctx *Context, i RowIter) ([]Row, error)

RowIterToRows converts a row iterator to a slice of rows.

func (Row) Append

func (r Row) Append(r2 Row) Row

Append appends all the values in r2 to this row and returns the result

func (Row) Copy

func (r Row) Copy() Row

Copy creates a new row with the same values as the current one.

func (Row) Equals

func (r Row) Equals(row Row, schema Schema) (bool, error)

Equals checks whether two rows are equal given a schema.

type Row2 added in v0.12.0

type Row2 []Value

Row2 is a slice of values

func (Row2) GetField added in v0.12.0

func (r Row2) GetField(i int) Value

GetField returns the Value for the ith field in this row.

func (Row2) Len added in v0.12.0

func (r Row2) Len() int

Len returns the number of fields of this row

type RowDeleter

type RowDeleter interface {
	EditOpenerCloser
	// Delete deletes the given row. Returns ErrDeleteRowNotFound if the row was not found. Delete will be called once for
	// each row to process for the delete operation, which may involve many rows. After all rows have been processed,
	// Close is called.
	Delete(*Context, Row) error
	// Closer finalizes the delete operation, persisting the result.
	Closer
}

RowDeleter is a delete cursor that can delete one or more rows from a table.

type RowFrame added in v0.12.0

type RowFrame struct {
	Types []querypb.Type

	// Values are the values this row.
	Values []ValueBytes
	// contains filtered or unexported fields
}

func NewRowFrame added in v0.12.0

func NewRowFrame(vals ...Value) (f *RowFrame)

func (*RowFrame) Append added in v0.12.0

func (f *RowFrame) Append(vals ...Value)

Append appends the values given into this frame.

func (*RowFrame) AppendMany added in v0.12.0

func (f *RowFrame) AppendMany(types []querypb.Type, vals []ValueBytes)

AppendMany appends the types and values given, as two parallel arrays, into this frame.

func (*RowFrame) Clear added in v0.12.0

func (f *RowFrame) Clear()

Clear clears this row frame for reuse. The underlying byte arrays are not zeroed out or discarded, but will be overwritten by future calls to Append.

func (*RowFrame) Recycle added in v0.12.0

func (f *RowFrame) Recycle()

Recycle returns this row frame to the shared pool. Further use will result in concurrency errors. All RowFrames should be recycled when they are no longer being used to prevent resource leaks.

func (*RowFrame) Row2 added in v0.12.0

func (f *RowFrame) Row2() Row2

Row2 returns the underlying row value in this frame. Does not make a deep copy of underlying byte arrays, so further modification to this frame may result in the returned value changing as well.

func (*RowFrame) Row2Copy added in v0.12.0

func (f *RowFrame) Row2Copy() Row2

Row2Copy returns the row in this frame as a deep copy of the underlying byte arrays. Useful when reusing the RowFrame object via Clear()

type RowInserter

type RowInserter interface {
	EditOpenerCloser
	// Insert inserts the row given, returning an error if it cannot. Insert will be called once for each row to process
	// for the insert operation, which may involve many rows. After all rows in an operation have been processed, Close
	// is called.
	Insert(*Context, Row) error
	// Close finalizes the insert operation, persisting its result.
	Closer
}

RowInserter is an insert cursor that can insert one or more values to a table.

type RowIter

type RowIter interface {
	// Next retrieves the next row. It will return io.EOF if it's the last row.
	// After retrieving the last row, Close will be automatically closed.
	Next(ctx *Context) (Row, error)
	Closer
}

RowIter is an iterator that produces rows. TODO: most row iters need to be Disposable for CachedResult safety

func NewSpanIter

func NewSpanIter(span trace.Span, iter RowIter) RowIter

NewSpanIter creates a RowIter executed in the given span. Currently inactive, returns the iter returned unaltered.

func RowsToRowIter

func RowsToRowIter(rows ...Row) RowIter

RowsToRowIter creates a RowIter that iterates over the given rows.

type RowReplacer

type RowReplacer interface {
	EditOpenerCloser
	RowInserter
	RowDeleter
}

RowReplacer is a combination of RowDeleter and RowInserter.

type RowUpdater

type RowUpdater interface {
	EditOpenerCloser
	// Update the given row. Provides both the old and new rows.
	Update(ctx *Context, old Row, new Row) error
	// Closer finalizes the update operation, persisting the result.
	Closer
}

RowUpdater is an update cursor that can update one or more rows in a table.

type Rows2Cache added in v0.12.0

type Rows2Cache interface {
	RowsCache
	// Add2 a new row to the cache. If there is no memory available, it will try to
	// free some memory. If after that there is still no memory available, it
	// will return an error and erase all the content of the cache.
	Add2(Row2) error
	// Get2 gets all rows.
	Get2() []Row2
}

Rows2Cache is a cache of Row2s.

type RowsCache

type RowsCache interface {
	// Add a new row to the cache. If there is no memory available, it will try to
	// free some memory. If after that there is still no memory available, it
	// will return an error and erase all the content of the cache.
	Add(Row) error
	// Get returns all rows.
	Get() []Row
}

RowsCache is a cache of rows.

type Schema

type Schema []*Column

Schema is the definition of a table.

func (Schema) CaseSensitiveEquals added in v0.17.0

func (s Schema) CaseSensitiveEquals(s2 Schema) bool

CaseSensitiveEquals checks whether the given schema is equal to this one, failing for column names with different casing

func (Schema) CheckRow

func (s Schema) CheckRow(row Row) error

CheckRow checks the row conforms to the schema.

func (Schema) Contains

func (s Schema) Contains(column string, source string) bool

Contains returns whether the schema contains a column with the given name.

func (Schema) Copy added in v0.12.0

func (s Schema) Copy() Schema

Copy returns a deep copy of this schema, making a copy of all columns

func (Schema) Equals

func (s Schema) Equals(s2 Schema) bool

Equals checks whether the given schema is equal to this one.

func (Schema) HasAutoIncrement added in v0.11.0

func (s Schema) HasAutoIncrement() bool

HasAutoIncrement returns true if the schema has an auto increment column.

func (Schema) HasVirtualColumns added in v0.18.0

func (s Schema) HasVirtualColumns() bool

HasVirtualColumns returns whether the schema has any virtual columns

func (Schema) IndexOf

func (s Schema) IndexOf(column, source string) int

IndexOf returns the index of the given column in the schema or -1 if it's not present.

func (Schema) IndexOfColName added in v0.12.0

func (s Schema) IndexOfColName(column string) int

IndexOfColName returns the index of the given column in the schema or -1 if it's not present. Only safe for schemas corresponding to a single table, where the source of the column is irrelevant.

func (Schema) PhysicalSchema added in v0.18.0

func (s Schema) PhysicalSchema() Schema

PhysicalSchema returns a schema with only the physical (non-virtual) columns

func (Schema) Resolved added in v0.16.0

func (s Schema) Resolved() bool

Resolved returns true if this schema is fully resolved. Currently, the only piece of a schema that needs to be resolved are any column default value expressions.

type SchemaDatabase added in v0.19.0

type SchemaDatabase interface {
	Nameable
	// GetSchema returns the database with the schema name provided, matched case-insensitive.
	// If the schema does not exist, the boolean return value should be false.
	GetSchema(ctx *Context, schemaName string) (DatabaseSchema, bool, error)
	// CreateSchema creates a new schema in the database.
	// If the schema already exists, should return ErrSchemaAlreadyExists, although the engine checks this as well.
	CreateSchema(ctx *Context, schemaName string) error
	// AllSchemas returns all schemas in the database.
	AllSchemas(ctx *Context) ([]DatabaseSchema, error)
}

SchemaDatabase is a database comprising multiple schemas that can each be queried for tables.

type SchemaTarget added in v0.12.0

type SchemaTarget interface {
	// WithTargetSchema returns a copy of this node with the target schema set
	WithTargetSchema(Schema) (Node, error)
	// TargetSchema returns the target schema for this node
	TargetSchema() Schema
}

SchemaTarget is a node that has a target schema that can be set during analysis. This is necessary because some schema objects (things that involve expressions, column references, etc.) can only be reified during analysis. The target schema is the schema of a table under a DDL operation, not the schema of rows returned by this node.

type SchemaValidator added in v0.18.0

type SchemaValidator interface {
	Database
	// ValidateSchema lets storage integrators validate whether they can
	// serialize a given schema.
	ValidateSchema(Schema) error
}

SchemaValidator is a database that performs schema compatibility checks for CREATE and ALTER TABLE statements.

type Services added in v0.12.0

type Services struct {
	KillConnection func(connID uint32) error
	LoadInfile     func(filename string) (io.ReadCloser, error)
}

Services are handles to optional or plugin functionality that can be used by the SQL implementation in certain situations. An integrator can set methods on Services for a given *Context and different parts of go-mysql-server will inspect it in order to fulfill their implementations. Currently, the KillConnection service is available. Set these with |WithServices|; the implementation will access them through the corresponding methods on *Context, such as |KillConnection|.

type Session

type Session interface {
	// Address of the server.
	Address() string
	// Client returns the user of the session.
	Client() Client
	// SetClient returns a new session with the given client.
	SetClient(Client)
	// SetSessionVariable sets the given system variable to the value given for this session.
	SetSessionVariable(ctx *Context, sysVarName string, value interface{}) error
	// InitSessionVariable sets the given system variable to the value given for this session and will allow for
	// initialization of readonly variables.
	InitSessionVariable(ctx *Context, sysVarName string, value interface{}) error
	// SetUserVariable sets the given user variable to the value given for this session, or creates it for this session.
	SetUserVariable(ctx *Context, varName string, value interface{}, typ Type) error
	// GetSessionVariable returns this session's value of the system variable with the given name.
	// To access global scope, use sql.SystemVariables.GetGlobal instead.
	GetSessionVariable(ctx *Context, sysVarName string) (interface{}, error)
	// GetUserVariable returns this session's value of the user variable with the given name, along with its most
	// appropriate type.
	GetUserVariable(ctx *Context, varName string) (Type, interface{}, error)
	// GetAllSessionVariables returns a copy of all session variable values.
	GetAllSessionVariables() map[string]interface{}
	// GetStatusVariable returns the value of the status variable with session scope with the given name.
	// To access global scope, use sql.StatusVariables instead.
	GetStatusVariable(ctx *Context, statVarName string) (interface{}, error)
	// SetStatusVariable sets the value of the status variable with session scope with the given name.
	// To access global scope, use sql.StatusVariables.GetGlobal instead.
	SetStatusVariable(ctx *Context, statVarName string, val interface{}) error
	// GetAllStatusVariables returns a map of all status variables with session scope and their values.
	// To access global scope, use sql.StatusVariables instead.
	GetAllStatusVariables(ctx *Context) map[string]StatusVarValue
	// IncrementStatusVariable increments the value of the status variable by the integer value
	IncrementStatusVariable(ctx *Context, statVarName string, val int)
	// GetCurrentDatabase gets the current database for this session
	GetCurrentDatabase() string
	// SetCurrentDatabase sets the current database for this session
	SetCurrentDatabase(dbName string)
	// UseDatabase notifies sessions that a particular database is now the default DB namespace
	UseDatabase(ctx *Context, db Database) error
	// ID returns the unique ID of the connection.
	ID() uint32
	// Warn stores the warning in the session.
	Warn(warn *Warning)
	// Warnings returns a copy of session warnings (from the most recent).
	Warnings() []*Warning
	// ClearWarningCount clears the warning count without clearing the actual warnings.
	ClearWarningCount()
	// ClearWarnings cleans up session warnings.
	ClearWarnings()
	// WarningCount returns a number of session warnings
	WarningCount() uint16
	// LockWarnings prevents the session warnings from being cleared.
	LockWarnings()
	// UnlockWarnings allows the session warnings to be cleared.
	UnlockWarnings()
	// AddLock adds a lock to the set of locks owned by this user which will need to be released if this session terminates
	AddLock(lockName string) error
	// DelLock removes a lock from the set of locks owned by this user
	DelLock(lockName string) error
	// IterLocks iterates through all locks owned by this user
	IterLocks(cb func(name string) error) error
	// SetLastQueryInfoInt sets session-level query info for the key given, applying to the query just executed.
	SetLastQueryInfoInt(key string, value int64)
	// GetLastQueryInfoInt returns the session-level query info for the key given, for the query most recently executed.
	GetLastQueryInfoInt(key string) int64
	// SetLastQueryInfoString sets session-level query info as a string for the key given, applying to the query just executed.
	SetLastQueryInfoString(key string, value string)
	// GetLastQueryInfoString returns the session-level query info as a string for the key given, for the query most recently executed.
	GetLastQueryInfoString(key string) string
	// GetTransaction returns the active transaction, if any
	GetTransaction() Transaction
	// SetTransaction sets the session's transaction
	SetTransaction(tx Transaction)
	// SetIgnoreAutoCommit instructs the session to ignore the value of the @@autocommit variable, or consider it again
	SetIgnoreAutoCommit(ignore bool)
	// GetIgnoreAutoCommit returns whether this session should ignore the @@autocommit variable
	GetIgnoreAutoCommit() bool
	// GetLogger returns the logger for this session, useful if clients want to log messages with the same format / output
	// as the running server. Clients should instantiate their own global logger with formatting options, and session
	// implementations should return the logger to be used for the running server.
	GetLogger() *logrus.Entry
	// SetLogger sets the logger to use for this session, which will always be an extension of the one returned by
	// GetLogger, extended with session information
	SetLogger(*logrus.Entry)
	// GetIndexRegistry returns the index registry for this session
	GetIndexRegistry() *IndexRegistry
	// GetViewRegistry returns the view registry for this session
	GetViewRegistry() *ViewRegistry
	// SetIndexRegistry sets the index registry for this session. Integrators should set an index registry in the event
	// they are using an index driver.
	SetIndexRegistry(*IndexRegistry)
	// SetViewRegistry sets the view registry for this session. Integrators should set a view registry if their database
	// doesn't implement ViewDatabase and they want views created to persist across sessions.
	SetViewRegistry(*ViewRegistry)
	// SetConnectionId sets this sessions unique ID
	SetConnectionId(connId uint32)
	// GetCharacterSet returns the character set for this session (defined by the system variable `character_set_connection`).
	GetCharacterSet() CharacterSetID
	// GetCharacterSetResults returns the result character set for this session (defined by the system variable `character_set_results`).
	GetCharacterSetResults() CharacterSetID
	// GetCollation returns the collation for this session (defined by the system variable `collation_connection`).
	GetCollation() CollationID
	// GetPrivilegeSet returns the cached privilege set associated with this session, along with its counter. The
	// PrivilegeSet is only valid when the counter is greater than zero.
	GetPrivilegeSet() (PrivilegeSet, uint64)
	// SetPrivilegeSet updates this session's cache with the given counter and privilege set. Setting the counter to a
	// value of zero will force the cache to reload. This is an internal function and is not intended to be used by
	// integrators.
	SetPrivilegeSet(newPs PrivilegeSet, counter uint64)
	// ValidateSession provides integrators a chance to do any custom validation of this session before any query is
	// executed in it. For example, Dolt uses this hook to validate that the session's working set is valid.
	ValidateSession(ctx *Context) error
}

Session holds the session data.

type SessionUserVariables added in v0.15.0

type SessionUserVariables interface {
	// SetUserVariable sets the user variable name to the given value and type
	SetUserVariable(ctx *Context, varName string, value interface{}, typ Type) error
	// GetUserVariable returns the value and type of the user variable named
	GetUserVariable(ctx *Context, varName string) (Type, interface{}, error)
}

SessionUserVariables is a simple dictionary to set and retrieve user variables within a session.

func NewUserVars added in v0.15.0

func NewUserVars() SessionUserVariables

type SetType

type SetType interface {
	Type
	CharacterSet() CharacterSetID
	Collation() CollationID
	// NumberOfElements returns the number of elements in this set.
	NumberOfElements() uint16
	// BitsToString takes a previously-converted value and returns it as a string.
	BitsToString(bits uint64) (string, error)
	// Values returns all of the set's values in ascending order according to their corresponding bit value.
	Values() []string
}

SetType represents the SET type. https://dev.mysql.com/doc/refman/8.0/en/set.html The type of the returned value is uint64.

type SortField added in v0.9.0

type SortField struct {
	// Column to order by.
	Column Expression
	// Column Expression2 to order by. This is always the same value as Column, but avoids a type cast
	Column2 Expression2
	// Order type.
	Order SortOrder
	// NullOrdering defining how nulls will be ordered.
	NullOrdering NullOrdering
}

SortField is a field by which a query will be sorted.

func (SortField) DebugString added in v0.9.0

func (s SortField) DebugString() string

func (SortField) String added in v0.9.0

func (s SortField) String() string

type SortFields added in v0.9.0

type SortFields []SortField

func (SortFields) FromExpressions added in v0.9.0

func (sf SortFields) FromExpressions(exprs ...Expression) SortFields

func (SortFields) ToExpressions added in v0.9.0

func (sf SortFields) ToExpressions() []Expression

type SortOrder added in v0.9.0

type SortOrder byte

SortOrder represents the order of the sort (ascending or descending).

const (
	// Ascending order.
	Ascending SortOrder = 1
	// Descending order.
	Descending SortOrder = 2
)

func (SortOrder) String added in v0.9.0

func (s SortOrder) String() string

type SpatialColumnType added in v0.12.0

type SpatialColumnType interface {
	// GetSpatialTypeSRID returns the SRID value for spatial types.
	GetSpatialTypeSRID() (uint32, bool)
	// SetSRID sets SRID value for spatial types.
	SetSRID(uint32) Type
	// MatchSRID returns nil if column type SRID matches given value SRID otherwise returns error.
	MatchSRID(interface{}) error
}

SpatialColumnType is a node that contains a reference to all spatial types.

type SpatialIndexBuilder added in v0.15.0

type SpatialIndexBuilder struct {
	// contains filtered or unexported fields
}

SpatialIndexBuilder is like the MySQLIndexBuilder, but spatial

func NewSpatialIndexBuilder added in v0.15.0

func NewSpatialIndexBuilder(idx Index) *SpatialIndexBuilder

func (*SpatialIndexBuilder) AddRange added in v0.15.0

func (b *SpatialIndexBuilder) AddRange(lower, upper interface{}) *SpatialIndexBuilder

func (*SpatialIndexBuilder) Build added in v0.15.0

func (b *SpatialIndexBuilder) Build() (IndexLookup, error)

type SqlMode added in v0.17.0

type SqlMode struct {
	// contains filtered or unexported fields
}

SqlMode encodes the SQL mode string and provides methods for querying the enabled modes.

func LoadSqlMode added in v0.17.0

func LoadSqlMode(ctx *Context) *SqlMode

LoadSqlMode loads the SQL mode using the session data contained in |ctx| and returns a SqlMode instance that can be used to query which modes are enabled.

func NewSqlModeFromString added in v0.17.0

func NewSqlModeFromString(sqlModeString string) *SqlMode

NewSqlModeFromString returns a new SqlMode instance, constructed from the specified |sqlModeString| that has a comma delimited list of SQL modes (e.g. "ONLY_FULLY_GROUP_BY,ANSI_QUOTES").

func (*SqlMode) AnsiQuotes added in v0.17.0

func (s *SqlMode) AnsiQuotes() bool

AnsiQuotes returns true if the ANSI_QUOTES SQL mode is enabled. Note that the ANSI mode is a compound mode that includes ANSI_QUOTES and other options, so if ANSI or ANSI_QUOTES is enabled, this function will return true.

func (*SqlMode) ModeEnabled added in v0.17.0

func (s *SqlMode) ModeEnabled(mode string) bool

ModeEnabled returns true if |mode| was explicitly specified in the SQL_MODE string that was used to create this SqlMode instance. Note this function does not support expanding compound modes into the individual modes they contain (e.g. if "ANSI" is the SQL_MODE string, then this function will not report that "ANSI_QUOTES" is enabled). To deal with compound modes, use the mode specific functions, such as SqlMode::AnsiQuotes().

func (*SqlMode) ParserOptions added in v0.17.0

func (s *SqlMode) ParserOptions() sqlparser.ParserOptions

ParserOptions returns a ParserOptions struct, with options set based on what SQL modes are enabled.

func (*SqlMode) String added in v0.17.0

func (s *SqlMode) String() string

String returns the SQL_MODE string representing this SqlMode instance.

type StatQualifier added in v0.18.0

type StatQualifier struct {
	Database string `json:"database"`
	Sch      string `json:"schema"`
	Tab      string `json:"table"`
	Idx      string `json:"index"`
}

StatQualifier is the namespace hierarchy for a given statistic. The qualifier and set of columns completely describes a unique stat.

func NewQualifierFromString added in v0.18.0

func NewQualifierFromString(q string) (StatQualifier, error)

NewQualifierFromString creates a new StatQualifier from a string.

func NewSchemaQualifierFromString added in v0.19.0

func NewSchemaQualifierFromString(q string) (StatQualifier, error)

NewSchemaQualifierFromString creates a new StatQualifier from a string, assuming the string contains a schema part.

func NewStatQualifier added in v0.18.0

func NewStatQualifier(db, schema, table, index string) StatQualifier

func (StatQualifier) Db added in v0.18.0

func (q StatQualifier) Db() string

func (StatQualifier) Empty added in v0.18.0

func (q StatQualifier) Empty() bool

func (StatQualifier) Index added in v0.18.0

func (q StatQualifier) Index() string

func (StatQualifier) Schema added in v0.19.0

func (q StatQualifier) Schema() string

func (StatQualifier) String added in v0.18.0

func (q StatQualifier) String() string

func (StatQualifier) Table added in v0.18.0

func (q StatQualifier) Table() string

type Statistic added in v0.18.0

type Statistic interface {
	JSONWrapper
	MutableStatistic
	RowCount() uint64
	DistinctCount() uint64
	NullCount() uint64
	AvgSize() uint64
	CreatedAt() time.Time
	Columns() []string
	Types() []Type
	Qualifier() StatQualifier
	Histogram() Histogram
	IndexClass() IndexClass
	FuncDeps() *FuncDepSet
	ColSet() ColSet
	LowerBound() Row
}

Statistic is the top-level interface for accessing cardinality and costing estimates for an index prefix.

type StatisticsTable

type StatisticsTable interface {
	Table
	// DataLength returns the length of the data file (varies by engine).
	DataLength(ctx *Context) (uint64, error)
	// RowCount returns the row count for this table and whether the count is exact
	RowCount(ctx *Context) (uint64, bool, error)
}

StatisticsTable is a table that can provide information about its number of rows and other facts to improve query planning performance.

type StatsProvider added in v0.18.0

type StatsProvider interface {
	// GetTableStats returns all statistics for the table
	GetTableStats(ctx *Context, db string, table Table) ([]Statistic, error)
	// RefreshTableStats updates all statistics associated with a given table
	RefreshTableStats(ctx *Context, table Table, db string) error
	// SetStats updates or overwrites a set of table statistics
	SetStats(ctx *Context, stats Statistic) error
	// GetStats fetches a set of statistics for a set of table columns
	GetStats(ctx *Context, qual StatQualifier, cols []string) (Statistic, bool)
	// DropStats deletes a set of column statistics
	DropStats(ctx *Context, qual StatQualifier, cols []string) error
	// DropAllStats deletes all database statistics
	DropDbStats(ctx *Context, db string, flush bool) error
	// RowCount returns the number of rows in a table
	RowCount(ctx *Context, db string, table Table) (uint64, error)
	// DataLength returns the estimated size of each row in the table
	DataLength(ctx *Context, db string, table Table) (uint64, error)
}

StatsProvider is a catalog extension for databases that can build and provide index statistics.

type StatusVarValue added in v0.18.1

type StatusVarValue interface {
	Increment(uint64) error
	Set(interface{}) error
	Value() interface{}
	Variable() StatusVariable
	Copy() StatusVarValue
}

type StatusVariable added in v0.18.1

type StatusVariable interface {
	GetName() string
	GetScope() StatusVariableScope
	GetType() Type
	GetDefault() interface{}
}

type StatusVariableRegistry added in v0.18.1

type StatusVariableRegistry interface {
	// NewSessionMap returns a deep copy of the status variables that are
	// not GlobalOnly scope (i.e. SessionOnly or Both)
	NewSessionMap() map[string]StatusVarValue
	// NewGlobalMap returns a deep copy of the status variables of every scope
	NewGlobalMap() map[string]StatusVarValue
	// GetGlobal returns the current global value of the status variable with the given name
	GetGlobal(name string) (StatusVariable, interface{}, bool)
	// SetGlobal sets the global value of the status variable with the given
	// name, returns an error if the variable is SessionOnly scope
	SetGlobal(name string, val interface{}) error
	// IncrementGlobal increments the value of the status variable by the
	// given integer value. Noop if the variable is session-only scoped.
	IncrementGlobal(name string, val int)
}

StatusVariableRegistry is a registry of status variables.

var StatusVariables StatusVariableRegistry

type StatusVariableScope added in v0.18.1

type StatusVariableScope byte

StatusVariableScope represents the scope of a status variable.

const (
	StatusVariableScope_Global StatusVariableScope = iota
	StatusVariableScope_Session
	StatusVariableScope_Both
)

type StoredProcedureDatabase added in v0.9.0

type StoredProcedureDatabase interface {
	Database
	// GetStoredProcedure returns the desired StoredProcedureDetails from the database.
	GetStoredProcedure(ctx *Context, name string) (StoredProcedureDetails, bool, error)
	// GetStoredProcedures returns all StoredProcedureDetails for the database.
	GetStoredProcedures(ctx *Context) ([]StoredProcedureDetails, error)
	// SaveStoredProcedure stores the given StoredProcedureDetails to the database. The integrator should verify that
	// the name of the new stored procedure is unique amongst existing stored procedures.
	SaveStoredProcedure(ctx *Context, spd StoredProcedureDetails) error
	// DropStoredProcedure removes the StoredProcedureDetails with the matching name from the database.
	DropStoredProcedure(ctx *Context, name string) error
}

StoredProcedureDatabase is a database that supports the creation and execution of stored procedures. The engine will handle all parsing and execution logic for stored procedures. Integrators only need to store and retrieve StoredProcedureDetails, while verifying that all stored procedures have a unique name without regard to case-sensitivity.

type StoredProcedureDetails added in v0.9.0

type StoredProcedureDetails struct {
	Name            string    // The name of this stored procedure. Names must be unique within a database.
	CreateStatement string    // The CREATE statement for this stored procedure.
	CreatedAt       time.Time // The time that the stored procedure was created.
	ModifiedAt      time.Time // The time of the last modification to the stored procedure.
	SqlMode         string    // The SQL_MODE when this procedure was defined.
	SchemaName      string    // The name of the schema that this stored procedure belongs to, for databases that support schemas.
}

StoredProcedureDetails are the details of the stored procedure. Integrators only need to store and retrieve the given details for a stored procedure, as the engine handles all parsing and processing.

type StringType

type StringType interface {
	Type
	CharacterSet() CharacterSetID
	Collation() CollationID
	// MaxCharacterLength returns the maximum number of chars that can safely be stored in this type, based on
	// the current character set.
	MaxCharacterLength() int64
	// MaxByteLength returns the maximum number of bytes that may be consumed by a value stored in this type.
	MaxByteLength() int64
	// Length returns the maximum length, in characters, allowed for this string type.
	Length() int64
}

StringType represents all string types, including VARCHAR and BLOB. https://dev.mysql.com/doc/refman/8.0/en/char.html https://dev.mysql.com/doc/refman/8.0/en/binary-varbinary.html https://dev.mysql.com/doc/refman/8.0/en/blob.html The type of the returned value is string.

type SystemVarValue added in v0.15.0

type SystemVarValue struct {
	Var SystemVariable
	Val interface{}
}

type SystemVariable added in v0.10.0

type SystemVariable interface {
	// GetName returns the name of the sv. Case-sensitive.
	GetName() string
	// GetType returns the type of the sv.
	GetType() Type
	// GetSessionScope returns SESSION scope of the sv.
	GetSessionScope() SystemVariableScope
	// SetDefault sets the default value of the sv.
	SetDefault(any)
	// GetDefault returns the defined default value of the sv.
	// This is used for resetting some variables to initial default/reset value.
	GetDefault() any
	// InitValue sets value without validation.
	// This is used for setting the initial values internally
	// using pre-defined variables or for test-purposes.
	InitValue(val any, global bool) (SystemVarValue, error)
	// SetValue sets the value of the sv of given scope, global or session
	// It validates setting value of correct scope,
	// converts the given value to appropriate value depending on the sv
	// and it returns the SystemVarValue with the updated value.
	SetValue(val any, global bool) (SystemVarValue, error)
	// IsReadOnly checks whether the variable is read only.
	// It returns false if variable can be set to a value.
	IsReadOnly() bool
	// IsGlobalOnly checks whether the scope of the variable is global only.
	IsGlobalOnly() bool
	// DisplayString gets 'specified scope' prefix and
	// returns the name with the prefix, if applicable.
	DisplayString(string) string
}

SystemVariable is used to system variables.

type SystemVariableRegistry added in v0.15.0

type SystemVariableRegistry interface {
	// AddSystemVariables adds the given system variables to this registry
	AddSystemVariables(sysVars []SystemVariable)
	// AssignValues assigns the given values to the system variables in this registry
	AssignValues(vals map[string]interface{}) error
	// NewSessionMap returns a map of system variables values that can be used by a session
	NewSessionMap() map[string]SystemVarValue
	// GetGlobal returns the current global value of the system variable with the given name
	GetGlobal(name string) (SystemVariable, interface{}, bool)
	// SetGlobal sets the global value of the system variable with the given name
	SetGlobal(name string, val interface{}) error
	// GetAllGlobalVariables returns a copy of all global variable values.
	GetAllGlobalVariables() map[string]interface{}
}

SystemVariableRegistry is a registry of system variables. Each session gets its own copy of all values via the SessionMap() method.

var SystemVariables SystemVariableRegistry

type SystemVariableScope added in v0.10.0

type SystemVariableScope interface {
	// SetValue sets an appropriate value to the given SV name depending on the scope.
	SetValue(*Context, string, any) error
	// GetValue returns appropriate value of the given SV name depending on the scope.
	GetValue(*Context, string, CollationID) (any, error)
	// IsGlobalOnly returns true if SV is of SystemVariableScope_Global scope.
	IsGlobalOnly() bool
	// IsSessionOnly returns true if SV is of SystemVariableScope_Session scope.
	IsSessionOnly() bool
}

SystemVariableScope represents the scope of a system variable and handles SV values depending on its scope.

type SystemVariableType added in v0.10.0

type SystemVariableType interface {
	Type
	// EncodeValue returns the given value as a string for storage.
	EncodeValue(interface{}) (string, error)
	// DecodeValue returns the original value given to EncodeValue from the given string. This is different from `Convert`,
	// as the encoded value may technically be an "illegal" value according to the type rules.
	DecodeValue(string) (interface{}, error)
	// UnderlyingType returns the underlying type that this system variable type is based on.
	UnderlyingType() Type
}

SystemVariableType represents a SQL type specifically (and only) used in system variables. Assigning any non-system variables a SystemVariableType will cause errors.

type Table

type Table interface {
	Nameable
	fmt.Stringer
	// Schema returns the table's schema.
	Schema() Schema
	// Collation returns the table's collation.
	Collation() CollationID
	// Partitions returns the table's partitions in an iterator.
	Partitions(*Context) (PartitionIter, error)
	// PartitionRows returns the rows in the given partition, which was returned by Partitions.
	PartitionRows(*Context, Partition) (RowIter, error)
}

Table is a SQL table.

func GetTableInsensitive

func GetTableInsensitive(tblName string, tables map[string]Table) (Table, bool)

GetTableInsensitive implements a case-insensitive map lookup for tables keyed off of the table name. Looks for exact matches first. If no exact matches are found then any table matching the name case insensitively should be returned. If there is more than one table that matches a case-insensitive comparison the resolution strategy is not defined.

func GetUnderlyingTable added in v0.19.0

func GetUnderlyingTable(t Table) Table

type TableCopierDatabase added in v0.11.0

type TableCopierDatabase interface {
	// CopyTableData copies the sourceTable data to the destinationTable and returns the number of rows copied.
	CopyTableData(ctx *Context, sourceTable string, destinationTable string) (uint64, error)
}

TableCopierDatabase is a database that can copy a source table's data (without preserving indexed, fks, etc.) into another destination table.

type TableCreator

type TableCreator interface {
	Database
	// CreateTable creates the table with the given name, schema, collation, and comment. Integrators are
	// responsible for persisting all provided table metadata. Comment may be optionally persisted, and if
	// so, sql.Table implementations should also implement sql.CommentedTable so that the comment may be
	// retrieved.
	CreateTable(ctx *Context, name string, schema PrimaryKeySchema, collation CollationID, comment string) error
}

TableCreator is a Database that can create new tables.

type TableDropper

type TableDropper interface {
	Database
	DropTable(ctx *Context, name string) error
}

TableDropper is a Datagbase that can drop tables.

type TableEditor added in v0.10.0

type TableEditor interface {
	RowReplacer
	RowUpdater
}

TableEditor is the combination of interfaces that allow any table edit operation: i.e. INSERT, UPDATE, DELETE, REPLACE

type TableFunction added in v0.12.0

type TableFunction interface {
	Node
	Expressioner
	Databaser
	Nameable

	// NewInstance calls the table function with the arguments provided, producing a Node
	NewInstance(ctx *Context, db Database, args []Expression) (Node, error)
}

TableFunction is a node that is generated by a function and can be used as a table factor in many SQL queries.

type TableFunctionProvider added in v0.12.0

type TableFunctionProvider interface {
	// TableFunction returns the table function with the name provided, case-insensitive.
	// It also returns boolean param for whether the table function was found.
	TableFunction(ctx *Context, name string) (TableFunction, bool)
	// WithTableFunctions returns a new provider with (only) the list of table functions arguments
	WithTableFunctions(fns ...TableFunction) (TableFunctionProvider, error)
}

TableFunctionProvider is an interface that allows custom table functions to be provided. It's usually (but not always) implemented by a DatabaseProvider.

type TableId added in v0.18.0

type TableId uint16

TableId is the unique identifier of a table or table alias in a multi-db environment. The long-term goal is to migrate all uses of table name strings to this and minimize places where we construct/inspect TableIDs. By treating this as an opaque identifier, it will be easier to migrate to a system where we compute IDs once during plan building. For aliases, DatabaseName is nil.

func (TableId) IsEmpty added in v0.18.0

func (i TableId) IsEmpty() bool

type TableNode added in v0.17.0

type TableNode interface {
	Table
	Node
	CollationCoercible
	Databaser
	// UnderlyingTable returns the table that this node is wrapping, recursively unwrapping any further layers of
	// wrapping to get to the base sql.Table.
	UnderlyingTable() Table
}

TableNode is an interface for nodes that are also tables. A node that implements this interface exposes all the information needed for filters on the table to be optimized into indexes. This is possible when the return value of `UnderlyingTable` is a table that implements `sql.IndexAddressable` For an example of how to use this interface to optimize a system table or table function, see memory.IntSequenceTable

type TableProgress

type TableProgress struct {
	Progress
	PartitionsProgress map[string]PartitionProgress
}

TableProgress keeps track of a table progress, and for each of its partitions

func NewTableProgress

func NewTableProgress(name string, total int64) TableProgress

func (TableProgress) String

func (p TableProgress) String() string

type TableRenamer

type TableRenamer interface {
	Database
	// RenameTable renames a table from oldName to newName as given.
	RenameTable(ctx *Context, oldName, newName string) error
}

TableRenamer is a database that can rename tables.

type TableRowIter

type TableRowIter struct {
	// contains filtered or unexported fields
}

TableRowIter is an iterator over the partitions in a table.

func NewTableRowIter

func NewTableRowIter(ctx *Context, table Table, partitions PartitionIter) *TableRowIter

NewTableRowIter returns a new iterator over the rows in the partitions of the table given.

func (*TableRowIter) Close

func (i *TableRowIter) Close(ctx *Context) error

func (*TableRowIter) Next

func (i *TableRowIter) Next(ctx *Context) (Row, error)

type TableWrapper

type TableWrapper interface {
	// Underlying returns the underlying table.
	Underlying() Table
}

TableWrapper is a node that wraps the real table. This is needed because wrappers cannot implement some methods the table may implement. This interface is used in analysis and planning and is not expected to be implemented by integrators.

type Tableable

type Tableable interface {
	// Table returns the table name.
	Table() string
}

Tableable is something that has a table.

type TemporaryTable added in v0.11.0

type TemporaryTable interface {
	// IsTemporary should return true if the table is temporary to the session
	IsTemporary() bool
}

TemporaryTable allows tables to declare that they are temporary (created by CREATE TEMPORARY TABLE). Only used for validation of certain DDL operations -- in almost all respects TemporaryTables are indistinguishable from persisted tables to the engine.

type TemporaryTableCreator added in v0.11.0

type TemporaryTableCreator interface {
	Database
	// CreateTemporaryTable creates the table with the given name and schema. If a temporary table with that name already exists, must
	// return sql.ErrTableAlreadyExists
	CreateTemporaryTable(ctx *Context, name string, schema PrimaryKeySchema, collation CollationID) error
}

TemporaryTableCreator is a database that can create temporary tables that persist only as long as the session. Note that temporary tables with the same name as persisted tables take precedence in most SQL operations.

type TemporaryTableDatabase added in v0.11.0

type TemporaryTableDatabase interface {
	// GetAllTemporaryTables returns the names of all temporary tables in the session.
	GetAllTemporaryTables(ctx *Context) ([]Table, error)
}

TemporaryTableDatabase is a database that can query the session (which manages the temporary table state) to retrieve the name of all temporary tables.

type Transaction added in v0.10.0

type Transaction interface {
	fmt.Stringer
	IsReadOnly() bool
}

Transaction is an opaque type implemented by an integrator to record necessary information at the start of a transaction. Active transactions will be recorded in the session.

type TransactionCharacteristic added in v0.11.0

type TransactionCharacteristic int
const (
	ReadWrite TransactionCharacteristic = iota
	ReadOnly
)

type TransactionSession added in v0.15.0

type TransactionSession interface {
	Session
	// StartTransaction starts a new transaction and returns it
	StartTransaction(ctx *Context, tCharacteristic TransactionCharacteristic) (Transaction, error)
	// CommitTransaction commits the transaction given
	CommitTransaction(ctx *Context, tx Transaction) error
	// Rollback restores the database to the state recorded in the transaction given
	Rollback(ctx *Context, transaction Transaction) error
	// CreateSavepoint records a savepoint for the transaction given with the name given. If the name is already in use
	// for this transaction, the new savepoint replaces the old one.
	CreateSavepoint(ctx *Context, transaction Transaction, name string) error
	// RollbackToSavepoint restores the database to the state named by the savepoint
	RollbackToSavepoint(ctx *Context, transaction Transaction, name string) error
	// ReleaseSavepoint removes the savepoint named from the transaction given
	ReleaseSavepoint(ctx *Context, transaction Transaction, name string) error
}

TransactionSession can BEGIN, ROLLBACK and COMMIT transactions, as well as create SAVEPOINTS and restore to them. Transactions can span multiple databases, and integrators must do their own error handling to prevent this if they cannot support multiple databases in a single transaction. Such integrators can use Session.GetTransactionDatabase to determine the database that was considered in scope when a transaction began.

type TreePrinter

type TreePrinter struct {
	// contains filtered or unexported fields
}

TreePrinter is a printer for tree nodes.

func NewTreePrinter

func NewTreePrinter() *TreePrinter

NewTreePrinter creates a new tree printer.

func (*TreePrinter) String

func (p *TreePrinter) String() string

String returns the output of the printed tree.

func (*TreePrinter) WriteChildren

func (p *TreePrinter) WriteChildren(children ...string) error

WriteChildren writes a children of the tree.

func (*TreePrinter) WriteNode

func (p *TreePrinter) WriteNode(format string, args ...interface{}) error

WriteNode writes the main node.

type TriggerDatabase

type TriggerDatabase interface {
	Database
	// GetTriggers returns all trigger definitions for the database
	GetTriggers(ctx *Context) ([]TriggerDefinition, error)
	// CreateTrigger is called when an integrator is asked to create a trigger. The CREATE TRIGGER statement string is
	// provided to store, along with the name of the trigger.
	CreateTrigger(ctx *Context, definition TriggerDefinition) error
	// DropTrigger is called when a trigger should no longer be stored. The name has already been validated.
	// Returns ErrTriggerDoesNotExist if the trigger was not found.
	DropTrigger(ctx *Context, name string) error
}

TriggerDatabase is a Database that supports creating and storing triggers. The engine handles all parsing and execution logic for triggers. Integrators are not expected to parse or understand the trigger definitions, but must store and return them when asked.

type TriggerDefinition

type TriggerDefinition struct {
	// The name of this trigger. Trigger names in a database are unique.
	Name string
	// The text of the statement to create this trigger.
	CreateStatement string
	// The time that the trigger was created.
	CreatedAt time.Time
	// SqlMode holds the SQL_MODE that was in use when this trigger was originally defined. It contains information
	// needed for how to parse the trigger's SQL, such as whether ANSI_QUOTES mode is enabled.
	SqlMode string
	// SchemaName is the name of the schema of the trigger, for databases that support schemas.
	SchemaName string
}

TriggerDefinition defines a trigger. Integrators are not expected to parse or understand the trigger definitions, but must store and return them when asked.

type TruncateableTable

type TruncateableTable interface {
	Table
	// Truncate removes all rows from the table. If the table also implements DeletableTable and it is determined that
	// truncate would be equivalent to a DELETE which spans the entire table, then this function will be called instead.
	// Returns the number of rows that were removed.
	Truncate(*Context) (int, error)
}

TruncateableTable is a table that can process the deletion of all rows either via a TRUNCATE TABLE statement or a DELETE statement without a WHERE clause. This is usually much faster that deleting rows one at a time.

type Type

type Type interface {
	CollationCoercible
	// Compare returns an integer comparing two values.
	// The result will be 0 if a==b, -1 if a < b, and +1 if a > b.
	Compare(interface{}, interface{}) (int, error)
	// Convert a value of a compatible type to a most accurate type, returning
	// the new value, whether the value in range, or an error. If |inRange| is
	// false, the value was coerced according to MySQL's rules.
	Convert(interface{}) (interface{}, ConvertInRange, error)
	// Equals returns whether the given type is equivalent to the calling type. All parameters are included in the
	// comparison, so ENUM("a", "b") is not equivalent to ENUM("a", "b", "c").
	Equals(otherType Type) bool
	// MaxTextResponseByteLength returns the maximum number of bytes needed to serialize an instance of this type
	// as a string in a response over the wire for MySQL's text protocol – in other words, this is the maximum bytes
	// needed to serialize any value of this type as human-readable text, NOT in a more compact, binary representation.
	MaxTextResponseByteLength(ctx *Context) uint32
	// Promote will promote the current type to the largest representing type of the same kind, such as Int8 to Int64.
	Promote() Type
	// SQL returns the sqltypes.Value for the given value.
	// Implementations can optionally use |dest| to append
	// serialized data, but should not mutate existing data.
	SQL(ctx *Context, dest []byte, v interface{}) (sqltypes.Value, error)
	// Type returns the query.Type for the given Type.
	Type() query.Type
	// ValueType returns the Go type of the value returned by Convert().
	ValueType() reflect.Type
	// Zero returns the golang zero value for this type
	Zero() interface{}
	fmt.Stringer
}

Type represents a SQL type.

func GetColExprTypes added in v0.12.0

func GetColExprTypes(ranges []MySQLRange) []Type

GetColExprTypes returns a list of MySQLRangeColumnExpr type fields, defaulting to Null types if all columns expressions are Null.

type Type2 added in v0.12.0

type Type2 interface {
	Type

	// Compare2 returns an integer comparing two Values.
	Compare2(Value, Value) (int, error)
	// Convert2 converts a value of a compatible type.
	Convert2(Value) (Value, error)
	// Zero2 returns the zero Value for this type.
	Zero2() Value
	// SQL2 returns the sqltypes.Value for the given value
	SQL2(Value) (sqltypes.Value, error)
}

type TypeWithCollation added in v0.14.0

type TypeWithCollation interface {
	// Collation returns the collation belonging to this type.
	Collation() CollationID
	// WithNewCollation returns a replica of this type, except with the given collation replacing the existing collation.
	WithNewCollation(collation CollationID) (Type, error)
	// StringWithTableCollation converts this type to a string, however it uses the given table collation to determine
	// whether to include the character set and/or collation information.
	StringWithTableCollation(tableCollation CollationID) string
}

TypeWithCollation is implemented on all types that may return a collation.

type TypedValue

type TypedValue struct {
	Typ   Type
	Value interface{}
}

TypedValue is a value along with its type.

type UnaryNode added in v0.12.0

type UnaryNode interface {
	Child() Node
}

UnaryNode is a Node with one child.

type UniqueKeyError added in v0.10.0

type UniqueKeyError struct {
	IsPK     bool
	Existing Row
	// contains filtered or unexported fields
}

func (UniqueKeyError) Error added in v0.10.0

func (ue UniqueKeyError) Error() string

type UnresolvedColumnDefault added in v0.12.0

type UnresolvedColumnDefault struct {
	ExprString string
}

func (UnresolvedColumnDefault) Children added in v0.12.0

func (u UnresolvedColumnDefault) Children() []Expression

func (UnresolvedColumnDefault) CollationCoercibility added in v0.15.0

func (UnresolvedColumnDefault) CollationCoercibility(ctx *Context) (collation CollationID, coercibility byte)

CollationCoercibility implements the interface sql.CollationCoercible.

func (UnresolvedColumnDefault) Eval added in v0.12.0

func (u UnresolvedColumnDefault) Eval(ctx *Context, row Row) (interface{}, error)

func (UnresolvedColumnDefault) IsNullable added in v0.12.0

func (u UnresolvedColumnDefault) IsNullable() bool

func (UnresolvedColumnDefault) Resolved added in v0.12.0

func (u UnresolvedColumnDefault) Resolved() bool

func (UnresolvedColumnDefault) String added in v0.12.0

func (u UnresolvedColumnDefault) String() string

func (UnresolvedColumnDefault) Type added in v0.12.0

func (u UnresolvedColumnDefault) Type() Type

func (UnresolvedColumnDefault) WithChildren added in v0.12.0

func (u UnresolvedColumnDefault) WithChildren(children ...Expression) (Expression, error)

type UnresolvedDatabase

type UnresolvedDatabase string

UnresolvedDatabase is a database which has not been resolved yet.

func (UnresolvedDatabase) GetTableInsensitive

func (UnresolvedDatabase) GetTableInsensitive(ctx *Context, tblName string) (Table, bool, error)

func (UnresolvedDatabase) GetTableNames

func (UnresolvedDatabase) GetTableNames(ctx *Context) ([]string, error)

func (UnresolvedDatabase) Name

func (d UnresolvedDatabase) Name() string

Name returns the database name.

func (UnresolvedDatabase) Tables

func (UnresolvedDatabase) Tables() map[string]Table

Tables returns the tables in the database.

type UnresolvedTable added in v0.12.0

type UnresolvedTable interface {
	Nameable
	// Database returns the database, which may be unresolved
	Database() Database
	// WithAsOf returns a copy of this versioned table with its AsOf
	// field set to the given value. Analogous to WithChildren.
	WithAsOf(asOf Expression) (Node, error)
	// AsOf returns this table's asof expression.
	AsOf() Expression
}

UnresolvedTable is a Table that is either unresolved or deferred for until an asOf resolution. Used by the analyzer during planning, and is not expected to be implemented by integrators.

type UnsupportedFunctionStub added in v0.12.0

type UnsupportedFunctionStub interface {
	IsUnsupported() bool
}

UnsupportedFunctionStub is a marker interface for function stubs that are unsupported

type UpdatableTable

type UpdatableTable interface {
	Table
	// Updater returns a RowUpdater for this table. The RowUpdater will have Update called once for each row to be
	// updated, followed by a call to Close() when all rows have been processed.
	Updater(ctx *Context) RowUpdater
}

UpdatableTable is a table that can process updates of existing rows via update statements.

type UserVars added in v0.15.0

type UserVars struct {
	// contains filtered or unexported fields
}

func (*UserVars) GetUserVariable added in v0.15.0

func (u *UserVars) GetUserVariable(ctx *Context, varName string) (Type, interface{}, error)

GetUserVariable implements the Session interface.

func (*UserVars) SetUserVariable added in v0.15.0

func (u *UserVars) SetUserVariable(ctx *Context, varName string, value interface{}, typ Type) error

type Value added in v0.12.0

type Value struct {
	Typ querypb.Type
	Val ValueBytes
}

Value is a logical index into a Row2. For efficiency reasons, use sparingly.

func ConvertToValue added in v0.12.0

func ConvertToValue(v interface{}) (Value, error)

ConvertToValue converts the interface to a sql value.

func MustConvertToValue added in v0.17.0

func MustConvertToValue(v interface{}) Value

func (Value) IsNull added in v0.12.0

func (v Value) IsNull() bool

IsNull returns whether this value represents NULL

type ValueBytes added in v0.12.0

type ValueBytes []byte

type VersionedDatabase

type VersionedDatabase interface {
	Database
	// GetTableInsensitiveAsOf retrieves a table by its case-insensitive name with the same semantics as
	// Database.GetTableInsensitive, but at a particular revision of the database. Implementors must choose which types
	// of expressions to accept as revision names.
	GetTableInsensitiveAsOf(ctx *Context, tblName string, asOf interface{}) (Table, bool, error)
	// GetTableNamesAsOf returns the table names of every table in the database as of the revision given. Implementors
	// must choose which types of expressions to accept as revision names.
	GetTableNamesAsOf(ctx *Context, asOf interface{}) ([]string, error)
}

VersionedDatabase is a Database that can return tables as they existed at different points in time. The engine supports queries on historical table data via the AS OF construct introduced in SQL 2011.

type View

type View struct {
	// contains filtered or unexported fields
}

View is the parsed version of ViewDefinition Not meant to be used externally

func NewView

func NewView(name string, definition Node, textDefinition, createViewStmt string) *View

NewView creates a View with the specified name and definition.

func (*View) CreateStatement added in v0.15.0

func (v *View) CreateStatement() string

CreateStatement returns the text create view statement of the view as originally defined.

func (*View) Definition

func (v *View) Definition() Node

Definition returns the definition of the view.

func (*View) Name

func (v *View) Name() string

Name returns the name of the view.

func (*View) TextDefinition

func (v *View) TextDefinition() string

TextDefinition returns the text definition of the view as originally defined.

func (*View) WithDefinition added in v0.17.0

func (v *View) WithDefinition(def Node) *View

WithDefinition returns a new view with the updated definition

type ViewDatabase added in v0.11.0

type ViewDatabase interface {
	// CreateView persists the definition a view with the name and select statement given. If a view with that name
	// already exists, should return ErrExistingView
	CreateView(ctx *Context, name string, selectStatement, createViewStmt string) error

	// DropView deletes the view named from persistent storage. If the view doesn't exist, should return
	// ErrViewDoesNotExist
	DropView(ctx *Context, name string) error

	// GetViewDefinition returns the ViewDefinition of the view with the name given, or false if it doesn't exist.
	GetViewDefinition(ctx *Context, viewName string) (ViewDefinition, bool, error)

	// AllViews returns the definitions of all views in the database
	AllViews(ctx *Context) ([]ViewDefinition, error)
}

ViewDatabase is implemented by databases that persist view definitions

type ViewDefinition added in v0.11.0

type ViewDefinition struct {
	Name                string
	TextDefinition      string
	CreateViewStatement string
	SqlMode             string
	// SchemaName is the name of the schema of the view, for databases that support schemas.
	SchemaName string
}

ViewDefinition is the named textual definition of a view

type ViewKey

type ViewKey struct {
	// contains filtered or unexported fields
}

ViewKey is the key used to store view definitions

func NewViewKey

func NewViewKey(databaseName, viewName string) ViewKey

NewViewKey creates a ViewKey ensuring both names are lowercase.

type ViewRegistry

type ViewRegistry struct {
	// contains filtered or unexported fields
}

ViewRegistry stores session-local views for databases that don't implement view storage. Each session gets a new view registry by default. Integrators that want views to persist across sessions should either implement sql.ViewDatabase, or construct their sessions to reuse the same ViewRegistry for each session.

func NewViewRegistry

func NewViewRegistry() *ViewRegistry

NewViewRegistry creates an empty ViewRegistry.

func (*ViewRegistry) Delete

func (r *ViewRegistry) Delete(databaseName, viewName string) error

Delete deletes the view specified by the pair {databaseName, viewName}, returning an error if it does not exist.

func (*ViewRegistry) Exists

func (r *ViewRegistry) Exists(databaseName, viewName string) bool

Exists returns whether the specified key is already registered

func (*ViewRegistry) Register

func (r *ViewRegistry) Register(database string, view *View) error

Register adds the view specified by the pair {database, view.Name()}, returning an error if there is already an element with that key.

func (*ViewRegistry) View

func (r *ViewRegistry) View(databaseName, viewName string) (*View, bool)

View returns a pointer to the view specified by the pair {databaseName, viewName}, returning an error if it does not exist.

func (*ViewRegistry) ViewsInDatabase

func (r *ViewRegistry) ViewsInDatabase(databaseName string) (views []*View)

ViewsInDatabase returns an array of all the views registered under the specified database.

type Visitor

type Visitor interface {
	// Visit method is invoked for each expr encountered by Walk.
	// If the result Visitor is not nil, Walk visits each of the children
	// of the expr with that visitor, followed by a call of Visit(nil)
	// to the returned visitor.
	Visit(expr Expression) Visitor
}

Visitor visits expressions in an expression tree.

type Warning

type Warning struct {
	Level   string
	Message string
	Code    int
}

Warning stands for mySQL warning record.

type WindowAdaptableExpression added in v0.12.0

type WindowAdaptableExpression interface {
	Expression
	IdExpression

	// NewEvalable constructs an executable aggregation WindowFunction
	NewWindowFunction() (WindowFunction, error)
	// WithWindow returns a version of this aggregation with the WindowDefinition given
	WithWindow(window *WindowDefinition) WindowAdaptableExpression
	// Window returns this expression's window
	Window() *WindowDefinition
}

WindowAdaptableExpression is an Expression that can be executed as a window aggregation

type WindowAggregation added in v0.9.0

type WindowAggregation interface {
	WindowAdaptableExpression
}

WindowAggregation implements a window aggregation expression. A WindowAggregation is similar to an Aggregation, except that it returns a result row for every input row, as opposed to as single for the entire result set. A WindowAggregation is expected to track its input rows in the order received, and to return the value for the row index given on demand.

type WindowBuffer added in v0.12.0

type WindowBuffer []Row

WindowBuffer is a type alias for a window materialization

type WindowDefinition added in v0.12.0

type WindowDefinition struct {
	PartitionBy []Expression
	OrderBy     SortFields
	Frame       WindowFrame
	Ref         string
	Name        string
	// contains filtered or unexported fields
}

A WindowDefinition specifies the window parameters of a window function

func NewWindowDefinition added in v0.12.0

func NewWindowDefinition(partitionBy []Expression, orderBy SortFields, frame WindowFrame, ref, name string) *WindowDefinition

func (*WindowDefinition) DebugString added in v0.12.0

func (w *WindowDefinition) DebugString() string

func (*WindowDefinition) FromExpressions added in v0.12.0

func (w *WindowDefinition) FromExpressions(children []Expression) (*WindowDefinition, error)

FromExpressions returns copy of this window with the given expressions taken to stand in for the partition and order by fields. An error is returned if the lengths or types of these expressions are incompatible with this window.

func (*WindowDefinition) PartitionId added in v0.12.0

func (w *WindowDefinition) PartitionId() (uint64, error)

func (*WindowDefinition) String added in v0.12.0

func (w *WindowDefinition) String() string

func (*WindowDefinition) ToExpressions added in v0.12.0

func (w *WindowDefinition) ToExpressions() []Expression

ToExpressions converts the PartitionBy and OrderBy expressions to a single slice of expressions suitable for manipulation by analyzer rules.

type WindowFrame added in v0.12.0

type WindowFrame interface {
	fmt.Stringer

	// NewFramer constructs an executable WindowFramer
	NewFramer(*WindowDefinition) (WindowFramer, error)
	// UnboundedFollowing returns whether a frame end is unbounded
	UnboundedFollowing() bool
	// UnboundedPreceding returns whether a frame start is unbounded
	UnboundedPreceding() bool
	// StartCurrentRow returns whether a frame start is CURRENT ROW
	StartCurrentRow() bool
	// EndCurrentRow returns whether a frame end is CURRENT ROW
	EndCurrentRow() bool
	// StartNFollowing returns a frame's start preceding Expression or nil
	StartNPreceding() Expression
	// StartNFollowing returns a frame's start following Expression or nil
	StartNFollowing() Expression
	// EndNPreceding returns whether a frame end preceding Expression or nil
	EndNPreceding() Expression
	// EndNPreceding returns whether a frame end following Expression or nil
	EndNFollowing() Expression
}

WindowFrame describe input bounds for an aggregation function execution. A frame will only have two non-null fields for the start and end bounds. A WindowFrame plan node is associated with an exec WindowFramer.

type WindowFramer added in v0.12.0

type WindowFramer interface {
	// NewFramer is a prototype constructor that create a new Framer with pass-through
	// parent arguments
	NewFramer(WindowInterval) (WindowFramer, error)
	// Next returns the next WindowInterval frame, or an io.EOF error after the last row
	Next(*Context, WindowBuffer) (WindowInterval, error)
	// FirstIdx returns the current frame start index
	FirstIdx() int
	// LastIdx returns the last valid index in the current frame
	LastIdx() int
	// Interval returns the current frame as a WindowInterval
	Interval() (WindowInterval, error)
}

WindowFramer is responsible for tracking window frame indices for partition rows. WindowFramer is aware of the framing strategy (offsets, ranges, etc), and is responsible for returning a WindowInterval for each partition row.

type WindowFunction added in v0.12.0

type WindowFunction interface {
	Disposable

	// StartPartition discards any previous state and initializes the aggregation for a new partition
	StartPartition(*Context, WindowInterval, WindowBuffer) error
	// DefaultFramer returns a new instance of the default WindowFramer for a particular aggregation
	DefaultFramer() WindowFramer
	// NewSlidingFrameInterval is updates the function's internal aggregation state for the next
	// Compute call using three WindowInterval: added, dropped, and current.
	// TODO: implement sliding window interface in aggregation functions and windowBlockIter
	// NewSlidingFrameInterval(added, dropped WindowInterval)
	// Compute returns an aggregation result for a given interval and buffer
	Compute(*Context, WindowInterval, WindowBuffer) interface{}
}

WindowFunction performs aggregations on buffer intervals, optionally maintaining internal state for performance optimizations

type WindowInterval added in v0.12.0

type WindowInterval struct {
	Start, End int
}

WindowInterval is a WindowBuffer index range, where [Start] is inclusive, and [End] is exclusive

type WithDescribeStats added in v0.18.0

type WithDescribeStats interface {
	GetDescribeStatsString(options DescribeOptions) string
	SetDescribeStats(stats DescribeStats)
	// contains filtered or unexported methods
}

type WrappedInsertError added in v0.12.0

type WrappedInsertError struct {
	OffendingRow Row
	Cause        error
}

func NewWrappedInsertError added in v0.12.0

func NewWrappedInsertError(r Row, err error) WrappedInsertError

func (WrappedInsertError) Error added in v0.12.0

func (w WrappedInsertError) Error() string

type WrappedTypeConversionError added in v0.14.0

type WrappedTypeConversionError struct {
	OffendingVal interface{}
	OffendingIdx int
	Err          error
}

func NewWrappedTypeConversionError added in v0.14.0

func NewWrappedTypeConversionError(offendingVal interface{}, idx int, err error) WrappedTypeConversionError

func (WrappedTypeConversionError) Error added in v0.14.0

type YearType

type YearType interface {
	Type
}

YearType represents the YEAR type. https://dev.mysql.com/doc/refman/8.0/en/year.html The type of the returned value is int16.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL