{"modulePath":"github.com/objectundefined/cockroach","version":"v0.0.0-20160624191317-5695764788c5","isLatest":true,"isStandardLibrary":false,"goos":"all","goarch":"all","docs":"# package sql\n\nPackage sql provides the user-facing API for access to a Cockroach datastore. As the name suggests, the API is based around SQL, the same SQL you find in traditional RDMBS systems like Oracle, MySQL or Postgres. The core Cockroach system implements a distributed, transactional, monolithic sorted key-value map. The sql package builds on top of this core system adding parsing, query planning and query execution as well as defining the privilege model.\n\n### Databases and Tables {#hdr-Databases_and_Tables}\n\nThe two primary objects are databases and tables. A database is a namespace which holds a series of tables. Conceptually, a database can be viewed like a directory in a filesystem plus some additional metadata (privileges). A table is like a file on steroids: containing a structured layout of rows and columns along with secondary indexes.\n\nLike a directory, a database has a name and metadata. The metadata is defined by the DatabaseDescriptor:\n\n\tmessage DatabaseDescriptor {\n\t  optional string name;\n\t  optional uint32 id;\n\t  optional PrivilegeDescriptor privileges;\n\t}\n\nSimilarly, tables have a TableDescriptor:\n\n\tmessage TableDescriptor {\n\t  optional string name;\n\t  optional uint32 id;\n\t  repeated ColumnDescriptor columns;\n\t  optional IndexDescriptor primary_index;\n\t  repeated IndexDescriptor indexes;\n\t  optional PrivilegeDescriptor privileges;\n\t}\n\nBoth the database ID and the table ID are allocate from the same \"ID space\" and IDs are never reused.\n\nThe namespace in which databases and tables exist contains only two levels: the root level contains databases and the database level contains tables. The \"system.namespace\" and \"system.descriptor\" tables implement the mapping from database/table name to ID and from ID to descriptor:\n\n\tCREATE TABLE system.namespace (\n\t  \"parentID\" INT,\n\t  \"name\"     CHAR,\n\t  \"id\"       INT,\n\t  PRIMARY KEY (parentID, name)\n\t);\n\n\tCREATE TABLE system.descriptor (\n\t  \"id\"         INT PRIMARY KEY,\n\t  \"descriptor\" BLOB\n\t);\n\nThe reserved ID of 0 is used for the \"root\" of the namespace in which the databases reside. In order to lookup the ID of a database given its name, the system effectively does a query like:\n\n\tSELECT id FROM system.namespace WHERE parentID = 0 AND name = \u003cdatabase-name\u003e\n\nAnd given a database/table ID, the system looks up the descriptor using a query like:\n\n\tSELECT descriptor FROM system.descriptor WHERE id = \u003cID\u003e\n\n### Primary Key Addressing {#hdr-Primary_Key_Addressing}\n\nAll of the SQL data stored in tables is mapped down to keys and values. This mapping is referred to as key addressing. All tables have a primary key, whether explicitly listed in the schema or automatically generated. Note that a primary key is unrelated to the core Cockroach key-value functionality and is instead referring to the primary key for a SQL table.\n\nThe primary key consists of one or more non-NULL columns from the table. For a given row of the table, the columns for the primary key are encoded into a single string using the routines in util/encoding. These routines allow for the encoding of NULL values, integers, floating pointer numbers and strings in such a way that lexicographic ordering of the encoded strings corresponds to the same ordering of the unencoded data. Using \"system.namespace\" as an example, the primary key columns would be encoded as:\n\n\t/parentID/name\n\n\\[Note that \"/\" is being used to disambiguate the components of the key. The actual encodings do not use \"/\"].\n\nBefore being stored in the monolothic key-value space, the encoded primary key columns are prefixed with the table ID and an ID indicating that the key corresponds to the primary index:\n\n\t/TableID/PrimaryIndexID/parentID/name\n\nThe column data associated with a row in a table is stored within the primary index which is the index associated with the primary key. Every column has a unique ID (that is local to the table). The value for a column is stored at the key:\n\n\t/TableID/PrimaryIndexID/parentID/name/ColumnID -\u003e Value\n\nA column containing a NULL value is not stored in the monolithic map. In order to detect rows which only contain NULL values in non-primary key columns, every row has a sentinel key indicating its existence. The sentinel key is simply the primary index key:\n\n\t/TableID/PrimaryIndexID/parentID/name -\u003e NULL\n\nAs an optimization, columns that are part of the primary key are not stored separately as their data can be decoded from the sentinel value.\n\n### Secondary Indexes {#hdr-Secondary_Indexes}\n\nDespite not being a formal part of SQL, secondary indexes are one of its most powerful features. Secondary indexes are a level of indirection that allow quick lookup of a row using something other than the primary key. As an example, we can imagine creating a secondary index on the \"system.namespace\" table:\n\n\tCREATE INDEX name ON system.namespace (name);\n\nThis would create a \"name\" index composed solely of the \"name\" column. The key addressing for this non-unique index looks like:\n\n\t/TableId/SecondaryIndexID/name/parentID -\u003e NULL\n\nNotice that while the index is on \"name\", the key contains both \"name\" and \"parentID\". This is done to ensure that each row for a table has a unique key for the non-unique index. In general, for a non-unique index we encoded the index's columns followed by any primary key columns that have not already been mentioned. This effectively transforms any non-unique index into a unique index.\n\nLet's suppose that we had instead defined the index as:\n\n\tCREATE UNIQUE INDEX name ON system.namespace (name, id);\n\nThe key addressing for a unique index looks like:\n\n\t/TableID/SecondaryID/name/ID -\u003e /parentID\n\nUnique index keys are defined like this so that a conditional put operation can fail if that key already exists for another row, thereby enforcing the uniqueness constraint. The value for a unique index is composed of any primary key columns that are not part of the index (\"parentID\" in this example).\n\n### Query Planning and Execution {#hdr-Query_Planning_and_Execution}\n\nQuery planning is the system which takes a parsed SQL statement (described by an abstract syntax tree) and creates an execution plan which is itself a tree consisting of a set of scan, join, group, sort and projection operations. For the bulk of SQL statements, query planning is straightforward: the complexity lies in SELECT.\n\nAt one end of the performance spectrum, an implementation of SELECT can be straightforward: do a full scan of the (joined) tables in the FROM clause, filter rows based on the WHERE clause, group the resulting rows based on the GROUP BY clause, filter those rows using the HAVING clause, sort using the ORDER BY clause. There are a number of steps, but they all have well defined semantics and are mostly just an exercise in software engineering: retrieve the rows as quickly as possible and then send them through the pipeline of filtering, grouping, filtering and sorting.\n\nAt the other end of the performance spectrum, query planners attempt to take advantage of secondary indexes to limit the data retrieved, make joining of data between two tables easier and faster and to avoid the need to sort data by retrieving it in a sorted or partially sorted form. The details of how we implement this are in flux and will continue to be in flux for the foreseeable future. This section is intended to provide a high-level overview of a few of the techniques involved.\n\nAfter parsing a SELECT query, the query planner performs semantic analysis to verify the queries correctness and to resolve names within the query to actual objects within the system. Let's consider the query:\n\n\tSELECT id FROM system.namespace WHERE parentID = 0 AND name = 'test'\n\nThis query would look up the ID of the database named \"test\". The query planner needs to resolve the \"system.namespace\" qualified name in the FROM clause to the appropriate TableDescriptor. It also needs to resolve the \"id\", \"parentID\" and \"name\" column references to the appropriate column descriptions with the \"system.namespace\" TableDescriptor. Lastly, as part of semantic analysis, the query planner verifies that the expressions in the select targets and the WHERE clause are valid (e.g. the WHERE clause evaluates to a boolean).\n\nFrom that starting point, the query planner then analyzes the GROUP BY and ORDER BY clauses, adding \"hidden\" targets for expressions used in those clauses that are not explicit targets of the query. In our example without a GROUP BY or ORDER BY clause we move straight to the next step: index selection. Index selection is the stage where the query planner selects the best index to scan and selects the start and end keys to use for scanning the index. Depending on the query, the query planner might even select multiple ranges to scan from an index or multiple ranges from different indexes.\n\nHow does the query planner decide which index to use and which range of the index to scan? We currently use a restricted form of value propagation in oder to determine the range of possible values for columns referenced in the WHERE clause. Using this range information, each index is examined to determine if it is a potential candidate and ranked according to its specificity. In addition to ranking indexes by the column value range information, they are ranked by how well they match the sorting required by the ORDER BY clause. Back to the example above, the range information would determine that:\n\n\tparentID \u003e= 0 AND parentID \u003c= 0 AND name \u003e= 'test' and name \u003c= 'test\n\nNotice that each column has a start and end value associated with it. Since there is only a single index on the \"system.namespace\" table, it is always selected. The start key is computed using the range information as:\n\n\t/system.descriptor/primary/0/test\n\nThe end key is computed as:\n\n\t/system.descriptor/primary/0/tesu\n\nThe \"tesu\" suffix is not a typo: the end key is computed as the \"prefix end key\" for the key \"/TableID/PrimaryIndexId/0/test\". This is done by incrementing the final byte of the key such that \"t\" becomes \"u\".\n\nOur example query thus only scans two key-value pairs:\n\n\t/system.descriptor/primary/0/test    -\u003e NULL\n\t/system.descriptor/primary/0/test/id -\u003e \u003cID\u003e\n\n## Constants\n\n```go\nconst ColumnTruncateAndBackfillChunkSize = 600\n```\nColumnTruncateAndBackfillChunkSize is the maximum number of rows of keys processed per chunk during the column truncate or backfill.\n\nTODO(vivek): Run some experiments to set this value to something sensible or adjust it dynamically. Also add in a sleep after every chunk is processed to slow down the backfill and reduce its CPU usage.\n\n```go\nconst IndexBackfillChunkSize = 100\n```\nIndexBackfillChunkSize is the maximum number of rows processed per chunk during the index backfill.\n\nTODO(vivek) Run some experiments to set this value to something sensible or adjust it dynamically. Also add in a sleep after every chunk is processed, to slow down the backfill and not have it interfere with OLTP commands.\n\n## Variables\n\n```go\nvar (\n\t// LeaseDuration is the mean duration a lease will be acquired for. The\n\t// actual duration is jittered in the range\n\t// [0.75,1.25]*LeaseDuration. Exported for testing purposes only.\n\tLeaseDuration = 5 * time.Minute\n\t// MinLeaseDuration is the minimum duration a lease will have remaining upon\n\t// acquisition. Exported for testing purposes only.\n\tMinLeaseDuration = time.Minute\n)\n```\n\n## Functions\n\n```go\nfunc AddEventLogToMetadataSchema(schema *sqlbase.MetadataSchema)\n```\nAddEventLogToMetadataSchema adds the event log table to the supplied MetadataSchema.\n\n```go\nfunc GetTableDesc(cfg config.SystemConfig, id sqlbase.ID) (*sqlbase.TableDescriptor, error)\n```\nGetTableDesc returns the table descriptor for the table with 'id'. Returns nil if the descriptor is not present, or is present but is not a table.\n\n```go\nfunc GetZoneConfig(cfg config.SystemConfig, id uint32) (*config.ZoneConfig, error)\n```\nGetZoneConfig returns the zone config for the object with 'id'.\n\n```go\nfunc TestDisableTableLeases() func()\n```\nTestDisableTableLeases disables table leases and returns a function that can be used to enable it.\n\n## Types\n\n```go\ntype DatabaseAccessor interface {\n\t// contains filtered or unexported methods\n}\n```\nDatabaseAccessor provides helper methods for using SQL database descriptors.\n\n```go\ntype DescriptorAccessor interface {\n\t// contains filtered or unexported methods\n}\n```\nDescriptorAccessor provides helper methods for using descriptors to SQL objects.\n\n```go\ntype EventLogType string\n```\nEventLogType represents an event type that can be recorded in the event log.\n\n```go\nconst (\n\t// EventLogCreateDatabase is recorded when a database is created.\n\tEventLogCreateDatabase EventLogType = \"create_database\"\n\t// EventLogDropDatabase is recorded when a database is dropped.\n\tEventLogDropDatabase EventLogType = \"drop_database\"\n\t// EventLogCreateTable is recorded when a table is created.\n\tEventLogCreateTable EventLogType = \"create_table\"\n\t// EventLogDropTable is recorded when a table is dropped.\n\tEventLogDropTable EventLogType = \"drop_table\"\n\t// EventLogNodeJoin is recorded when a node joins the cluster.\n\tEventLogNodeJoin EventLogType = \"node_join\"\n\t// EventLogNodeRestart is recorded when an existing node rejoins the cluster\n\t// after being offline.\n\tEventLogNodeRestart EventLogType = \"node_restart\"\n)\n```\n\n```go\ntype EventLogger struct {\n\tInternalExecutor\n}\n```\nAn EventLogger exposes methods used to record events to the event table.\n\n```go\nfunc MakeEventLogger(leaseMgr *LeaseManager) EventLogger\n```\nMakeEventLogger constructs a new EventLogger. A LeaseManager is required in order to correctly execute SQL statements.\n\n```go\nfunc (ev EventLogger) InsertEventRecord(txn *client.Txn, eventType EventLogType, targetID, reportingID int32, info interface{}) error\n```\nInsertEventRecord inserts a single event into the event log as part of the provided transaction.\n\n```go\ntype Executor struct {\n\t// contains filtered or unexported fields\n}\n```\nAn Executor executes SQL statements. Executor is thread-safe.\n\n```go\nfunc NewExecutor(ctx ExecutorContext, stopper *stop.Stopper, registry *metric.Registry) *Executor\n```\nNewExecutor creates an Executor and registers a callback on the system config.\n\n```go\nfunc (e *Executor) ExecuteStatements(\n\tctx context.Context, session *Session, stmts string, pinfo *parser.PlaceholderInfo,\n) StatementResults\n```\nExecuteStatements executes the given statement(s) and returns a response.\n\n```go\nfunc (e *Executor) Prepare(\n\tctx context.Context,\n\tquery string,\n\tsession *Session,\n\tpinfo parser.PlaceholderTypes,\n) ([]ResultColumn, error)\n```\nPrepare returns the result types of the given statement. pinfo may contain partial type information for placeholders. Prepare will populate the missing types. The column result types are returned (or nil if there are no results).\n\n```go\nfunc (e *Executor) Registry() *metric.Registry\n```\nRegistry returns a registry with the metrics tracked by this executor, which can be used to access its stats or be added to another registry.\n\n```go\nfunc (e *Executor) SetNodeID(nodeID roachpb.NodeID)\n```\nSetNodeID sets the node ID for the SQL server. This method must be called before actually using the Executor.\n\n```go\ntype ExecutorContext struct {\n\tDB           *client.DB\n\tGossip       *gossip.Gossip\n\tLeaseManager *LeaseManager\n\tClock        *hlc.Clock\n\tDistSQLSrv   *distsql.ServerImpl\n\n\tTestingKnobs *ExecutorTestingKnobs\n}\n```\nAn ExecutorContext encompasses the auxiliary objects and configuration required to create an executor. All fields holding a pointer or an interface are required to create a Executor; the rest will have sane defaults set if omitted.\n\n```go\ntype ExecutorTestingKnobs struct {\n\t// WaitForGossipUpdate causes metadata-mutating operations to wait\n\t// for the new metadata to back-propagate through gossip.\n\tWaitForGossipUpdate bool\n\n\t// CheckStmtStringChange causes Executor.execStmtsInCurrentTxn to verify\n\t// that executed statements are not modified during execution.\n\tCheckStmtStringChange bool\n\n\t// FixTxnPriority causes transaction priority values to be hardcoded (for\n\t// each priority level) to avoid the randomness in the normal generation.\n\tFixTxnPriority bool\n\n\t// SyncSchemaChangersFilter is called before running schema changers\n\t// synchronously (at the end of a txn). The function can be used to clear the\n\t// schema changers (if the test doesn't want them run using the synchronous\n\t// path) or to temporarily block execution.\n\t// Note that this has nothing to do with the async path for running schema\n\t// changers. To block that, see TestDisableAsyncSchemaChangeExec().\n\tSyncSchemaChangersFilter SyncSchemaChangersFilter\n\n\t// SchemaChangersStartBackfillNotification is called before applying the\n\t// backfill for a schema change operation. It returns error to stop the\n\t// backfill and return an error to the caller of the SchemaChanger.exec().\n\tSchemaChangersStartBackfillNotification func() error\n\n\t//SyncSchemaChangersRenameOldNameNotInUseNotification is called during a rename\n\t//schema change, after all leases on the version of the descriptor with the\n\t//old name are gone, and just before the mapping of the old name to the\n\t//descriptor id is about to be deleted.\n\tSyncSchemaChangersRenameOldNameNotInUseNotification func()\n}\n```\nExecutorTestingKnobs is part of the context used to control parts of the system during testing.\n\n```go\nfunc (*ExecutorTestingKnobs) ModuleTestingKnobs()\n```\nModuleTestingKnobs is part of the base.ModuleTestingKnobs interface.\n\n```go\ntype FKCheck int\n```\nFKCheck indicates a kind of FK check (delete, insert, or both).\n\n```go\nconst (\n\t// CheckDeletes checks if rows reference a changed value.\n\tCheckDeletes FKCheck = iota\n\t// CheckInserts checks if a new/changed value references an existing row.\n\tCheckInserts\n\t// CheckUpdates checks all references (CheckDeletes+CheckInserts).\n\tCheckUpdates\n)\n```\n\n```go\ntype InternalExecutor struct {\n\tLeaseManager *LeaseManager\n}\n```\nInternalExecutor can be used internally by cockroach to execute SQL statements without needing to open a SQL connection. InternalExecutor assumes that the caller has access to a cockroach KV client to handle connection and transaction management.\n\n```go\nfunc (ie InternalExecutor) ExecuteStatementInTransaction(\n\ttxn *client.Txn, statement string, qargs ...interface{},\n) (int, error)\n```\nExecuteStatementInTransaction executes the supplied SQL statement as part of the supplied transaction. Statements are currently executed as the root user.\n\n```go\nfunc (ie InternalExecutor) GetTableSpan(user string, txn *client.Txn, dbName, tableName string) (roachpb.Span, error)\n```\nGetTableSpan gets the key span for a SQL table, including any indices.\n\n```go\ntype LeaseManager struct {\n\tLeaseStore\n\t// contains filtered or unexported fields\n}\n```\nLeaseManager manages acquiring and releasing per-table leases. It also handles resolving table names to descriptor IDs. Exported only for testing.\n\n```go\nfunc NewLeaseManager(\n\tnodeID uint32,\n\tdb client.DB,\n\tclock *hlc.Clock,\n\ttestingKnobs LeaseManagerTestingKnobs,\n) *LeaseManager\n```\nNewLeaseManager creates a new LeaseManager. Args:\n\n\ttestingLeasesRefreshedEvent: if not nil, a callback called after the leases\n\tare refreshed as a result of a gossip update.\n\n```go\nfunc (m *LeaseManager) Acquire(\n\ttxn *client.Txn, tableID sqlbase.ID, version sqlbase.DescriptorVersion,\n) (*LeaseState, error)\n```\nAcquire acquires a read lease for the specified table ID. If version is non-zero the lease is grabbed for the specified version. Otherwise it is grabbed for the most recent version of the descriptor that the lease manager knows about. TODO(andrei): move the tests that use this to the sql package and un-export it.\n\n```go\nfunc (m *LeaseManager) AcquireByName(\n\ttxn *client.Txn, dbID sqlbase.ID, tableName string,\n) (*LeaseState, error)\n```\nAcquireByName acquires a read lease for the specified table. The lease is grabbed for the most recent version of the descriptor that the lease manager knows about.\n\n```go\nfunc (m *LeaseManager) RefreshLeases(s *stop.Stopper, db *client.DB, gossip *gossip.Gossip)\n```\nRefreshLeases starts a goroutine that refreshes the lease manager leases for tables received in the latest system configuration via gossip.\n\n```go\nfunc (m *LeaseManager) Release(lease *LeaseState) error\n```\nRelease releases a previously acquired read lease.\n\n```go\ntype LeaseManagerTestingKnobs struct {\n\t// A callback called when a gossip update is received, before the leases are\n\t// refreshed. Careful when using this to block for too long - you can block\n\t// all the gossip users in the system.\n\tGossipUpdateEvent func(config.SystemConfig)\n\t// A callback called after the leases are refreshed as a result of a gossip update.\n\tTestingLeasesRefreshedEvent func(config.SystemConfig)\n\n\tLeaseStoreTestingKnobs LeaseStoreTestingKnobs\n}\n```\nLeaseManagerTestingKnobs contains test knobs.\n\n```go\nfunc (*LeaseManagerTestingKnobs) ModuleTestingKnobs()\n```\nModuleTestingKnobs is part of the base.ModuleTestingKnobs interface.\n\n```go\ntype LeaseState struct {\n\tsqlbase.TableDescriptor\n\t// contains filtered or unexported fields\n}\n```\nLeaseState holds the state for a lease. Exported only for testing.\n\n```go\nfunc (s *LeaseState) Expiration() time.Time\n```\nExpiration returns the expiration time of the lease.\n\n```go\nfunc (s *LeaseState) Refcount() int\n```\nRefcount returns the reference count of the lease.\n\n```go\nfunc (s *LeaseState) String() string\n```\n\n```go\ntype LeaseStore struct {\n\t// contains filtered or unexported fields\n}\n```\nLeaseStore implements the operations for acquiring and releasing leases and publishing a new version of a descriptor. Exported only for testing.\n\n```go\nfunc (s LeaseStore) Acquire(\n\ttxn *client.Txn,\n\ttableID sqlbase.ID,\n\tminVersion sqlbase.DescriptorVersion,\n\tminExpirationTime parser.DTimestamp,\n) (*LeaseState, error)\n```\nAcquire a lease on the most recent version of a table descriptor. If the lease cannot be obtained because the descriptor is in the process of being deleted, the error will be errTableDeleted.\n\n```go\nfunc (s LeaseStore) Publish(\n\ttableID sqlbase.ID, update func(*sqlbase.TableDescriptor) error,\n) (*sqlbase.Descriptor, error)\n```\nPublish updates a table descriptor. It also maintains the invariant that there are at most two versions of the descriptor out in the wild at any time by first waiting for all nodes to be on the current (pre-update) version of the table desc. The update closure is called after the wait, and it provides the new version of the descriptor to be written. In a multi-step schema operation, this update should perform a single step. The closure may be called multiple times if retries occur; make sure it does not have side effects. Returns the updated version of the descriptor.\n\n```go\nfunc (s LeaseStore) Release(lease *LeaseState) error\n```\nRelease a previously acquired table descriptor lease.\n\n```go\ntype LeaseStoreTestingKnobs struct {\n\t// Called after a lease is removed from the store, with any operation error.\n\tLeaseReleasedEvent func(lease *LeaseState, err error)\n}\n```\nLeaseStoreTestingKnobs contains testing knobs.\n\n```go\nfunc (*LeaseStoreTestingKnobs) ModuleTestingKnobs()\n```\nModuleTestingKnobs is part of the base.ModuleTestingKnobs interface.\n\n```go\ntype PreparedPortal struct {\n\tStmt  *PreparedStatement\n\tQargs parser.QueryArguments\n\n\tProtocolMeta interface{} // a field for protocol implementations to hang metadata off of.\n}\n```\nPreparedPortal is a PreparedStatement that has been bound with query arguments.\n\n```go\ntype PreparedPortals struct {\n\t// contains filtered or unexported fields\n}\n```\nPreparedPortals is a mapping of PreparedPortal names to their corresponding PreparedPortals.\n\n```go\nfunc (pp PreparedPortals) Delete(name string) bool\n```\nDelete removes the PreparedPortal with the provided name from the PreparedPortals. The method returns whether a portal with that name was found and removed.\n\n```go\nfunc (pp PreparedPortals) Exists(name string) bool\n```\nExists returns whether a PreparedPortal with the provided name exists.\n\n```go\nfunc (pp PreparedPortals) Get(name string) (*PreparedPortal, bool)\n```\nGet returns the PreparedPortal with the provided name.\n\n```go\nfunc (pp PreparedPortals) New(name string, stmt *PreparedStatement, qargs parser.QueryArguments,\n) *PreparedPortal\n```\nNew creates a new PreparedPortal with the provided name and corresponding PreparedStatement, binding the statement using the given QueryArguments.\n\n```go\ntype PreparedStatement struct {\n\tQuery    string\n\tSQLTypes parser.PlaceholderTypes\n\tColumns  []ResultColumn\n\n\tProtocolMeta interface{} // a field for protocol implementations to hang metadata off of.\n\t// contains filtered or unexported fields\n}\n```\nPreparedStatement is a SQL statement that has been parsed and the types of arguments and results have been determined.\n\n```go\ntype PreparedStatements struct {\n\t// contains filtered or unexported fields\n}\n```\nPreparedStatements is a mapping of PreparedStatement names to their corresponding PreparedStatements.\n\n```go\nfunc (ps PreparedStatements) Delete(name string) bool\n```\nDelete removes the PreparedStatement with the provided name from the PreparedStatements. The method returns whether a statement with that name was found and removed.\n\n```go\nfunc (ps PreparedStatements) DeleteAll()\n```\nDeleteAll removes all PreparedStatements from the PreparedStatements. This will in turn remove all PreparedPortals from the session's PreparedPortals.\n\n```go\nfunc (ps PreparedStatements) Exists(name string) bool\n```\nExists returns whether a PreparedStatement with the provided name exists.\n\n```go\nfunc (ps PreparedStatements) Get(name string) (*PreparedStatement, bool)\n```\nGet returns the PreparedStatement with the provided name.\n\n```go\nfunc (ps PreparedStatements) New(\n\tctx context.Context,\n\te *Executor,\n\tname, query string,\n\tplaceholderHints parser.PlaceholderTypes,\n) (*PreparedStatement, error)\n```\nNew creates a new PreparedStatement with the provided name and corresponding query string, using the given PlaceholderTypes hints to assist in inferring placeholder types.\n\n```go\ntype Result struct {\n\tErr error\n\t// The type of statement that the result is for.\n\tType parser.StatementType\n\t// The tag of the statement that the result is for.\n\tPGTag string\n\t// RowsAffected will be populated if the statement type is \"RowsAffected\".\n\tRowsAffected int\n\t// Columns will be populated if the statement type is \"Rows\". It will contain\n\t// the names and types of the columns returned in the result set in the order\n\t// specified in the SQL statement. The number of columns will equal the number\n\t// of values in each Row.\n\tColumns []ResultColumn\n\t// Rows will be populated if the statement type is \"Rows\". It will contain\n\t// the result set of the result.\n\t// TODO(nvanbenschoten): Can this be streamed from the planNode?\n\tRows []ResultRow\n}\n```\nResult corresponds to the execution of a single SQL statement.\n\n```go\ntype ResultColumn struct {\n\tName string\n\tTyp  parser.Datum\n\t// contains filtered or unexported fields\n}\n```\nResultColumn contains the name and type of a SQL \"cell\".\n\n```go\ntype ResultList []Result\n```\nResultList represents a list of results for a list of SQL statements. There is one result object per SQL statement in the request.\n\n```go\ntype ResultRow struct {\n\tValues []parser.Datum\n}\n```\nResultRow is a collection of values representing a row in a result.\n\n```go\ntype SchemaAccessor interface {\n\t// contains filtered or unexported methods\n}\n```\nSchemaAccessor provides helper methods for using the SQL schema.\n\n```go\ntype SchemaChangeManager struct {\n\t// contains filtered or unexported fields\n}\n```\nSchemaChangeManager processes pending schema changes seen in gossip updates. Most schema changes are executed synchronously by the node that created the schema change. If the node dies while processing the schema change this manager acts as a backup execution mechanism.\n\n```go\nfunc NewSchemaChangeManager(\n\ttestingKnobs *SchemaChangeManagerTestingKnobs,\n\tdb client.DB,\n\tgossip *gossip.Gossip,\n\tleaseMgr *LeaseManager,\n) *SchemaChangeManager\n```\nNewSchemaChangeManager returns a new SchemaChangeManager.\n\n```go\nfunc (s *SchemaChangeManager) Start(stopper *stop.Stopper)\n```\nStart starts a goroutine that runs outstanding schema changes for tables received in the latest system configuration via gossip.\n\n```go\ntype SchemaChangeManagerTestingKnobs struct {\n\t// AsyncSchemaChangersExecNotification is a function called before running\n\t// a schema change asynchronously. Returning an error will prevent the\n\t// asynchronous execution path from running.\n\tAsyncSchemaChangerExecNotification func() error\n\n\t// AsyncSchemaChangerExecQuickly executes queued schema changes as soon as\n\t// possible.\n\tAsyncSchemaChangerExecQuickly bool\n}\n```\nSchemaChangeManagerTestingKnobs for the SchemaChangeManager.\n\n```go\nfunc (*SchemaChangeManagerTestingKnobs) ModuleTestingKnobs()\n```\nModuleTestingKnobs is part of the base.ModuleTestingKnobs interface.\n\n```go\ntype SchemaChanger struct {\n\t// contains filtered or unexported fields\n}\n```\nSchemaChanger is used to change the schema on a table.\n\n```go\nfunc NewSchemaChangerForTesting(\n\ttableID sqlbase.ID,\n\tmutationID sqlbase.MutationID,\n\tnodeID roachpb.NodeID,\n\tdb client.DB,\n\tleaseMgr *LeaseManager,\n) SchemaChanger\n```\nNewSchemaChangerForTesting only for tests.\n\n```go\nfunc (sc *SchemaChanger) AcquireLease() (sqlbase.TableDescriptor_SchemaChangeLease, error)\n```\nAcquireLease acquires a schema change lease on the table if an unexpired lease doesn't exist. It returns the lease.\n\n```go\nfunc (sc *SchemaChanger) ExtendLease(\n\texistingLease sqlbase.TableDescriptor_SchemaChangeLease,\n) (sqlbase.TableDescriptor_SchemaChangeLease, error)\n```\nExtendLease for the current leaser.\n\n```go\nfunc (sc *SchemaChanger) IsDone() (bool, error)\n```\nIsDone returns true if the work scheduled for the schema changer is complete.\n\n```go\nfunc (sc *SchemaChanger) MaybeIncrementVersion() (*sqlbase.Descriptor, error)\n```\nMaybeIncrementVersion increments the version if needed. If the version is to be incremented, it also assures that all nodes are on the current (pre-increment) version of the descriptor. Returns the (potentially updated) descriptor.\n\n```go\nfunc (sc *SchemaChanger) ReleaseLease(lease sqlbase.TableDescriptor_SchemaChangeLease) error\n```\nReleaseLease the table lease if it is the one registered with the table descriptor.\n\n```go\nfunc (sc *SchemaChanger) RunStateMachineBeforeBackfill() error\n```\nRunStateMachineBeforeBackfill moves the state machine forward and wait to ensure that all nodes are seeing the latest version of the table.\n\n```go\ntype Session struct {\n\tDatabase string\n\tUser     string\n\tSyntax   int32\n\n\t// Info about the open transaction (if any).\n\tTxnState txnState\n\n\tPreparedStatements PreparedStatements\n\tPreparedPortals    PreparedPortals\n\n\tLocation              *time.Location\n\tDefaultIsolationLevel enginepb.IsolationType\n\tTrace                 trace.Trace\n\t// contains filtered or unexported fields\n}\n```\nSession contains the state of a SQL client connection. Create instances using NewSession().\n\n```go\nfunc NewSession(args SessionArgs, e *Executor, remote net.Addr) *Session\n```\nNewSession creates and initializes new Session object. remote can be nil.\n\n```go\nfunc (s *Session) Finish()\n```\nFinish releases resources held by the Session.\n\n```go\ntype SessionArgs struct {\n\tDatabase string\n\tUser     string\n}\n```\nSessionArgs contains arguments for creating a new Session with NewSession().\n\n```go\ntype StatementResults struct {\n\tResultList\n\t// Indicates that after parsing, the request contained 0 non-empty statements.\n\tEmpty bool\n}\n```\nStatementResults represents a list of results from running a batch of SQL statements, plus some meta info about the batch.\n\n```go\ntype SyncSchemaChangersFilter func(TestingSchemaChangerCollection)\n```\nSyncSchemaChangersFilter is the type of a hook to be installed through the ExecutorContext for blocking or otherwise manipulating schema changers run through the sync schema changers path.\n\n```go\ntype TablesByID map[sqlbase.ID]*sqlbase.TableDescriptor\n```\nTablesByID maps table IDs to looked up descriptors.\n\n```go\nfunc TablesNeededForFKs(table *sqlbase.TableDescriptor, usage FKCheck) TablesByID\n```\nTablesNeededForFKs calculates the IDs of the additional TableDescriptors that will be needed for FK checking delete and/or insert operations on \\`table\\`.\n\nNB: the returned map's values are \\*not\\* set -- higher level calling code, eg in planner, should fill the map's values by acquiring leases. This function is essentially just returning a slice of IDs, but the empty map can be filled in place and reused, avoiding a second allocation.\n\n```go\ntype TestingSchemaChangerCollection struct {\n\t// contains filtered or unexported fields\n}\n```\nTestingSchemaChangerCollection is an exported (for testing) version of schemaChangerCollection. TODO(andrei): get rid of this type once we can have tests internal to the sql package (as of April 2016 we can't because sql can't import server).\n\n```go\nfunc (tscc TestingSchemaChangerCollection) ClearSchemaChangers()\n```\nClearSchemaChangers clears the schema changers from the collection. If this is called from a SyncSchemaChangersFilter, no schema changer will be run.\n\n```go\ntype TxnStateEnum int\n```\nTxnStateEnum represents the state of a SQL txn.\n\n```go\nconst (\n\t// No txn is in scope. Either there never was one, or it got committed/rolled back.\n\tNoTxn TxnStateEnum = iota\n\t// A txn is in scope.\n\tOpen\n\t// The txn has encoutered a (non-retriable) error.\n\t// Statements will be rejected until a COMMIT/ROLLBACK is seen.\n\tAborted\n\t// The txn has encoutered a retriable error.\n\t// Statements will be rejected until a RESTART_TRANSACTION is seen.\n\tRestartWait\n\t// The KV txn has been committed successfully through a RELEASE.\n\t// Statements are rejected until a COMMIT is seen.\n\tCommitWait\n)\n```\n\n```go\nfunc (i TxnStateEnum) String() string\n```\n\n","path":"github.com/objectundefined/cockroach/sql","name":"sql","synopsis":"Package sql provides the user-facing API for access to a Cockroach datastore.","isRedistributable":true}
