sqlbase

package
v1.0.1 Latest Latest
Warning

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

Go to latest
Published: May 18, 2017 License: Apache-2.0 Imports: 30 Imported by: 0

Documentation

Overview

Package sqlbase is a generated protocol buffer package.

It is generated from these files:

cockroach/pkg/sql/sqlbase/encoded_datum.proto
cockroach/pkg/sql/sqlbase/privilege.proto
cockroach/pkg/sql/sqlbase/structured.proto

It has these top-level messages:

UserPrivileges
PrivilegeDescriptor
ColumnType
ForeignKeyReference
ColumnDescriptor
ColumnFamilyDescriptor
InterleaveDescriptor
IndexDescriptor
DescriptorMutation
TableDescriptor
DatabaseDescriptor
Descriptor

Index

Constants

View Source
const (

	// SizeOfDatum is the memory size of a Datum reference.
	SizeOfDatum = int64(unsafe.Sizeof(parser.Datum(nil)))
	// SizeOfDatums is the memory size of a Datum slice.
	SizeOfDatums = int64(unsafe.Sizeof(parser.Datums(nil)))
)
View Source
const (
	// CheckFKs can be passed to row writers to check fk validity.
	CheckFKs = true
	// SkipFKs can be passed to row writer to skip fk validity checks.
	SkipFKs = false
)
View Source
const (
	// RowUpdaterDefault indicates that a RowUpdater should update everything
	// about a row, including secondary indexes.
	RowUpdaterDefault rowUpdaterType = 0
	// RowUpdaterOnlyColumns indicates that a RowUpdater should only update the
	// columns of a row.
	RowUpdaterOnlyColumns rowUpdaterType = 1
)
View Source
const (
	NamespaceTableSchema = `
CREATE TABLE system.namespace (
  "parentID" INT,
  name       STRING,
  id         INT,
  PRIMARY KEY ("parentID", name)
);`

	DescriptorTableSchema = `
CREATE TABLE system.descriptor (
  id         INT PRIMARY KEY,
  descriptor BYTES
);`

	UsersTableSchema = `
CREATE TABLE system.users (
  username         STRING PRIMARY KEY,
  "hashedPassword" BYTES
);`

	// Zone settings per DB/Table.
	ZonesTableSchema = `
CREATE TABLE system.zones (
  id     INT PRIMARY KEY,
  config BYTES
);`

	SettingsTableSchema = `` /* 254-byte string literal not displayed */

)

These system tables are part of the system config.

View Source
const (
	LeaseTableSchema = `` /* 165-byte string literal not displayed */

	EventLogTableSchema = `` /* 290-byte string literal not displayed */

	// rangelog is currently envisioned as a wide table; many different event
	// types can be recorded to the table.
	RangeEventTableSchema = `` /* 323-byte string literal not displayed */

	UITableSchema = `
CREATE TABLE system.ui (
	key           STRING PRIMARY KEY,
	value         BYTES,
	"lastUpdated" TIMESTAMP NOT NULL
);`

	JobsTableSchema = `` /* 291-byte string literal not displayed */

)

These system tables are not part of the system config.

View Source
const (
	// CodeRangeUnavailable signals that some data from the cluster cannot be
	// accessed (e.g. because all replicas awol).
	// We're using the postgres "Internal Error" error class "XX".
	CodeRangeUnavailable string = "XXC00"
)

Cockroach error extensions:

View Source
const FamilyHeuristicTargetBytes = 256

FamilyHeuristicTargetBytes is the target total byte size of columns that the current heuristic will assign to a family.

View Source
const (
	// PrimaryKeyIndexName is the name of the index for the primary key.
	PrimaryKeyIndexName = "primary"
)

Variables

View Source
var (
	ErrInvalidLengthPrivilege = fmt.Errorf("proto: negative length found during unmarshaling")
	ErrIntOverflowPrivilege   = fmt.Errorf("proto: integer overflow")
)
View Source
var (
	ErrInvalidLengthStructured = fmt.Errorf("proto: negative length found during unmarshaling")
	ErrIntOverflowStructured   = fmt.Errorf("proto: integer overflow")
)
View Source
var (
	// SystemDB is the descriptor for the system database.
	SystemDB = DatabaseDescriptor{
		Name: "system",
		ID:   keys.SystemDatabaseID,

		Privileges: NewPrivilegeDescriptor(security.RootUser,
			SystemDesiredPrivileges(keys.SystemDatabaseID)),
	}

	// NamespaceTable is the descriptor for the namespace table.
	NamespaceTable = TableDescriptor{
		Name:     "namespace",
		ID:       keys.NamespaceTableID,
		ParentID: 1,
		Version:  1,
		Columns: []ColumnDescriptor{
			{Name: "parentID", ID: 1, Type: colTypeInt},
			{Name: "name", ID: 2, Type: colTypeString},
			{Name: "id", ID: 3, Type: colTypeInt, Nullable: true},
		},
		NextColumnID: 4,
		Families: []ColumnFamilyDescriptor{
			{Name: "primary", ID: 0, ColumnNames: []string{"parentID", "name"}, ColumnIDs: []ColumnID{1, 2}},
			{Name: "fam_3_id", ID: 3, ColumnNames: []string{"id"}, ColumnIDs: []ColumnID{3}, DefaultColumnID: 3},
		},
		NextFamilyID: 4,
		PrimaryIndex: IndexDescriptor{
			Name:             "primary",
			ID:               1,
			Unique:           true,
			ColumnNames:      []string{"parentID", "name"},
			ColumnDirections: []IndexDescriptor_Direction{IndexDescriptor_ASC, IndexDescriptor_ASC},
			ColumnIDs:        []ColumnID{1, 2},
		},
		NextIndexID:    2,
		Privileges:     NewPrivilegeDescriptor(security.RootUser, SystemDesiredPrivileges(keys.NamespaceTableID)),
		FormatVersion:  InterleavedFormatVersion,
		NextMutationID: 1,
	}

	// DescriptorTable is the descriptor for the descriptor table.
	DescriptorTable = TableDescriptor{
		Name:       "descriptor",
		ID:         keys.DescriptorTableID,
		Privileges: NewPrivilegeDescriptor(security.RootUser, SystemDesiredPrivileges(keys.DescriptorTableID)),
		ParentID:   1,
		Version:    1,
		Columns: []ColumnDescriptor{
			{Name: "id", ID: 1, Type: colTypeInt},
			{Name: "descriptor", ID: 2, Type: colTypeBytes, Nullable: true},
		},
		NextColumnID: 3,
		Families: []ColumnFamilyDescriptor{
			{Name: "primary", ID: 0, ColumnNames: []string{"id"}, ColumnIDs: singleID1},
			{Name: "fam_2_descriptor", ID: 2, ColumnNames: []string{"descriptor"}, ColumnIDs: []ColumnID{2}, DefaultColumnID: 2},
		},
		PrimaryIndex:   pk("id"),
		NextFamilyID:   3,
		NextIndexID:    2,
		FormatVersion:  InterleavedFormatVersion,
		NextMutationID: 1,
	}

	// UsersTable is the descriptor for the users table.
	UsersTable = TableDescriptor{
		Name:     "users",
		ID:       keys.UsersTableID,
		ParentID: 1,
		Version:  1,
		Columns: []ColumnDescriptor{
			{Name: "username", ID: 1, Type: colTypeString},
			{Name: "hashedPassword", ID: 2, Type: colTypeBytes, Nullable: true},
		},
		NextColumnID: 3,
		Families: []ColumnFamilyDescriptor{
			{Name: "primary", ID: 0, ColumnNames: []string{"username"}, ColumnIDs: singleID1},
			{Name: "fam_2_hashedPassword", ID: 2, ColumnNames: []string{"hashedPassword"}, ColumnIDs: []ColumnID{2}, DefaultColumnID: 2},
		},
		PrimaryIndex:   pk("username"),
		NextFamilyID:   3,
		NextIndexID:    2,
		Privileges:     NewPrivilegeDescriptor(security.RootUser, SystemDesiredPrivileges(keys.UsersTableID)),
		FormatVersion:  InterleavedFormatVersion,
		NextMutationID: 1,
	}

	// ZonesTable is the descriptor for the zones table.
	ZonesTable = TableDescriptor{
		Name:     "zones",
		ID:       keys.ZonesTableID,
		ParentID: 1,
		Version:  1,
		Columns: []ColumnDescriptor{
			{Name: "id", ID: 1, Type: colTypeInt},
			{Name: "config", ID: 2, Type: colTypeBytes, Nullable: true},
		},
		NextColumnID: 3,
		Families: []ColumnFamilyDescriptor{
			{Name: "primary", ID: 0, ColumnNames: []string{"id"}, ColumnIDs: singleID1},
			{Name: "fam_2_config", ID: 2, ColumnNames: []string{"config"}, ColumnIDs: []ColumnID{2}, DefaultColumnID: 2},
		},
		PrimaryIndex:   pk("id"),
		NextFamilyID:   3,
		NextIndexID:    2,
		Privileges:     NewPrivilegeDescriptor(security.RootUser, SystemDesiredPrivileges(keys.ZonesTableID)),
		FormatVersion:  InterleavedFormatVersion,
		NextMutationID: 1,
	}
	// SettingsTable is the descriptor for the jobs table.
	SettingsTable = TableDescriptor{
		Name:     "settings",
		ID:       keys.SettingsTableID,
		ParentID: 1,
		Version:  1,
		Columns: []ColumnDescriptor{
			{Name: "name", ID: 1, Type: colTypeString},
			{Name: "value", ID: 2, Type: colTypeString},
			{Name: "lastUpdated", ID: 3, Type: colTypeTimestamp, DefaultExpr: &nowString},
			{Name: "valueType", ID: 4, Type: colTypeString, Nullable: true},
		},
		NextColumnID: 5,
		Families: []ColumnFamilyDescriptor{
			{
				Name:        "fam_0_name_value_lastUpdated_valueType",
				ID:          0,
				ColumnNames: []string{"name", "value", "lastUpdated", "valueType"},
				ColumnIDs:   []ColumnID{1, 2, 3, 4},
			},
		},
		NextFamilyID:   1,
		PrimaryIndex:   pk("name"),
		NextIndexID:    2,
		Privileges:     NewPrivilegeDescriptor(security.RootUser, SystemDesiredPrivileges(keys.SettingsTableID)),
		FormatVersion:  InterleavedFormatVersion,
		NextMutationID: 1,
	}
)

These system config TableDescriptor literals should match the descriptor that would be produced by evaluating one of the above `CREATE TABLE` statements. See the `TestSystemTableLiterals` which checks that they do indeed match, and has suggestions on writing and maintaining them.

View Source
var (
	// LeaseTable is the descriptor for the leases table.
	LeaseTable = TableDescriptor{
		Name:     "lease",
		ID:       keys.LeaseTableID,
		ParentID: 1,
		Version:  1,
		Columns: []ColumnDescriptor{
			{Name: "descID", ID: 1, Type: colTypeInt},
			{Name: "version", ID: 2, Type: colTypeInt},
			{Name: "nodeID", ID: 3, Type: colTypeInt},
			{Name: "expiration", ID: 4, Type: colTypeTimestamp},
		},
		NextColumnID: 5,
		Families: []ColumnFamilyDescriptor{
			{Name: "primary", ID: 0, ColumnNames: []string{"descID", "version", "nodeID", "expiration"}, ColumnIDs: []ColumnID{1, 2, 3, 4}},
		},
		PrimaryIndex: IndexDescriptor{
			Name:             "primary",
			ID:               1,
			Unique:           true,
			ColumnNames:      []string{"descID", "version", "expiration", "nodeID"},
			ColumnDirections: []IndexDescriptor_Direction{IndexDescriptor_ASC, IndexDescriptor_ASC, IndexDescriptor_ASC, IndexDescriptor_ASC},
			ColumnIDs:        []ColumnID{1, 2, 4, 3},
		},
		NextFamilyID:   1,
		NextIndexID:    2,
		Privileges:     NewPrivilegeDescriptor(security.RootUser, SystemDesiredPrivileges(keys.LeaseTableID)),
		FormatVersion:  InterleavedFormatVersion,
		NextMutationID: 1,
	}

	// EventLogTable is the descriptor for the event log table.
	EventLogTable = TableDescriptor{
		Name:     "eventlog",
		ID:       keys.EventLogTableID,
		ParentID: 1,
		Version:  1,
		Columns: []ColumnDescriptor{
			{Name: "timestamp", ID: 1, Type: colTypeTimestamp},
			{Name: "eventType", ID: 2, Type: colTypeString},
			{Name: "targetID", ID: 3, Type: colTypeInt},
			{Name: "reportingID", ID: 4, Type: colTypeInt},
			{Name: "info", ID: 5, Type: colTypeString, Nullable: true},
			{Name: "uniqueID", ID: 6, Type: colTypeBytes, DefaultExpr: &uuidV4String},
		},
		NextColumnID: 7,
		Families: []ColumnFamilyDescriptor{
			{Name: "primary", ID: 0, ColumnNames: []string{"timestamp", "uniqueID"}, ColumnIDs: []ColumnID{1, 6}},
			{Name: "fam_2_eventType", ID: 2, ColumnNames: []string{"eventType"}, ColumnIDs: []ColumnID{2}, DefaultColumnID: 2},
			{Name: "fam_3_targetID", ID: 3, ColumnNames: []string{"targetID"}, ColumnIDs: []ColumnID{3}, DefaultColumnID: 3},
			{Name: "fam_4_reportingID", ID: 4, ColumnNames: []string{"reportingID"}, ColumnIDs: []ColumnID{4}, DefaultColumnID: 4},
			{Name: "fam_5_info", ID: 5, ColumnNames: []string{"info"}, ColumnIDs: []ColumnID{5}, DefaultColumnID: 5},
		},
		PrimaryIndex: IndexDescriptor{
			Name:             "primary",
			ID:               1,
			Unique:           true,
			ColumnNames:      []string{"timestamp", "uniqueID"},
			ColumnDirections: []IndexDescriptor_Direction{IndexDescriptor_ASC, IndexDescriptor_ASC},
			ColumnIDs:        []ColumnID{1, 6},
		},
		NextFamilyID:   6,
		NextIndexID:    2,
		Privileges:     NewPrivilegeDescriptor(security.RootUser, SystemDesiredPrivileges(keys.EventLogTableID)),
		FormatVersion:  InterleavedFormatVersion,
		NextMutationID: 1,
	}

	// RangeEventTable is the descriptor for the range log table.
	RangeEventTable = TableDescriptor{
		Name:     "rangelog",
		ID:       keys.RangeEventTableID,
		ParentID: 1,
		Version:  1,
		Columns: []ColumnDescriptor{
			{Name: "timestamp", ID: 1, Type: colTypeTimestamp},
			{Name: "rangeID", ID: 2, Type: colTypeInt},
			{Name: "storeID", ID: 3, Type: colTypeInt},
			{Name: "eventType", ID: 4, Type: colTypeString},
			{Name: "otherRangeID", ID: 5, Type: colTypeInt, Nullable: true},
			{Name: "info", ID: 6, Type: colTypeString, Nullable: true},
			{Name: "uniqueID", ID: 7, Type: colTypeInt, DefaultExpr: &uniqueRowIDString},
		},
		NextColumnID: 8,
		Families: []ColumnFamilyDescriptor{
			{Name: "primary", ID: 0, ColumnNames: []string{"timestamp", "uniqueID"}, ColumnIDs: []ColumnID{1, 7}},
			{Name: "fam_2_rangeID", ID: 2, ColumnNames: []string{"rangeID"}, ColumnIDs: []ColumnID{2}, DefaultColumnID: 2},
			{Name: "fam_3_storeID", ID: 3, ColumnNames: []string{"storeID"}, ColumnIDs: []ColumnID{3}, DefaultColumnID: 3},
			{Name: "fam_4_eventType", ID: 4, ColumnNames: []string{"eventType"}, ColumnIDs: []ColumnID{4}, DefaultColumnID: 4},
			{Name: "fam_5_otherRangeID", ID: 5, ColumnNames: []string{"otherRangeID"}, ColumnIDs: []ColumnID{5}, DefaultColumnID: 5},
			{Name: "fam_6_info", ID: 6, ColumnNames: []string{"info"}, ColumnIDs: []ColumnID{6}, DefaultColumnID: 6},
		},
		PrimaryIndex: IndexDescriptor{
			Name:             "primary",
			ID:               1,
			Unique:           true,
			ColumnNames:      []string{"timestamp", "uniqueID"},
			ColumnDirections: []IndexDescriptor_Direction{IndexDescriptor_ASC, IndexDescriptor_ASC},
			ColumnIDs:        []ColumnID{1, 7},
		},
		NextFamilyID:   7,
		NextIndexID:    2,
		Privileges:     NewPrivilegeDescriptor(security.RootUser, SystemDesiredPrivileges(keys.RangeEventTableID)),
		FormatVersion:  InterleavedFormatVersion,
		NextMutationID: 1,
	}

	// UITable is the descriptor for the ui table.
	UITable = TableDescriptor{
		Name:     "ui",
		ID:       keys.UITableID,
		ParentID: 1,
		Version:  1,
		Columns: []ColumnDescriptor{
			{Name: "key", ID: 1, Type: colTypeString},
			{Name: "value", ID: 2, Type: colTypeBytes, Nullable: true},
			{Name: "lastUpdated", ID: 3, Type: ColumnType{Kind: ColumnType_TIMESTAMP}},
		},
		NextColumnID: 4,
		Families: []ColumnFamilyDescriptor{
			{Name: "primary", ID: 0, ColumnNames: []string{"key"}, ColumnIDs: singleID1},
			{Name: "fam_2_value", ID: 2, ColumnNames: []string{"value"}, ColumnIDs: []ColumnID{2}, DefaultColumnID: 2},
			{Name: "fam_3_lastUpdated", ID: 3, ColumnNames: []string{"lastUpdated"}, ColumnIDs: []ColumnID{3}, DefaultColumnID: 3},
		},
		NextFamilyID:   4,
		PrimaryIndex:   pk("key"),
		NextIndexID:    2,
		Privileges:     NewPrivilegeDescriptor(security.RootUser, SystemDesiredPrivileges(keys.UITableID)),
		FormatVersion:  InterleavedFormatVersion,
		NextMutationID: 1,
	}

	// JobsTable is the descriptor for the jobs table.
	JobsTable = TableDescriptor{
		Name:     "jobs",
		ID:       keys.JobsTableID,
		ParentID: 1,
		Version:  1,
		Columns: []ColumnDescriptor{
			{Name: "id", ID: 1, Type: colTypeInt, DefaultExpr: &uniqueRowIDString},
			{Name: "status", ID: 2, Type: colTypeString},
			{Name: "created", ID: 3, Type: colTypeTimestamp, DefaultExpr: &nowString},
			{Name: "payload", ID: 4, Type: colTypeBytes},
		},
		NextColumnID: 5,
		Families: []ColumnFamilyDescriptor{
			{
				Name:        "fam_0_id_status_created_payload",
				ID:          0,
				ColumnNames: []string{"id", "status", "created", "payload"},
				ColumnIDs:   []ColumnID{1, 2, 3, 4},
			},
		},
		NextFamilyID: 1,
		PrimaryIndex: pk("id"),
		Indexes: []IndexDescriptor{
			{
				Name:             "jobs_status_created_idx",
				ID:               2,
				Unique:           false,
				ColumnNames:      []string{"status", "created"},
				ColumnDirections: []IndexDescriptor_Direction{IndexDescriptor_ASC, IndexDescriptor_ASC},
				ColumnIDs:        []ColumnID{2, 3},
				ExtraColumnIDs:   []ColumnID{1},
			},
		},
		NextIndexID:    3,
		Privileges:     NewPrivilegeDescriptor(security.RootUser, SystemDesiredPrivileges(keys.JobsTableID)),
		FormatVersion:  InterleavedFormatVersion,
		NextMutationID: 1,
	}
)

These system TableDescriptor literals should match the descriptor that would be produced by evaluating one of the above `CREATE TABLE` statements for system tables that are not system config tables. See the `TestSystemTableLiterals` which checks that they do indeed match, and has suggestions on writing and maintaining them.

View Source
var ColumnType_Kind_name = map[int32]string{
	0:   "BOOL",
	1:   "INT",
	2:   "FLOAT",
	3:   "DECIMAL",
	4:   "DATE",
	5:   "TIMESTAMP",
	6:   "INTERVAL",
	7:   "STRING",
	8:   "BYTES",
	9:   "TIMESTAMPTZ",
	10:  "COLLATEDSTRING",
	11:  "NAME",
	12:  "OID",
	13:  "NULL",
	100: "INT_ARRAY",
	200: "INT2VECTOR",
}
View Source
var ColumnType_Kind_value = map[string]int32{
	"BOOL":           0,
	"INT":            1,
	"FLOAT":          2,
	"DECIMAL":        3,
	"DATE":           4,
	"TIMESTAMP":      5,
	"INTERVAL":       6,
	"STRING":         7,
	"BYTES":          8,
	"TIMESTAMPTZ":    9,
	"COLLATEDSTRING": 10,
	"NAME":           11,
	"OID":            12,
	"NULL":           13,
	"INT_ARRAY":      100,
	"INT2VECTOR":     200,
}
View Source
var ConstraintValidity_name = map[int32]string{
	0: "Validated",
	1: "Unvalidated",
}
View Source
var ConstraintValidity_value = map[string]int32{
	"Validated":   0,
	"Unvalidated": 1,
}
View Source
var DatumEncoding_name = map[int32]string{
	0: "ASCENDING_KEY",
	1: "DESCENDING_KEY",
	2: "VALUE",
}
View Source
var DatumEncoding_value = map[string]int32{
	"ASCENDING_KEY":  0,
	"DESCENDING_KEY": 1,
	"VALUE":          2,
}
View Source
var DefaultSearchPath = parser.SearchPath{"pg_catalog"}

DefaultSearchPath is the search path used by virgin sessions.

View Source
var DescriptorMutation_Direction_name = map[int32]string{
	0: "NONE",
	1: "ADD",
	2: "DROP",
}
View Source
var DescriptorMutation_Direction_value = map[string]int32{
	"NONE": 0,
	"ADD":  1,
	"DROP": 2,
}
View Source
var DescriptorMutation_State_name = map[int32]string{
	0: "UNKNOWN",
	1: "DELETE_ONLY",
	2: "WRITE_ONLY",
}
View Source
var DescriptorMutation_State_value = map[string]int32{
	"UNKNOWN":     0,
	"DELETE_ONLY": 1,
	"WRITE_ONLY":  2,
}
View Source
var ErrDescriptorNotFound = errors.New("descriptor not found")

ErrDescriptorNotFound is returned by GetTableDescFromID to signal that a descriptor could not be found with the given id.

View Source
var ErrMissingColumns = errors.New("table must contain at least 1 column")

ErrMissingColumns indicates a table with no columns.

View Source
var ErrMissingPrimaryKey = errors.New("table must contain a primary key")

ErrMissingPrimaryKey indicates a table with no primary key.

View Source
var IndexDescriptor_Direction_name = map[int32]string{
	0: "ASC",
	1: "DESC",
}
View Source
var IndexDescriptor_Direction_value = map[string]int32{
	"ASC":  0,
	"DESC": 1,
}

SystemAllowedPrivileges describes the allowable privilege lists for each system object. The root user must have the privileges of exactly one of those privilege lists. No user may have more privileges than the root user.

Some system objects were created with different privileges in previous versions of the system. These privileges are no longer "desired" but must still be "allowed," or this version and the previous version with different privileges will be unable to coexist in the same cluster because one version will think it has invalid table descriptors.

The currently-desired privileges (i.e., the privileges with which the object will be created in fresh clusters) must be listed first in the mapped value, followed by previously-desirable but still allowable privileges in any order.

If we supported backwards-incompatible migrations, pruning allowed privileges would require a two-step migration process. First, a new version that allows both must be deployed to all nodes, after which a a migration to upgrade from the old privileges to the new privileges can be run. Only then can a version that removes the old allowed versions be deployed. TODO(benesch): Once we support backwards-incompatible migrations, prune old allowed privileges.

View Source
var TableDescriptor_State_name = map[int32]string{
	0: "PUBLIC",
	1: "ADD",
	2: "DROP",
}
View Source
var TableDescriptor_State_value = map[string]int32{
	"PUBLIC": 0,
	"ADD":    1,
	"DROP":   2,
}

Functions

func CheckColumnType

func CheckColumnType(col ColumnDescriptor, typ parser.Type, pmap *parser.PlaceholderInfo) error

CheckColumnType verifies that a given value is compatible with the type requested by the column. If the value is a placeholder, the type of the placeholder gets populated.

func CheckValueWidth

func CheckValueWidth(col ColumnDescriptor, val parser.Datum) error

CheckValueWidth checks that the width (for strings, byte arrays, and bit string) and scale (for decimals) of the value fits the specified column type. Used by INSERT and UPDATE.

func ColIDtoRowIndexFromCols

func ColIDtoRowIndexFromCols(cols []ColumnDescriptor) map[ColumnID]int

ColIDtoRowIndexFromCols groups a slice of ColumnDescriptors by their ID field, returning a map from ID to ColumnDescriptor. It assumes there are no duplicate descriptors in the input.

func ColumnsSelectors

func ColumnsSelectors(cols []ColumnDescriptor) parser.SelectExprs

ColumnsSelectors generates Select expressions for cols.

func CompareDatums

func CompareDatums(
	ordering ColumnOrdering, evalCtx *parser.EvalContext, lhs, rhs parser.Datums,
) int

CompareDatums compares two datum rows according to a column ordering. Returns:

  • 0 if lhs and rhs are equal on the ordering columns;
  • less than 0 if lhs comes first;
  • greater than 0 if rhs comes first.

func ConvertBatchError

func ConvertBatchError(tableDesc *TableDescriptor, b *client.Batch) error

ConvertBatchError returns a user friendly constraint violation error.

func DecodeIndexKey

func DecodeIndexKey(
	a *DatumAlloc,
	desc *TableDescriptor,
	indexID IndexID,
	vals []EncDatum,
	colDirs []encoding.Direction,
	key []byte,
) ([]byte, bool, error)

DecodeIndexKey decodes the values that are a part of the specified index key. ValTypes is a slice returned from makeKeyVals. The remaining bytes in the index key are returned which will either be an encoded column ID for the primary key index, the primary key suffix for non-unique secondary indexes or unique secondary indexes containing NULL or empty. If the given descriptor does not match the key, false is returned with no error.

func DecodeKeyVals

func DecodeKeyVals(
	a *DatumAlloc, vals []EncDatum, directions []encoding.Direction, key []byte,
) ([]byte, error)

DecodeKeyVals decodes the values that are part of the key. The decoded values are stored in the vals. If this slice is nil, the direction used will default to encoding.Ascending.

func DecodeTableIDIndexID

func DecodeTableIDIndexID(key []byte) ([]byte, ID, IndexID, error)

DecodeTableIDIndexID decodes a table id followed by an index id.

func DecodeTableKey

func DecodeTableKey(
	a *DatumAlloc, valType parser.Type, key []byte, dir encoding.Direction,
) (parser.Datum, []byte, error)

DecodeTableKey decodes a table key/value.

func DecodeTableValue

func DecodeTableValue(a *DatumAlloc, valType parser.Type, b []byte) (parser.Datum, []byte, error)

DecodeTableValue decodes a value encoded by EncodeTableValue.

func EncDatumRowToDatums

func EncDatumRowToDatums(datums parser.Datums, row EncDatumRow, da *DatumAlloc) error

EncDatumRowToDatums converts a given EncDatumRow to a Datums.

func EncodeColumns

func EncodeColumns(
	columnIDs []ColumnID,
	directions directions,
	colMap map[ColumnID]int,
	values []parser.Datum,
	keyPrefix []byte,
) (key []byte, containsNull bool, err error)

EncodeColumns is a version of EncodePartialIndexKey that takes ColumnIDs and directions explicitly. WARNING: unlike EncodePartialIndexKey, EncodeColumns appends directly to keyPrefix.

func EncodeDatum

func EncodeDatum(b []byte, d parser.Datum) ([]byte, error)

EncodeDatum encodes a datum (order-preserving encoding, suitable for keys).

func EncodeDatums

func EncodeDatums(b []byte, d parser.Datums) ([]byte, error)

EncodeDatums encodes a Datums (order-preserving).

func EncodeIndexKey

func EncodeIndexKey(
	tableDesc *TableDescriptor,
	index *IndexDescriptor,
	colMap map[ColumnID]int,
	values []parser.Datum,
	keyPrefix []byte,
) (key []byte, containsNull bool, err error)

EncodeIndexKey creates a key by concatenating keyPrefix with the encodings of the columns in the index.

If a table or index is interleaved, `encoding.encodedNullDesc` is used in place of the family id (a varint) to signal the next component of the key. An example of one level of interleaving (a parent): /<parent_table_id>/<parent_index_id>/<field_1>/<field_2>/NullDesc/<table_id>/<index_id>/<field_3>/<family>

Returns the key and whether any of the encoded values were NULLs.

Note that ExtraColumnIDs are not encoded, so the result isn't always a full index key.

func EncodePartialIndexKey

func EncodePartialIndexKey(
	tableDesc *TableDescriptor,
	index *IndexDescriptor,
	numCols int,
	colMap map[ColumnID]int,
	values []parser.Datum,
	keyPrefix []byte,
) (key []byte, containsNull bool, err error)

EncodePartialIndexKey encodes a partial index key; only the first numCols of index.ColumnIDs are encoded.

func EncodeSecondaryIndexes

func EncodeSecondaryIndexes(
	tableDesc *TableDescriptor,
	indexes []IndexDescriptor,
	colMap map[ColumnID]int,
	values []parser.Datum,
	secondaryIndexEntries []IndexEntry,
) error

EncodeSecondaryIndexes encodes key/values for the secondary indexes. colMap maps ColumnIDs to indices in `values`. secondaryIndexEntries is the return value (passed as a parameter so the caller can reuse between rows) and is expected to be the same length as indexes.

func EncodeTableKey

func EncodeTableKey(b []byte, val parser.Datum, dir encoding.Direction) ([]byte, error)

EncodeTableKey encodes `val` into `b` and returns the new buffer. The encoded value is guaranteed to be lexicographically sortable, but not guaranteed to be round-trippable during decoding.

func EncodeTableValue

func EncodeTableValue(appendTo []byte, colID ColumnID, val parser.Datum) ([]byte, error)

EncodeTableValue encodes `val` into `appendTo` using DatumEncoding_VALUE and returns the new buffer. The encoded value is guaranteed to round trip and decode exactly to its input, but is not guaranteed to be lexicographically sortable.

func ExtractIndexKey

func ExtractIndexKey(
	a *DatumAlloc, tableDesc *TableDescriptor, entry client.KeyValue,
) (roachpb.Key, error)

ExtractIndexKey constructs the index (primary) key for a row from any index key/value entry, including secondary indexes.

Don't use this function in the scan "hot path".

func FixedOffsetTimeZoneToLocation

func FixedOffsetTimeZoneToLocation(offset int, origRepr string) *time.Location

FixedOffsetTimeZoneToLocation creates a time.Location with a set offset and with a name that can be marshalled by crdb between nodes.

func HasCompositeKeyEncoding

func HasCompositeKeyEncoding(kind ColumnType_Kind) bool

HasCompositeKeyEncoding returns true if key columns of the given kind can have a composite encoding. For such types, it can be decided on a case-by-base basis whether a given Datum requires the composite encoding.

func IsPermanentSchemaChangeError

func IsPermanentSchemaChangeError(err error) bool

IsPermanentSchemaChangeError returns true if the error results in a permanent failure of a schema change.

func IsReservedID

func IsReservedID(id ID) bool

IsReservedID returns whether this ID is for any system object.

func IsSystemConfigID

func IsSystemConfigID(id ID) bool

IsSystemConfigID returns whether this ID is for a system config object.

func IsUndefinedDatabaseError

func IsUndefinedDatabaseError(err error) bool

IsUndefinedDatabaseError returns true if the error is for an undefined database.

func IsUndefinedTableError

func IsUndefinedTableError(err error) bool

IsUndefinedTableError returns true if the error is for an undefined table.

func IsUniquenessConstraintViolationError

func IsUniquenessConstraintViolationError(err error) bool

IsUniquenessConstraintViolationError returns true if the error is for a uniqueness constraint violation.

func MakeAllDescsMetadataKey

func MakeAllDescsMetadataKey() roachpb.Key

MakeAllDescsMetadataKey returns the key for all descriptors.

func MakeColumnDefDescs

func MakeColumnDefDescs(
	d *parser.ColumnTableDef, searchPath parser.SearchPath, evalCtx *parser.EvalContext,
) (*ColumnDescriptor, *IndexDescriptor, error)

MakeColumnDefDescs creates the column descriptor for a column, as well as the index descriptor if the column is a primary key or unique. The search path is used for name resolution for DEFAULT expressions.

func MakeDefaultExprs

func MakeDefaultExprs(
	cols []ColumnDescriptor, parse *parser.Parser, evalCtx *parser.EvalContext,
) ([]parser.TypedExpr, error)

MakeDefaultExprs returns a slice of the default expressions for the slice of input column descriptors, or nil if none of the input column descriptors have default expressions.

func MakeDescMetadataKey

func MakeDescMetadataKey(descID ID) roachpb.Key

MakeDescMetadataKey returns the key for the descriptor.

func MakeIndexKeyPrefix

func MakeIndexKeyPrefix(desc *TableDescriptor, indexID IndexID) []byte

MakeIndexKeyPrefix returns the key prefix used for the index's data. If you need the corresponding Span, prefer desc.IndexSpan(indexID) or desc.PrimaryIndexSpan().

func MakeKeyFromEncDatums

func MakeKeyFromEncDatums(
	values EncDatumRow,
	tableDesc *TableDescriptor,
	index *IndexDescriptor,
	keyPrefix []byte,
	alloc *DatumAlloc,
) (roachpb.Key, error)

MakeKeyFromEncDatums creates a key by concatenating keyPrefix with the encodings of the given EncDatum values. The values correspond to index.ColumnIDs.

If a table or index is interleaved, `encoding.encodedNullDesc` is used in place of the family id (a varint) to signal the next component of the key. An example of one level of interleaving (a parent): /<parent_table_id>/<parent_index_id>/<field_1>/<field_2>/NullDesc/<table_id>/<index_id>/<field_3>/<family>

Note that ExtraColumnIDs are not encoded, so the result isn't always a full index key.

func MakeNameMetadataKey

func MakeNameMetadataKey(parentID ID, name string) roachpb.Key

MakeNameMetadataKey returns the key for the name. Pass name == "" in order to generate the prefix key to use to scan over all of the names for the specified parentID.

func MakePrimaryIndexKey

func MakePrimaryIndexKey(desc *TableDescriptor, vals ...interface{}) (roachpb.Key, error)

MakePrimaryIndexKey creates a key prefix that corresponds to a table row (in the primary index); it is intended for tests.

The value types must match the primary key columns (or a prefix of them); supported types are: - Datum

  • bool (converts to DBool)
  • int (converts to DInt)
  • string (converts to DString)

func MakeZoneKey

func MakeZoneKey(id ID) roachpb.Key

MakeZoneKey returns the key for 'id's entry in the system.zones table.

func MarshalColumnValue

func MarshalColumnValue(col ColumnDescriptor, val parser.Datum) (roachpb.Value, error)

MarshalColumnValue returns a Go primitive value equivalent of val, of the type expected by col. If val's type is incompatible with col, or if col's type is not yet implemented, an error is returned.

func NewDatabaseAlreadyExistsError

func NewDatabaseAlreadyExistsError(name string) error

NewDatabaseAlreadyExistsError creates an error for a preexisting database.

func NewDependentObjectError

func NewDependentObjectError(msg string) error

NewDependentObjectError creates a dependent object error.

func NewDependentObjectErrorWithHint

func NewDependentObjectErrorWithHint(msg string, hint string) error

NewDependentObjectErrorWithHint creates a dependent object error with a hint

func NewInvalidSchemaDefinitionError

func NewInvalidSchemaDefinitionError(err error) error

NewInvalidSchemaDefinitionError creates an error for an invalid schema definition such as a schema definition that doesn't parse.

func NewNonNullViolationError

func NewNonNullViolationError(columnName string) error

NewNonNullViolationError creates an error for a violation of a non-NULL constraint.

func NewRangeUnavailableError

func NewRangeUnavailableError(
	rangeID roachpb.RangeID, origErr error, nodeIDs ...roachpb.NodeID,
) error

NewRangeUnavailableError creates an unavailable range error.

func NewRelationAlreadyExistsError

func NewRelationAlreadyExistsError(name string) error

NewRelationAlreadyExistsError creates an error for a preexisting relation.

func NewRetryError

func NewRetryError(cause error) error

NewRetryError creates an error signifying that the transaction can be retried. It signals to the user that the SQL txn entered the RESTART_WAIT state after a serialization error, and that a ROLLBACK TO SAVEPOINT COCKROACH_RESTART statement should be issued.

func NewStatementCompletionUnknownError

func NewStatementCompletionUnknownError(err *roachpb.AmbiguousResultError) error

NewStatementCompletionUnknownError creates an error with the corresponding pg code. This is used to inform the client that it's unknown whether a statement succeeded or not. Of particular interest to clients is when this error is returned for a statement outside of a transaction or for a COMMIT/RELEASE SAVEPOINT - there manual inspection may be necessary to check whether the statement/transaction committed. When this is returned for other transactional statements, the transaction has been rolled back (like it is for any errors).

NOTE(andrei): When introducing this error, I haven't verified the exact conditions under which Postgres returns this code, nor its relationship to code CodeTransactionResolutionUnknownError. I couldn't find good documentation on these codes.

func NewSyntaxError

func NewSyntaxError(msg string) error

NewSyntaxError creates a syntax error.

func NewTransactionAbortedError

func NewTransactionAbortedError(customMsg string) error

NewTransactionAbortedError creates an error for trying to run a command in the context of transaction that's already aborted.

func NewTransactionCommittedError

func NewTransactionCommittedError() error

NewTransactionCommittedError creates an error that signals that the SQL txn is in the COMMIT_WAIT state and that only a COMMIT statement will be accepted.

func NewUndefinedDatabaseError

func NewUndefinedDatabaseError(name string) error

NewUndefinedDatabaseError creates an error that represents a missing database.

func NewUndefinedTableError

func NewUndefinedTableError(name string) error

NewUndefinedTableError creates an error that represents a missing database table.

func NewUndefinedViewError

func NewUndefinedViewError(name string) error

NewUndefinedViewError creates an error that represents a missing database view.

func NewUniquenessConstraintViolationError

func NewUniquenessConstraintViolationError(index *IndexDescriptor, vals []parser.Datum) error

NewUniquenessConstraintViolationError creates an error that represents a violation of a UNIQUE constraint.

func NewWindowingError

func NewWindowingError(in string) error

NewWindowingError creates a windowing error.

func NewWrongObjectTypeError

func NewWrongObjectTypeError(name, desiredObjType string) error

NewWrongObjectTypeError creates a wrong object type error.

func ParseFixedOffsetTimeZone

func ParseFixedOffsetTimeZone(location string) (offset int, origRepr string, success bool)

ParseFixedOffsetTimeZone takes the string representation of a time.Location created by FixedOffsetTimeZoneToLocation and parses it to the offset and the original representation specified by the user. The bool returned is true if parsing was successful.

The strings produced by FixedOffsetTimeZoneToLocation look like "<fixedOffsetPrefix><offset> (<origRepr>)".

func PrettyKey

func PrettyKey(key roachpb.Key, skip int) string

PrettyKey pretty-prints the specified key, skipping over the first `skip` fields. The pretty printed key looks like:

/Table/<tableID>/<indexID>/...

We always strip off the /Table prefix and then `skip` more fields. Note that this assumes that the fields themselves do not contain '/', but that is currently true for the fields we care about stripping (the table and index ID).

func PrettySpan

func PrettySpan(span roachpb.Span, skip int) string

PrettySpan returns a human-readable representation of a span.

func PrettySpans

func PrettySpans(spans []roachpb.Span, skip int) string

PrettySpans returns a human-readable description of the spans.

func RandCollationLocale

func RandCollationLocale(rng *rand.Rand) *string

RandCollationLocale returns a random element of collationLocales.

func RandDatum

func RandDatum(rng *rand.Rand, typ ColumnType, null bool) parser.Datum

RandDatum generates a random Datum of the given type. If null is true, the datum can be DNull. Note that if typ.Kind is ColumnType_NULL, the datum will always be DNull, regardless of the null flag.

func RandEncDatumSlices

func RandEncDatumSlices(rng *rand.Rand, numSets, numValsPerSet int) [][]EncDatum

RandEncDatumSlices generates EncDatum slices, each slice with values of the same random type.

func RunFilter

func RunFilter(filter parser.TypedExpr, evalCtx *parser.EvalContext) (bool, error)

RunFilter runs a filter expression and returns whether the filter passes.

func SanitizeVarFreeExpr

func SanitizeVarFreeExpr(
	expr parser.Expr, expectedType parser.Type, context string, searchPath parser.SearchPath,
) (parser.TypedExpr, error)

SanitizeVarFreeExpr verifies that an expression is valid, has the correct type and contains no variable expressions. It returns the type-checked and constant-folded expression.

func SetKVBatchSize

func SetKVBatchSize(val int64) func()

SetKVBatchSize changes the kvFetcher batch size, and returns a function that restores it.

func SystemDesiredPrivileges

func SystemDesiredPrivileges(id ID) privilege.List

SystemDesiredPrivileges returns the desired privilege list (i.e., the privilege list with which the object should be created with in a fresh cluster) for a given system object ID. This function panics if id does not exist in the SystemAllowedPrivileges map and should only be used in contexts where id is guaranteed to exist.

func TimeZoneStringToLocation

func TimeZoneStringToLocation(location string) (*time.Location, error)

TimeZoneStringToLocation transforms a string into a time.Location. It supports the usual locations and also time zones with fixed offsets created by FixedOffsetTimeZoneToLocation().

func UnmarshalColumnValue

func UnmarshalColumnValue(
	a *DatumAlloc, typ ColumnType, value *roachpb.Value,
) (parser.Datum, error)

UnmarshalColumnValue decodes the value from a key-value pair using the type expected by the column. An error is returned if the value's type does not match the column's type.

Types

type ColTypeInfo

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

ColTypeInfo is a type that allows multiple representations of column type information (to avoid conversions and allocations).

func ColTypeInfoFromColTypes

func ColTypeInfoFromColTypes(colTypes []ColumnType) ColTypeInfo

ColTypeInfoFromColTypes creates a ColTypeInfo from []ColumnType.

func ColTypeInfoFromResCols

func ColTypeInfoFromResCols(resCols ResultColumns) ColTypeInfo

ColTypeInfoFromResCols creates a ColTypeInfo from ResultColumns.

func (ColTypeInfo) NumColumns

func (ti ColTypeInfo) NumColumns() int

NumColumns returns the number of columns in the type.

func (ColTypeInfo) Type

func (ti ColTypeInfo) Type(idx int) parser.Type

Type returns the datum type of the i-th column.

type ColumnDescriptor

type ColumnDescriptor struct {
	Name     string     `protobuf:"bytes,1,opt,name=name" json:"name"`
	ID       ColumnID   `protobuf:"varint,2,opt,name=id,casttype=ColumnID" json:"id"`
	Type     ColumnType `protobuf:"bytes,3,opt,name=type" json:"type"`
	Nullable bool       `protobuf:"varint,4,opt,name=nullable" json:"nullable"`
	// Default expression to use to populate the column on insert if no
	// value is provided.
	DefaultExpr *string `protobuf:"bytes,5,opt,name=default_expr,json=defaultExpr" json:"default_expr,omitempty"`
	Hidden      bool    `protobuf:"varint,6,opt,name=hidden" json:"hidden"`
}

func (*ColumnDescriptor) Descriptor

func (*ColumnDescriptor) Descriptor() ([]byte, []int)

func (*ColumnDescriptor) Marshal

func (m *ColumnDescriptor) Marshal() (dAtA []byte, err error)

func (*ColumnDescriptor) MarshalTo

func (m *ColumnDescriptor) MarshalTo(dAtA []byte) (int, error)

func (*ColumnDescriptor) ProtoMessage

func (*ColumnDescriptor) ProtoMessage()

func (*ColumnDescriptor) Reset

func (m *ColumnDescriptor) Reset()

func (*ColumnDescriptor) Size

func (m *ColumnDescriptor) Size() (n int)

func (*ColumnDescriptor) String

func (m *ColumnDescriptor) String() string

func (*ColumnDescriptor) Unmarshal

func (m *ColumnDescriptor) Unmarshal(dAtA []byte) error

type ColumnFamilyDescriptor

type ColumnFamilyDescriptor struct {
	Name string   `protobuf:"bytes,1,opt,name=name" json:"name"`
	ID   FamilyID `protobuf:"varint,2,opt,name=id,casttype=FamilyID" json:"id"`
	// A list of column names of which the family is comprised. This list
	// parallels the column_ids list. If duplicating the storage of the column
	// names here proves to be prohibitive, we could clear this field before
	// saving and reconstruct it after loading.
	ColumnNames []string `protobuf:"bytes,3,rep,name=column_names,json=columnNames" json:"column_names,omitempty"`
	// A list of column ids of which the family is comprised. This list parallels
	// the column_names list.
	ColumnIDs []ColumnID `protobuf:"varint,4,rep,name=column_ids,json=columnIds,casttype=ColumnID" json:"column_ids,omitempty"`
	// If nonzero, the column involved in the single column optimization.
	//
	// Families store colums in a ValueType_TUPLE as repeated <colid><data>
	// entries. As a space optimization and for backward compatibility, a single
	// column is written without the columnid prefix. Because more columns could
	// be added, it would be ambiguous which column was stored when read back in,
	// so this field supplies it.
	DefaultColumnID ColumnID `protobuf:"varint,5,opt,name=default_column_id,json=defaultColumnId,casttype=ColumnID" json:"default_column_id"`
}

ColumnFamilyDescriptor is set of columns stored together in one kv entry.

func (*ColumnFamilyDescriptor) Descriptor

func (*ColumnFamilyDescriptor) Descriptor() ([]byte, []int)

func (*ColumnFamilyDescriptor) Marshal

func (m *ColumnFamilyDescriptor) Marshal() (dAtA []byte, err error)

func (*ColumnFamilyDescriptor) MarshalTo

func (m *ColumnFamilyDescriptor) MarshalTo(dAtA []byte) (int, error)

func (*ColumnFamilyDescriptor) ProtoMessage

func (*ColumnFamilyDescriptor) ProtoMessage()

func (*ColumnFamilyDescriptor) Reset

func (m *ColumnFamilyDescriptor) Reset()

func (*ColumnFamilyDescriptor) Size

func (m *ColumnFamilyDescriptor) Size() (n int)

func (*ColumnFamilyDescriptor) String

func (m *ColumnFamilyDescriptor) String() string

func (*ColumnFamilyDescriptor) Unmarshal

func (m *ColumnFamilyDescriptor) Unmarshal(dAtA []byte) error

type ColumnID

type ColumnID parser.ColumnID

ColumnID is a custom type for ColumnDescriptor IDs.

type ColumnOrderInfo

type ColumnOrderInfo struct {
	ColIdx    int
	Direction encoding.Direction
}

ColumnOrderInfo describes a column (as an index) and a desired order direction.

type ColumnOrdering

type ColumnOrdering []ColumnOrderInfo

ColumnOrdering is used to describe a desired column ordering. For example,

[]ColumnOrderInfo{ {3, true}, {1, false} }

represents an ordering first by column 3 (descending), then by column 1 (ascending).

func (ColumnOrdering) IsPrefixOf

func (a ColumnOrdering) IsPrefixOf(b ColumnOrdering) bool

IsPrefixOf returns true if the receiver ordering matches a prefix of the given ordering. In this case, rows with an order conforming to b automatically conform to a.

type ColumnType

type ColumnType struct {
	Kind ColumnType_Kind `protobuf:"varint,1,opt,name=kind,enum=cockroach.sql.sqlbase.ColumnType_Kind" json:"kind"`
	// BIT, INT, FLOAT, DECIMAL, CHAR and BINARY
	Width int32 `protobuf:"varint,2,opt,name=width" json:"width"`
	// FLOAT and DECIMAL.
	Precision int32 `protobuf:"varint,3,opt,name=precision" json:"precision"`
	// The length of each dimension in the array. A dimension of -1 means that
	// no bound was specified for that dimension.
	ArrayDimensions []int32 `protobuf:"varint,4,rep,name=array_dimensions,json=arrayDimensions" json:"array_dimensions,omitempty"`
	// Collated STRING, CHAR, and VARCHAR
	Locale *string `protobuf:"bytes,5,opt,name=locale" json:"locale,omitempty"`
}

func DatumTypeToColumnType

func DatumTypeToColumnType(ptyp parser.Type) ColumnType

DatumTypeToColumnType converts a parser Type to a ColumnType.

func RandColumnType

func RandColumnType(rng *rand.Rand) ColumnType

RandColumnType returns a random ColumnType_Kind value.

func (*ColumnType) Descriptor

func (*ColumnType) Descriptor() ([]byte, []int)

func (*ColumnType) Marshal

func (m *ColumnType) Marshal() (dAtA []byte, err error)

func (*ColumnType) MarshalTo

func (m *ColumnType) MarshalTo(dAtA []byte) (int, error)

func (*ColumnType) MaxCharacterLength

func (c *ColumnType) MaxCharacterLength() (int32, bool)

MaxCharacterLength returns the declared maximum length of characters if the ColumnType is a character or bit string data type. Returns false if the data type is not a character or bit string, or if the string's length is not bounded.

func (*ColumnType) MaxOctetLength

func (c *ColumnType) MaxOctetLength() (int32, bool)

MaxOctetLength returns the maximum the maximum possible length in octets of a datum if the ColumnType is a character string. Returns false if the data type is not a character string, or if the string's length is not bounded.

func (*ColumnType) NumericPrecision

func (c *ColumnType) NumericPrecision() (int32, bool)

NumericPrecision returns the declared or implicit precision of numeric data types. Returns false if the data type is not numeric, or if the precision of the numeric type is not bounded.

func (*ColumnType) NumericScale

func (c *ColumnType) NumericScale() (int32, bool)

NumericScale returns the declared or implicit precision of exact numeric data types. Returns false if the data type is not an exact numeric, or if the scale of the exact numeric type is not bounded.

func (*ColumnType) ProtoMessage

func (*ColumnType) ProtoMessage()

func (*ColumnType) Reset

func (m *ColumnType) Reset()

func (*ColumnType) SQLString

func (c *ColumnType) SQLString() string

SQLString returns the SQL string corresponding to the type.

func (*ColumnType) Size

func (m *ColumnType) Size() (n int)

func (*ColumnType) String

func (m *ColumnType) String() string

func (*ColumnType) ToDatumType

func (c *ColumnType) ToDatumType() parser.Type

ToDatumType converts the ColumnType to the correct type, or nil if there is no correspondence.

func (*ColumnType) Unmarshal

func (m *ColumnType) Unmarshal(dAtA []byte) error

type ColumnType_Kind

type ColumnType_Kind int32

These mirror the types supported by the sql/parser. See sql/parser/col_types.go.

const (
	ColumnType_BOOL           ColumnType_Kind = 0
	ColumnType_INT            ColumnType_Kind = 1
	ColumnType_FLOAT          ColumnType_Kind = 2
	ColumnType_DECIMAL        ColumnType_Kind = 3
	ColumnType_DATE           ColumnType_Kind = 4
	ColumnType_TIMESTAMP      ColumnType_Kind = 5
	ColumnType_INTERVAL       ColumnType_Kind = 6
	ColumnType_STRING         ColumnType_Kind = 7
	ColumnType_BYTES          ColumnType_Kind = 8
	ColumnType_TIMESTAMPTZ    ColumnType_Kind = 9
	ColumnType_COLLATEDSTRING ColumnType_Kind = 10
	ColumnType_NAME           ColumnType_Kind = 11
	ColumnType_OID            ColumnType_Kind = 12
	// NULL is not supported as a table column type, however it can be
	// transferred through distsql streams.
	ColumnType_NULL ColumnType_Kind = 13
	// Array and vector types.
	//
	// TODO(cuongdo): Fix this before allowing persistence of array/vector types
	// It would be cleaner if when array_dimensions are specified, Kind is
	// simply the parameterized type of the array. However, because Kind is used
	// to determine type information elsewhere, it isn't possible to take the
	// cleaner approach without an extensive refactoring.
	ColumnType_INT_ARRAY  ColumnType_Kind = 100
	ColumnType_INT2VECTOR ColumnType_Kind = 200
)

func (ColumnType_Kind) Enum

func (x ColumnType_Kind) Enum() *ColumnType_Kind

func (ColumnType_Kind) EnumDescriptor

func (ColumnType_Kind) EnumDescriptor() ([]byte, []int)

func (ColumnType_Kind) String

func (x ColumnType_Kind) String() string

func (*ColumnType_Kind) UnmarshalJSON

func (x *ColumnType_Kind) UnmarshalJSON(data []byte) error

type ConstraintDetail

type ConstraintDetail struct {
	Kind        ConstraintType
	Columns     []string
	Details     string
	Unvalidated bool

	// Only populated for FK, PK, and Unique Constraints.
	Index *IndexDescriptor

	// Only populated for FK Constraints.
	FK              *ForeignKeyReference
	ReferencedTable *TableDescriptor
	ReferencedIndex *IndexDescriptor

	// Only populated for Check Constraints.
	CheckConstraint *TableDescriptor_CheckConstraint
}

ConstraintDetail describes a constraint.

type ConstraintType

type ConstraintType string

ConstraintType is used to identify the type of a constraint.

const (
	// ConstraintTypePK identifies a PRIMARY KEY constraint.
	ConstraintTypePK ConstraintType = "PRIMARY KEY"
	// ConstraintTypeFK identifies a FOREIGN KEY constraint.
	ConstraintTypeFK ConstraintType = "FOREIGN KEY"
	// ConstraintTypeUnique identifies a FOREIGN constraint.
	ConstraintTypeUnique ConstraintType = "UNIQUE"
	// ConstraintTypeCheck identifies a CHECK constraint.
	ConstraintTypeCheck ConstraintType = "CHECK"
)

type ConstraintValidity

type ConstraintValidity int32
const (
	ConstraintValidity_Validated   ConstraintValidity = 0
	ConstraintValidity_Unvalidated ConstraintValidity = 1
)

func (ConstraintValidity) Enum

func (ConstraintValidity) EnumDescriptor

func (ConstraintValidity) EnumDescriptor() ([]byte, []int)

func (ConstraintValidity) String

func (x ConstraintValidity) String() string

func (*ConstraintValidity) UnmarshalJSON

func (x *ConstraintValidity) UnmarshalJSON(data []byte) error

type DatabaseDescriptor

type DatabaseDescriptor struct {
	Name       string               `protobuf:"bytes,1,opt,name=name" json:"name"`
	ID         ID                   `protobuf:"varint,2,opt,name=id,casttype=ID" json:"id"`
	Privileges *PrivilegeDescriptor `protobuf:"bytes,3,opt,name=privileges" json:"privileges,omitempty"`
}

DatabaseDescriptor represents a namespace (aka database) and is stored in a structured metadata key. The DatabaseDescriptor has a globally-unique ID shared with the TableDescriptor ID. Permissions are applied to all tables in the namespace.

func GetDatabaseDescFromID

func GetDatabaseDescFromID(
	ctx context.Context, txn *client.Txn, id ID,
) (*DatabaseDescriptor, error)

GetDatabaseDescFromID retrieves the database descriptor for the database ID passed in using an existing txn. Returns an error if the descriptor doesn't exist or if it exists and is not a database.

func (*DatabaseDescriptor) Descriptor

func (*DatabaseDescriptor) Descriptor() ([]byte, []int)

func (*DatabaseDescriptor) GetID

func (m *DatabaseDescriptor) GetID() ID

func (*DatabaseDescriptor) GetName

func (m *DatabaseDescriptor) GetName() string

func (*DatabaseDescriptor) GetPrivileges

func (m *DatabaseDescriptor) GetPrivileges() *PrivilegeDescriptor

func (*DatabaseDescriptor) Marshal

func (m *DatabaseDescriptor) Marshal() (dAtA []byte, err error)

func (*DatabaseDescriptor) MarshalTo

func (m *DatabaseDescriptor) MarshalTo(dAtA []byte) (int, error)

func (*DatabaseDescriptor) ProtoMessage

func (*DatabaseDescriptor) ProtoMessage()

func (*DatabaseDescriptor) Reset

func (m *DatabaseDescriptor) Reset()

func (*DatabaseDescriptor) SetID

func (desc *DatabaseDescriptor) SetID(id ID)

SetID implements the DescriptorProto interface.

func (*DatabaseDescriptor) SetName

func (desc *DatabaseDescriptor) SetName(name string)

SetName implements the DescriptorProto interface.

func (*DatabaseDescriptor) Size

func (m *DatabaseDescriptor) Size() (n int)

func (*DatabaseDescriptor) String

func (m *DatabaseDescriptor) String() string

func (*DatabaseDescriptor) TypeName

func (desc *DatabaseDescriptor) TypeName() string

TypeName returns the plain type of this descriptor.

func (*DatabaseDescriptor) Unmarshal

func (m *DatabaseDescriptor) Unmarshal(dAtA []byte) error

func (*DatabaseDescriptor) Validate

func (desc *DatabaseDescriptor) Validate() error

Validate validates that the database descriptor is well formed. Checks include validate the database name, and verifying that there is at least one read and write user.

type DatumAlloc

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

DatumAlloc provides batch allocation of datum pointers, amortizing the cost of the allocations.

func (*DatumAlloc) NewDBytes

func (a *DatumAlloc) NewDBytes(v parser.DBytes) *parser.DBytes

NewDBytes allocates a DBytes.

func (*DatumAlloc) NewDDate

func (a *DatumAlloc) NewDDate(v parser.DDate) *parser.DDate

NewDDate allocates a DDate.

func (*DatumAlloc) NewDDecimal

func (a *DatumAlloc) NewDDecimal(v parser.DDecimal) *parser.DDecimal

NewDDecimal allocates a DDecimal.

func (*DatumAlloc) NewDFloat

func (a *DatumAlloc) NewDFloat(v parser.DFloat) *parser.DFloat

NewDFloat allocates a DFloat.

func (*DatumAlloc) NewDInt

func (a *DatumAlloc) NewDInt(v parser.DInt) *parser.DInt

NewDInt allocates a DInt.

func (*DatumAlloc) NewDInterval

func (a *DatumAlloc) NewDInterval(v parser.DInterval) *parser.DInterval

NewDInterval allocates a DInterval.

func (*DatumAlloc) NewDName

func (a *DatumAlloc) NewDName(v parser.DString) parser.Datum

NewDName allocates a DName.

func (*DatumAlloc) NewDOid

func (a *DatumAlloc) NewDOid(v parser.DOid) parser.Datum

NewDOid allocates a DOid.

func (*DatumAlloc) NewDString

func (a *DatumAlloc) NewDString(v parser.DString) *parser.DString

NewDString allocates a DString.

func (*DatumAlloc) NewDTimestamp

func (a *DatumAlloc) NewDTimestamp(v parser.DTimestamp) *parser.DTimestamp

NewDTimestamp allocates a DTimestamp.

func (*DatumAlloc) NewDTimestampTZ

func (a *DatumAlloc) NewDTimestampTZ(v parser.DTimestampTZ) *parser.DTimestampTZ

NewDTimestampTZ allocates a DTimestampTZ.

type DatumEncoding

type DatumEncoding int32

DatumEncoding identifies the encoding used for an EncDatum.

const (
	// Indicates that the datum is encoded using the order-preserving encoding
	// used for keys (ascending order).
	DatumEncoding_ASCENDING_KEY DatumEncoding = 0
	// Indicates that the datum is encoded using the order-preserving encoding
	// used for keys (descending order).
	DatumEncoding_DESCENDING_KEY DatumEncoding = 1
	// Indicates that the datum is encoded using the encoding used for values.
	DatumEncoding_VALUE DatumEncoding = 2
)

func RandDatumEncoding

func RandDatumEncoding(rng *rand.Rand) DatumEncoding

RandDatumEncoding returns a random DatumEncoding value.

func (DatumEncoding) Enum

func (x DatumEncoding) Enum() *DatumEncoding

func (DatumEncoding) EnumDescriptor

func (DatumEncoding) EnumDescriptor() ([]byte, []int)

func (DatumEncoding) String

func (x DatumEncoding) String() string

func (*DatumEncoding) UnmarshalJSON

func (x *DatumEncoding) UnmarshalJSON(data []byte) error

type Descriptor

type Descriptor struct {
	// Types that are valid to be assigned to Union:
	//	*Descriptor_Table
	//	*Descriptor_Database
	Union isDescriptor_Union `protobuf_oneof:"union"`
}

Descriptor is a union type holding either a table or database descriptor.

func WrapDescriptor

func WrapDescriptor(descriptor DescriptorProto) *Descriptor

WrapDescriptor fills in a Descriptor.

func (*Descriptor) Descriptor

func (*Descriptor) Descriptor() ([]byte, []int)

func (*Descriptor) GetDatabase

func (m *Descriptor) GetDatabase() *DatabaseDescriptor

func (*Descriptor) GetID

func (desc *Descriptor) GetID() ID

GetID returns the ID of the descriptor.

func (*Descriptor) GetName

func (desc *Descriptor) GetName() string

GetName returns the Name of the descriptor.

func (*Descriptor) GetTable

func (m *Descriptor) GetTable() *TableDescriptor

func (*Descriptor) GetUnion

func (m *Descriptor) GetUnion() isDescriptor_Union

func (*Descriptor) Marshal

func (m *Descriptor) Marshal() (dAtA []byte, err error)

func (*Descriptor) MarshalTo

func (m *Descriptor) MarshalTo(dAtA []byte) (int, error)

func (*Descriptor) ProtoMessage

func (*Descriptor) ProtoMessage()

func (*Descriptor) Reset

func (m *Descriptor) Reset()

func (*Descriptor) Size

func (m *Descriptor) Size() (n int)

func (*Descriptor) String

func (m *Descriptor) String() string

func (*Descriptor) Unmarshal

func (m *Descriptor) Unmarshal(dAtA []byte) error

func (*Descriptor) XXX_OneofFuncs

func (*Descriptor) XXX_OneofFuncs() (func(msg proto.Message, b *proto.Buffer) error, func(msg proto.Message, tag, wire int, b *proto.Buffer) (bool, error), func(msg proto.Message) (n int), []interface{})

XXX_OneofFuncs is for the internal use of the proto package.

type DescriptorKey

type DescriptorKey interface {
	Key() roachpb.Key
	Name() string
}

DescriptorKey is the interface implemented by both databaseKey and tableKey. It is used to easily get the descriptor key and plain name.

type DescriptorMutation

type DescriptorMutation struct {
	// Types that are valid to be assigned to Descriptor_:
	//	*DescriptorMutation_Column
	//	*DescriptorMutation_Index
	Descriptor_ isDescriptorMutation_Descriptor_ `protobuf_oneof:"descriptor"`
	State       DescriptorMutation_State         `protobuf:"varint,3,opt,name=state,enum=cockroach.sql.sqlbase.DescriptorMutation_State" json:"state"`
	Direction   DescriptorMutation_Direction     `protobuf:"varint,4,opt,name=direction,enum=cockroach.sql.sqlbase.DescriptorMutation_Direction" json:"direction"`
	// The mutation id used to group mutations that should be applied together.
	// This is used for situations like creating a unique column, which
	// involve adding two mutations: one for the column, and another for the
	// unique constraint index.
	MutationID MutationID `protobuf:"varint,5,opt,name=mutation_id,json=mutationId,casttype=MutationID" json:"mutation_id"`
	// A schema change can involve running multiple processors backfilling
	// or deleting data. They occasionally checkpoint Spans so that the
	// processing can resume in the event of a node failure. The spans are
	// non-overlapping contiguous areas of the KV space that still need to
	// be processed.
	ResumeSpans []cockroach_roachpb1.Span `protobuf:"bytes,6,rep,name=resume_spans,json=resumeSpans" json:"resume_spans"`
}

A DescriptorMutation represents a column or an index that has either been added or dropped and hasn't yet transitioned into a stable state: completely backfilled and visible, or completely deleted. A table descriptor in the middle of a schema change will have a DescriptorMutation FIFO queue containing each column/index descriptor being added or dropped.

func (*DescriptorMutation) Descriptor

func (*DescriptorMutation) Descriptor() ([]byte, []int)

func (*DescriptorMutation) GetColumn

func (m *DescriptorMutation) GetColumn() *ColumnDescriptor

func (*DescriptorMutation) GetDescriptor_

func (m *DescriptorMutation) GetDescriptor_() isDescriptorMutation_Descriptor_

func (*DescriptorMutation) GetIndex

func (m *DescriptorMutation) GetIndex() *IndexDescriptor

func (*DescriptorMutation) Marshal

func (m *DescriptorMutation) Marshal() (dAtA []byte, err error)

func (*DescriptorMutation) MarshalTo

func (m *DescriptorMutation) MarshalTo(dAtA []byte) (int, error)

func (*DescriptorMutation) ProtoMessage

func (*DescriptorMutation) ProtoMessage()

func (*DescriptorMutation) Reset

func (m *DescriptorMutation) Reset()

func (*DescriptorMutation) Size

func (m *DescriptorMutation) Size() (n int)

func (*DescriptorMutation) String

func (m *DescriptorMutation) String() string

func (*DescriptorMutation) Unmarshal

func (m *DescriptorMutation) Unmarshal(dAtA []byte) error

func (*DescriptorMutation) XXX_OneofFuncs

func (*DescriptorMutation) XXX_OneofFuncs() (func(msg proto.Message, b *proto.Buffer) error, func(msg proto.Message, tag, wire int, b *proto.Buffer) (bool, error), func(msg proto.Message) (n int), []interface{})

XXX_OneofFuncs is for the internal use of the proto package.

type DescriptorMutation_Column

type DescriptorMutation_Column struct {
	Column *ColumnDescriptor `protobuf:"bytes,1,opt,name=column,oneof"`
}

func (*DescriptorMutation_Column) MarshalTo

func (m *DescriptorMutation_Column) MarshalTo(dAtA []byte) (int, error)

func (*DescriptorMutation_Column) Size

func (m *DescriptorMutation_Column) Size() (n int)

type DescriptorMutation_Direction

type DescriptorMutation_Direction int32

Direction of mutation.

const (
	// Not used.
	DescriptorMutation_NONE DescriptorMutation_Direction = 0
	// Descriptor is being added.
	DescriptorMutation_ADD DescriptorMutation_Direction = 1
	// Descriptor is being dropped.
	DescriptorMutation_DROP DescriptorMutation_Direction = 2
)

func (DescriptorMutation_Direction) Enum

func (DescriptorMutation_Direction) EnumDescriptor

func (DescriptorMutation_Direction) EnumDescriptor() ([]byte, []int)

func (DescriptorMutation_Direction) String

func (*DescriptorMutation_Direction) UnmarshalJSON

func (x *DescriptorMutation_Direction) UnmarshalJSON(data []byte) error

type DescriptorMutation_Index

type DescriptorMutation_Index struct {
	Index *IndexDescriptor `protobuf:"bytes,2,opt,name=index,oneof"`
}

func (*DescriptorMutation_Index) MarshalTo

func (m *DescriptorMutation_Index) MarshalTo(dAtA []byte) (int, error)

func (*DescriptorMutation_Index) Size

func (m *DescriptorMutation_Index) Size() (n int)

type DescriptorMutation_State

type DescriptorMutation_State int32

A descriptor within a mutation is unavailable for reads, writes and deletes. It is only available for implicit (internal to the database) writes and deletes depending on the state of the mutation.

const (
	// Not used.
	DescriptorMutation_UNKNOWN DescriptorMutation_State = 0
	// Operations can use this invisible descriptor to implicitly
	// delete entries.
	// Column: A descriptor in this state is invisible to
	// INSERT and UPDATE. DELETE must delete a column in this state.
	// Index: A descriptor in this state is invisible to an INSERT.
	// UPDATE must delete the old value of the index but doesn't write
	// the new value. DELETE must delete the index.
	//
	// When deleting a descriptor, all descriptor related data
	// (column or index data) can only be mass deleted once
	// all the nodes have transitioned to the DELETE_ONLY state.
	DescriptorMutation_DELETE_ONLY DescriptorMutation_State = 1
	// Operations can use this invisible descriptor to implicitly
	// write and delete entries.
	// Column: INSERT will populate this column with the default
	// value. UPDATE ignores this descriptor. DELETE must delete
	// the column.
	// Index: INSERT, UPDATE and DELETE treat this index like any
	// other index.
	//
	// When adding a descriptor, all descriptor related data
	// (column default or index data) can only be backfilled once
	// all nodes have transitioned into the WRITE_ONLY state.
	DescriptorMutation_WRITE_ONLY DescriptorMutation_State = 2
)

func (DescriptorMutation_State) Enum

func (DescriptorMutation_State) EnumDescriptor

func (DescriptorMutation_State) EnumDescriptor() ([]byte, []int)

func (DescriptorMutation_State) String

func (x DescriptorMutation_State) String() string

func (*DescriptorMutation_State) UnmarshalJSON

func (x *DescriptorMutation_State) UnmarshalJSON(data []byte) error

type DescriptorProto

type DescriptorProto interface {
	proto.Message
	GetPrivileges() *PrivilegeDescriptor
	GetID() ID
	SetID(ID)
	TypeName() string
	GetName() string
	SetName(string)
}

DescriptorProto is the interface implemented by both DatabaseDescriptor and TableDescriptor. TODO(marc): this is getting rather large.

type DescriptorStatus

type DescriptorStatus int

DescriptorStatus is the status for a descriptor.

const (

	// DescriptorAbsent for a descriptor that doesn't exist.
	DescriptorAbsent DescriptorStatus
	// DescriptorIncomplete for a descriptor that is a part of a
	// schema change, and is still being processed.
	DescriptorIncomplete
	// DescriptorActive for a descriptor that is completely active
	// for read/write and delete operations.
	DescriptorActive
)

type DescriptorVersion

type DescriptorVersion uint32

DescriptorVersion is a custom type for TableDescriptor Versions.

type Descriptor_Database

type Descriptor_Database struct {
	Database *DatabaseDescriptor `protobuf:"bytes,2,opt,name=database,oneof"`
}

func (*Descriptor_Database) MarshalTo

func (m *Descriptor_Database) MarshalTo(dAtA []byte) (int, error)

func (*Descriptor_Database) Size

func (m *Descriptor_Database) Size() (n int)

type Descriptor_Table

type Descriptor_Table struct {
	Table *TableDescriptor `protobuf:"bytes,1,opt,name=table,oneof"`
}

func (*Descriptor_Table) MarshalTo

func (m *Descriptor_Table) MarshalTo(dAtA []byte) (int, error)

func (*Descriptor_Table) Size

func (m *Descriptor_Table) Size() (n int)

type EncDatum

type EncDatum struct {
	Type ColumnType

	// Decoded datum.
	Datum parser.Datum
	// contains filtered or unexported fields
}

EncDatum represents a datum that is "backed" by an encoding and/or by a parser.Datum. It allows "passing through" a Datum without decoding and reencoding.

func DatumToEncDatum

func DatumToEncDatum(ctyp ColumnType, d parser.Datum) EncDatum

DatumToEncDatum initializes an EncDatum with the given Datum.

func EncDatumFromBuffer

func EncDatumFromBuffer(typ ColumnType, enc DatumEncoding, buf []byte) (EncDatum, []byte, error)

EncDatumFromBuffer initializes an EncDatum with an encoding that is possibly followed by other data. Similar to EncDatumFromEncoded, except that this function figures out where the encoding stops and returns a slice for the rest of the buffer.

func EncDatumFromEncoded

func EncDatumFromEncoded(typ ColumnType, enc DatumEncoding, encoded []byte) EncDatum

EncDatumFromEncoded initializes an EncDatum with the given encoded value. The encoded value is stored as a shallow copy, so the caller must make sure the slice is not modified for the lifetime of the EncDatum. SetEncoded wipes the underlying Datum.

func MakeEncodedKeyVals

func MakeEncodedKeyVals(desc *TableDescriptor, columnIDs []ColumnID) ([]EncDatum, error)

MakeEncodedKeyVals returns a slice of EncDatums with the correct types for the given columns.

func RandEncDatum

func RandEncDatum(rng *rand.Rand) EncDatum

RandEncDatum generates a random EncDatum (of a random type).

func RandEncDatumSlice

func RandEncDatumSlice(rng *rand.Rand, numVals int) []EncDatum

RandEncDatumSlice generates a slice of random EncDatum values of the same random type.

func (*EncDatum) Compare

func (ed *EncDatum) Compare(
	a *DatumAlloc, evalCtx *parser.EvalContext, rhs *EncDatum,
) (int, error)

Compare returns:

-1 if the receiver is less than rhs,
0  if the receiver is equal to rhs,
+1 if the receiver is greater than rhs.

func (*EncDatum) Encode

func (ed *EncDatum) Encode(a *DatumAlloc, enc DatumEncoding, appendTo []byte) ([]byte, error)

Encode appends the encoded datum to the given slice using the requested encoding. Note: DatumEncoding_VALUE encodings are not unique because they can contain a column ID so they should not be used to test for equality.

func (*EncDatum) Encoding

func (ed *EncDatum) Encoding() (DatumEncoding, bool)

Encoding returns the encoding that is already available (the latter indicated by the bool return value).

func (*EncDatum) EnsureDecoded

func (ed *EncDatum) EnsureDecoded(a *DatumAlloc) error

EnsureDecoded ensures that the Datum field is set (decoding if it is not).

func (*EncDatum) IsNull

func (ed *EncDatum) IsNull() bool

IsNull returns true if the EncDatum value is NULL. Equivalent to checking if ed.Datum is DNull after calling EnsureDecoded.

func (*EncDatum) IsUnset

func (ed *EncDatum) IsUnset() bool

IsUnset returns true if SetEncoded or SetDatum were not called.

func (*EncDatum) String

func (ed *EncDatum) String() string

func (*EncDatum) UnsetDatum

func (ed *EncDatum) UnsetDatum()

UnsetDatum ensures subsequent IsUnset() calls return false.

type EncDatumRow

type EncDatumRow []EncDatum

EncDatumRow is a row of EncDatums.

func (EncDatumRow) Compare

func (r EncDatumRow) Compare(
	a *DatumAlloc, ordering ColumnOrdering, evalCtx *parser.EvalContext, rhs EncDatumRow,
) (int, error)

Compare returns the relative ordering of two EncDatumRows according to a ColumnOrdering:

-1 if the receiver comes before the rhs in the ordering,
+1 if the receiver comes after the rhs in the ordering,
0 if the relative order does not matter (i.e. the two rows have the same
  values for the columns in the ordering).

Note that a return value of 0 does not (in general) imply that the rows are equal; for example, rows [1 1 5] and [1 1 6] when compared against ordering {{0, asc}, {1, asc}} (i.e. ordered by first column and then by second column).

func (EncDatumRow) CompareToDatums

func (r EncDatumRow) CompareToDatums(
	a *DatumAlloc, ordering ColumnOrdering, evalCtx *parser.EvalContext, rhs parser.Datums,
) (int, error)

CompareToDatums is a version of Compare which compares against decoded Datums.

func (EncDatumRow) String

func (r EncDatumRow) String() string

type EncDatumRowAlloc

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

EncDatumRowAlloc is a helper that speeds up allocation of EncDatumRows (preferably of the same length).

func (*EncDatumRowAlloc) AllocRow

func (a *EncDatumRowAlloc) AllocRow(cols int) EncDatumRow

AllocRow allocates an EncDatumRow with the given number of columns.

func (*EncDatumRowAlloc) CopyRow

func (a *EncDatumRowAlloc) CopyRow(row EncDatumRow) EncDatumRow

CopyRow allocates an EncDatumRow and copies the given row to it.

type EncDatumRows

type EncDatumRows []EncDatumRow

EncDatumRows is a slice of EncDatumRows.

func (EncDatumRows) String

func (r EncDatumRows) String() string

type FKCheck

type FKCheck int

FKCheck indicates a kind of FK check (delete, insert, or both).

const (
	// CheckDeletes checks if rows reference a changed value.
	CheckDeletes FKCheck = iota
	// CheckInserts checks if a new/changed value references an existing row.
	CheckInserts
	// CheckUpdates checks all references (CheckDeletes+CheckInserts).
	CheckUpdates
)

type FamilyID

type FamilyID uint32

FamilyID is a custom type for ColumnFamilyDescriptor IDs.

type FkSpanCollector

type FkSpanCollector interface {
	CollectSpans() (reads roachpb.Spans, writes roachpb.Spans)
}

FkSpanCollector can collect the spans that foreign key validation will touch.

type ForeignKeyReference

type ForeignKeyReference struct {
	Table    ID                 `protobuf:"varint,1,opt,name=table,casttype=ID" json:"table"`
	Index    IndexID            `protobuf:"varint,2,opt,name=index,casttype=IndexID" json:"index"`
	Name     string             `protobuf:"bytes,3,opt,name=name" json:"name"`
	Validity ConstraintValidity `protobuf:"varint,4,opt,name=validity,enum=cockroach.sql.sqlbase.ConstraintValidity" json:"validity"`
	// If this FK only uses a prefix of the columns in its index, we record how
	// many to avoid spuriously counting the additional cols as used by this FK.
	SharedPrefixLen int32 `protobuf:"varint,5,opt,name=shared_prefix_len,json=sharedPrefixLen" json:"shared_prefix_len"`
}

func (*ForeignKeyReference) Descriptor

func (*ForeignKeyReference) Descriptor() ([]byte, []int)

func (ForeignKeyReference) IsSet

func (f ForeignKeyReference) IsSet() bool

IsSet returns whether or not the foreign key actually references a table.

func (*ForeignKeyReference) Marshal

func (m *ForeignKeyReference) Marshal() (dAtA []byte, err error)

func (*ForeignKeyReference) MarshalTo

func (m *ForeignKeyReference) MarshalTo(dAtA []byte) (int, error)

func (*ForeignKeyReference) ProtoMessage

func (*ForeignKeyReference) ProtoMessage()

func (*ForeignKeyReference) Reset

func (m *ForeignKeyReference) Reset()

func (*ForeignKeyReference) Size

func (m *ForeignKeyReference) Size() (n int)

func (*ForeignKeyReference) String

func (m *ForeignKeyReference) String() string

func (*ForeignKeyReference) Unmarshal

func (m *ForeignKeyReference) Unmarshal(dAtA []byte) error

type FormatVersion

type FormatVersion uint32

FormatVersion is a custom type for TableDescriptor versions of the sql to key:value mapping.

const (

	// BaseFormatVersion corresponds to the encoding described in
	// https://www.cockroachlabs.com/blog/sql-in-cockroachdb-mapping-table-data-to-key-value-storage/.
	BaseFormatVersion FormatVersion
	// FamilyFormatVersion corresponds to the encoding described in
	// https://github.com/cockroachdb/cockroach/blob/master/docs/RFCS/sql_column_families.md
	FamilyFormatVersion
	// InterleavedFormatVersion corresponds to the encoding described in
	// https://github.com/cockroachdb/cockroach/blob/master/docs/RFCS/sql_interleaved_tables.md
	InterleavedFormatVersion
)

func (FormatVersion) String

func (i FormatVersion) String() string

type ID

type ID parser.ID

ID is a custom type for {Database,Table}Descriptor IDs.

type IDs

type IDs []ID

IDs is a sortable list of IDs.

func (IDs) Len

func (ids IDs) Len() int

func (IDs) Less

func (ids IDs) Less(i, j int) bool

func (IDs) Swap

func (ids IDs) Swap(i, j int)

type IndexDescriptor

type IndexDescriptor struct {
	Name   string  `protobuf:"bytes,1,opt,name=name" json:"name"`
	ID     IndexID `protobuf:"varint,2,opt,name=id,casttype=IndexID" json:"id"`
	Unique bool    `protobuf:"varint,3,opt,name=unique" json:"unique"`
	// An ordered list of column names of which the index is comprised; these
	// columns do not include any additional stored columns (which are in
	// stored_column_names). This list parallels the column_ids list.
	//
	// Note: if duplicating the storage of the column names here proves to be
	// prohibitive, we could clear this field before saving and reconstruct it
	// after loading.
	ColumnNames []string `protobuf:"bytes,4,rep,name=column_names,json=columnNames" json:"column_names,omitempty"`
	// The sort direction of each column in column_names.
	ColumnDirections []IndexDescriptor_Direction `` /* 156-byte string literal not displayed */
	// An ordered list of column names which the index stores in addition to the
	// columns which are explicitly part of the index (STORING clause). Only used
	// for secondary indexes.
	StoreColumnNames []string `protobuf:"bytes,5,rep,name=store_column_names,json=storeColumnNames" json:"store_column_names,omitempty"`
	// An ordered list of column IDs of which the index is comprised. This list
	// parallels the column_names list and does not include any additional stored
	// columns.
	ColumnIDs []ColumnID `protobuf:"varint,6,rep,name=column_ids,json=columnIds,casttype=ColumnID" json:"column_ids,omitempty"`
	// An ordered list of IDs for the additional columns associated with the
	// index:
	//  - implicit columns, which are all the primary key columns that are not
	//    already part of the index (i.e. PrimaryIndex.column_ids - column_ids).
	//  - stored columns (the columns in store_column_names) if this index uses the
	//    old STORING encoding (key-encoded data).
	//
	// Only used for secondary indexes.
	// For non-unique indexes, these columns are appended to the key.
	// For unique indexes, these columns are stored in the value.
	// This distinction exists because we want to be able to insert an entry using
	// a single conditional put on the key.
	ExtraColumnIDs []ColumnID `protobuf:"varint,7,rep,name=extra_column_ids,json=extraColumnIds,casttype=ColumnID" json:"extra_column_ids,omitempty"`
	// An ordered list of column IDs that parallels store_column_names if this
	// index uses the new STORING encoding (value-encoded data, always in the KV
	// value).
	StoreColumnIDs []ColumnID `protobuf:"varint,14,rep,name=store_column_ids,json=storeColumnIds,casttype=ColumnID" json:"store_column_ids,omitempty"`
	// CompositeColumnIDs contains an ordered list of IDs of columns that appear
	// in the index and have a composite encoding. Includes IDs from both
	// column_ids and extra_column_ids.
	CompositeColumnIDs []ColumnID            `` /* 130-byte string literal not displayed */
	ForeignKey         ForeignKeyReference   `protobuf:"bytes,9,opt,name=foreign_key,json=foreignKey" json:"foreign_key"`
	ReferencedBy       []ForeignKeyReference `protobuf:"bytes,10,rep,name=referenced_by,json=referencedBy" json:"referenced_by"`
	// Interleave, if it's not the zero value, describes how this index's data is
	// interleaved into another index's data.
	Interleave InterleaveDescriptor `protobuf:"bytes,11,opt,name=interleave" json:"interleave"`
	// InterleavedBy contains a reference to every table/index that is interleaved
	// into this one.
	InterleavedBy []ForeignKeyReference `protobuf:"bytes,12,rep,name=interleaved_by,json=interleavedBy" json:"interleaved_by"`
}

IndexDescriptor describes an index (primary or secondary).

Sample field values on the following table:

CREATE TABLE t (
  k1 INT NOT NULL,   // column ID: 1
  k2 INT NOT NULL,   // column ID: 2
  u INT NULL,        // column ID: 3
  v INT NULL,        // column ID: 4
  w INT NULL,        // column ID: 5
  CONSTRAINT "primary" PRIMARY KEY (k1, k2),
  INDEX k1v (k1, v) STORING (w),
  FAMILY "primary" (k1, k2, u, v, w)
)

Primary index:

name:                primary
id:                  1
unique:              true
column_names:        k1, k2
column_directions:   ASC, ASC
column_ids:          1, 2   // k1, k2

[old STORING encoding] Index k1v (k1, v) STORING (w):

name:                k1v
id:                  2
unique:              false
column_names:        k1, v
column_directions:   ASC, ASC
store_column_names:  w
column_ids:          1, 4   // k1, v
extra_column_ids:    2, 5   // k2, w

[new STORING encoding] Index k1v (k1, v) STORING (w):

name:                k1v
id:                  2
unique:              false
column_names:        k1, v
column_directions:   ASC, ASC
store_column_names:  w
column_ids:          1, 4   // k1, v
extra_column_ids:    2      // k2
store_column_ids:    5      // w

func (*IndexDescriptor) ContainsColumnID

func (desc *IndexDescriptor) ContainsColumnID(colID ColumnID) bool

ContainsColumnID returns true if the index descriptor contains the specified column ID either in its explicit column IDs, the extra column IDs, or the stored column IDs.

func (*IndexDescriptor) Descriptor

func (*IndexDescriptor) Descriptor() ([]byte, []int)

func (*IndexDescriptor) FillColumns

func (desc *IndexDescriptor) FillColumns(elems parser.IndexElemList) error

FillColumns sets the column names and directions in desc.

func (*IndexDescriptor) FullColumnIDs

func (desc *IndexDescriptor) FullColumnIDs() ([]ColumnID, []encoding.Direction)

FullColumnIDs returns the index column IDs including any extra (implicit or stored (old STORING encoding)) column IDs for non-unique indexes. It also returns the direction with which each column was encoded.

func (*IndexDescriptor) HasOldStoredColumns

func (desc *IndexDescriptor) HasOldStoredColumns() bool

HasOldStoredColumns returns whether the index has stored columns in the old format (data encoded the same way as if they were in an implicit column).

func (*IndexDescriptor) Marshal

func (m *IndexDescriptor) Marshal() (dAtA []byte, err error)

func (*IndexDescriptor) MarshalTo

func (m *IndexDescriptor) MarshalTo(dAtA []byte) (int, error)

func (*IndexDescriptor) ProtoMessage

func (*IndexDescriptor) ProtoMessage()

func (*IndexDescriptor) Reset

func (m *IndexDescriptor) Reset()

func (*IndexDescriptor) RunOverAllColumns

func (desc *IndexDescriptor) RunOverAllColumns(fn func(id ColumnID) error) error

RunOverAllColumns applies its argument fn to each of the column IDs in desc. If there is an error, that error is returned immediately.

func (*IndexDescriptor) Size

func (m *IndexDescriptor) Size() (n int)

func (*IndexDescriptor) String

func (m *IndexDescriptor) String() string

func (*IndexDescriptor) Unmarshal

func (m *IndexDescriptor) Unmarshal(dAtA []byte) error

type IndexDescriptor_Direction

type IndexDescriptor_Direction int32

The direction of a column in the index.

const (
	IndexDescriptor_ASC  IndexDescriptor_Direction = 0
	IndexDescriptor_DESC IndexDescriptor_Direction = 1
)

func (IndexDescriptor_Direction) Enum

func (IndexDescriptor_Direction) EnumDescriptor

func (IndexDescriptor_Direction) EnumDescriptor() ([]byte, []int)

func (IndexDescriptor_Direction) String

func (x IndexDescriptor_Direction) String() string

func (IndexDescriptor_Direction) ToEncodingDirection

func (dir IndexDescriptor_Direction) ToEncodingDirection() (encoding.Direction, error)

ToEncodingDirection converts a direction from the proto to an encoding.Direction.

func (*IndexDescriptor_Direction) UnmarshalJSON

func (x *IndexDescriptor_Direction) UnmarshalJSON(data []byte) error

type IndexEntry

type IndexEntry struct {
	Key   roachpb.Key
	Value roachpb.Value
}

IndexEntry represents an encoded key/value for an index entry.

func EncodeSecondaryIndex

func EncodeSecondaryIndex(
	tableDesc *TableDescriptor,
	secondaryIndex *IndexDescriptor,
	colMap map[ColumnID]int,
	values []parser.Datum,
) (IndexEntry, error)

EncodeSecondaryIndex encodes key/values for a secondary index. colMap maps ColumnIDs to indices in `values`.

type IndexID

type IndexID parser.IndexID

IndexID is a custom type for IndexDescriptor IDs.

func DecodeIndexKeyPrefix

func DecodeIndexKeyPrefix(
	a *DatumAlloc, desc *TableDescriptor, key []byte,
) (indexID IndexID, remaining []byte, err error)

DecodeIndexKeyPrefix decodes the prefix of an index key and returns the index id and a slice for the rest of the key.

Don't use this function in the scan "hot path".

type InterleaveDescriptor

type InterleaveDescriptor struct {
	// Ancestors contains the nesting of interleaves in the order they appear in
	// an encoded key. This means they are always in the far-to-near ancestor
	// order (e.g. grand-grand-parent, grand-parent, parent).
	Ancestors []InterleaveDescriptor_Ancestor `protobuf:"bytes,1,rep,name=ancestors" json:"ancestors"`
}

InterleaveDescriptor represents an index (either primary or secondary) that is interleaved into another table's data.

Example: Table 1 -> /a/b Table 2 -> /a/b/c Table 3 -> /a/b/c/d

There are two components (table 2 is the parent and table 1 is the grandparent) with shared lengths 2 and 1.

func (*InterleaveDescriptor) Descriptor

func (*InterleaveDescriptor) Descriptor() ([]byte, []int)

func (*InterleaveDescriptor) Marshal

func (m *InterleaveDescriptor) Marshal() (dAtA []byte, err error)

func (*InterleaveDescriptor) MarshalTo

func (m *InterleaveDescriptor) MarshalTo(dAtA []byte) (int, error)

func (*InterleaveDescriptor) ProtoMessage

func (*InterleaveDescriptor) ProtoMessage()

func (*InterleaveDescriptor) Reset

func (m *InterleaveDescriptor) Reset()

func (*InterleaveDescriptor) Size

func (m *InterleaveDescriptor) Size() (n int)

func (*InterleaveDescriptor) String

func (m *InterleaveDescriptor) String() string

func (*InterleaveDescriptor) Unmarshal

func (m *InterleaveDescriptor) Unmarshal(dAtA []byte) error

type InterleaveDescriptor_Ancestor

type InterleaveDescriptor_Ancestor struct {
	// TableID the ID of the table being interleaved into.
	TableID ID `protobuf:"varint,1,opt,name=table_id,json=tableId,casttype=ID" json:"table_id"`
	// IndexID is the ID of the parent index being interleaved into.
	IndexID IndexID `protobuf:"varint,2,opt,name=index_id,json=indexId,casttype=IndexID" json:"index_id"`
	// SharedPrefixLen is how many fields are shared between a parent and child
	// being interleaved, excluding any fields shared between parent and
	// grandparent. Thus, the sum of SharedPrefixLens in the components of an
	// InterleaveDescriptor is always strictly less than the number of fields
	// in the index being interleaved.
	SharedPrefixLen uint32 `protobuf:"varint,3,opt,name=shared_prefix_len,json=sharedPrefixLen" json:"shared_prefix_len"`
}

func (*InterleaveDescriptor_Ancestor) Descriptor

func (*InterleaveDescriptor_Ancestor) Descriptor() ([]byte, []int)

func (*InterleaveDescriptor_Ancestor) Marshal

func (m *InterleaveDescriptor_Ancestor) Marshal() (dAtA []byte, err error)

func (*InterleaveDescriptor_Ancestor) MarshalTo

func (m *InterleaveDescriptor_Ancestor) MarshalTo(dAtA []byte) (int, error)

func (*InterleaveDescriptor_Ancestor) ProtoMessage

func (*InterleaveDescriptor_Ancestor) ProtoMessage()

func (*InterleaveDescriptor_Ancestor) Reset

func (m *InterleaveDescriptor_Ancestor) Reset()

func (*InterleaveDescriptor_Ancestor) Size

func (m *InterleaveDescriptor_Ancestor) Size() (n int)

func (*InterleaveDescriptor_Ancestor) String

func (*InterleaveDescriptor_Ancestor) Unmarshal

func (m *InterleaveDescriptor_Ancestor) Unmarshal(dAtA []byte) error

type MetadataSchema

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

MetadataSchema is used to construct the initial sql schema for a new CockroachDB cluster being bootstrapped. Tables and databases must be installed on the underlying persistent storage before a cockroach store can start running correctly, thus requiring this special initialization.

func MakeMetadataSchema

func MakeMetadataSchema() MetadataSchema

MakeMetadataSchema constructs a new MetadataSchema value which constructs the "system" database.

func (*MetadataSchema) AddConfigDescriptor

func (ms *MetadataSchema) AddConfigDescriptor(parentID ID, desc DescriptorProto)

AddConfigDescriptor adds a new descriptor to the system schema. Used only for SystemConfig tables and databases.

func (*MetadataSchema) AddDescriptor

func (ms *MetadataSchema) AddDescriptor(parentID ID, desc DescriptorProto)

AddDescriptor adds a new non-config descriptor to the system schema.

func (MetadataSchema) GetInitialValues

func (ms MetadataSchema) GetInitialValues() []roachpb.KeyValue

GetInitialValues returns the set of initial K/V values which should be added to a bootstrapping CockroachDB cluster in order to create the tables contained in the schema.

func (MetadataSchema) InitialRangeCount

func (ms MetadataSchema) InitialRangeCount() int

InitialRangeCount returns the number of ranges that would be installed if this metadata schema were installed on a fresh cluster and nothing else. Most clusters will have additional ranges installed by migrations, so this function should be used when only a lower bound, and not an exact count, is needed. See server.ExpectedInitialRangeCount() for a count that includes migrations.

func (MetadataSchema) SystemConfigDescriptorCount

func (ms MetadataSchema) SystemConfigDescriptorCount() int

SystemConfigDescriptorCount returns the number of config descriptors that will be created by this schema. This value is needed to automate certain tests.

func (MetadataSchema) SystemDescriptorCount

func (ms MetadataSchema) SystemDescriptorCount() int

SystemDescriptorCount returns the number of descriptors that will be created by this schema. This value is needed to automate certain tests.

type MutationID

type MutationID uint32

MutationID is custom type for TableDescriptor mutations.

const InvalidMutationID MutationID = 0

InvalidMutationID is the uninitialised mutation id.

type PrivilegeDescriptor

type PrivilegeDescriptor struct {
	Users []UserPrivileges `protobuf:"bytes,1,rep,name=users" json:"users"`
}

PrivilegeDescriptor describes a list of users and attached privileges. The list should be sorted by user for fast access.

func NewDefaultPrivilegeDescriptor

func NewDefaultPrivilegeDescriptor() *PrivilegeDescriptor

NewDefaultPrivilegeDescriptor returns a privilege descriptor with ALL privileges for the root user.

func NewPrivilegeDescriptor

func NewPrivilegeDescriptor(user string, priv privilege.List) *PrivilegeDescriptor

NewPrivilegeDescriptor returns a privilege descriptor for the given user with the specified list of privileges.

func (PrivilegeDescriptor) AnyPrivilege

func (p PrivilegeDescriptor) AnyPrivilege(user string) bool

AnyPrivilege returns true if 'user' has any privilege on this descriptor.

func (PrivilegeDescriptor) CheckPrivilege

func (p PrivilegeDescriptor) CheckPrivilege(user string, priv privilege.Kind) bool

CheckPrivilege returns true if 'user' has 'privilege' on this descriptor.

func (*PrivilegeDescriptor) Descriptor

func (*PrivilegeDescriptor) Descriptor() ([]byte, []int)

func (*PrivilegeDescriptor) Grant

func (p *PrivilegeDescriptor) Grant(user string, privList privilege.List)

Grant adds new privileges to this descriptor for a given list of users. TODO(marc): if all privileges other than ALL are set, should we collapse them into ALL?

func (*PrivilegeDescriptor) Marshal

func (m *PrivilegeDescriptor) Marshal() (dAtA []byte, err error)

func (*PrivilegeDescriptor) MarshalTo

func (m *PrivilegeDescriptor) MarshalTo(dAtA []byte) (int, error)

func (*PrivilegeDescriptor) ProtoMessage

func (*PrivilegeDescriptor) ProtoMessage()

func (*PrivilegeDescriptor) Reset

func (m *PrivilegeDescriptor) Reset()

func (*PrivilegeDescriptor) Revoke

func (p *PrivilegeDescriptor) Revoke(user string, privList privilege.List)

Revoke removes privileges from this descriptor for a given list of users.

func (PrivilegeDescriptor) Show

Show returns the list of {username, privileges} sorted by username. 'privileges' is a string of comma-separated sorted privilege names.

func (*PrivilegeDescriptor) Size

func (m *PrivilegeDescriptor) Size() (n int)

func (*PrivilegeDescriptor) String

func (m *PrivilegeDescriptor) String() string

func (*PrivilegeDescriptor) Unmarshal

func (m *PrivilegeDescriptor) Unmarshal(dAtA []byte) error

func (PrivilegeDescriptor) Validate

func (p PrivilegeDescriptor) Validate(id ID) error

Validate is called when writing a database or table descriptor. It takes the descriptor ID which is used to determine if it belongs to a system descriptor, in which case the maximum set of allowed privileges is looked up and applied.

type ResultColumn

type ResultColumn struct {
	Name string
	Typ  parser.Type

	// If set, this is an implicit column; used internally.
	Hidden bool

	// If set, a value won't be produced for this column; used internally.
	Omitted bool
}

ResultColumn contains the name and type of a SQL "cell".

type ResultColumns

type ResultColumns []ResultColumn

ResultColumns is the type used throughout the sql module to describe the column types of a table.

func ResultColumnsFromColDescs

func ResultColumnsFromColDescs(colDescs []ColumnDescriptor) ResultColumns

ResultColumnsFromColDescs converts ColumnDescriptors to ResultColumns.

type RowContainer

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

RowContainer is a container for rows of Datums which tracks the approximate amount of memory allocated for row data. Rows must be added using AddRow(); once the work is done the Close() method must be called to release the allocated memory.

TODO(knz): this does not currently track the amount of memory used for the outer array of Datums references.

func MakeRowContainer

func MakeRowContainer(acc mon.BoundAccount, ti ColTypeInfo, rowCapacity int) RowContainer

MakeRowContainer is the non-pointer version of NewRowContainer, suitable to avoid unnecessary indirections when RowContainer is already part of an on-heap structure.

func NewRowContainer

func NewRowContainer(acc mon.BoundAccount, ti ColTypeInfo, rowCapacity int) *RowContainer

NewRowContainer allocates a new row container.

The acc argument indicates where to register memory allocations by this row container. Should probably be created by Session.makeBoundAccount() or Session.TxnState.makeBoundAccount().

The rowCapacity argument indicates how many rows are to be expected; it is used to pre-allocate the outer array of row references, in the fashion of Go's capacity argument to the make() function.

Note that we could, but do not (yet), report the size of the row container itself to the monitor in this constructor. This is because the various planNodes are not (yet) equipped to call Close() upon encountering errors in their constructor (all nodes initializing a RowContainer there) and SetLimitHint() (for sortNode which initializes a RowContainer there). This would be rather error-prone to implement consistently and hellishly difficult to test properly. The trade-off is that very large table schemas or column selections could cause unchecked and potentially dangerous memory growth.

func (*RowContainer) AddRow

func (c *RowContainer) AddRow(ctx context.Context, row parser.Datums) (parser.Datums, error)

AddRow attempts to insert a new row in the RowContainer. The row slice is not used directly: the Datum values inside the Datums are copied to internal storage. Returns an error if the allocation was denied by the MemoryMonitor.

func (*RowContainer) At

func (c *RowContainer) At(i int) parser.Datums

At accesses a row at a specific index.

func (*RowContainer) Clear

func (c *RowContainer) Clear(ctx context.Context)

Clear resets the container and releases the associated memory. This allows the RowContainer to be reused.

func (*RowContainer) Close

func (c *RowContainer) Close(ctx context.Context)

Close releases the memory associated with the RowContainer.

func (*RowContainer) Len

func (c *RowContainer) Len() int

Len reports the number of rows currently held in this RowContainer.

func (*RowContainer) PopFirst

func (c *RowContainer) PopFirst()

PopFirst discards the first row in the RowContainer.

func (*RowContainer) Replace

func (c *RowContainer) Replace(ctx context.Context, i int, newRow parser.Datums) error

Replace substitutes one row for another. This does query the MemoryMonitor to determine whether the new row fits the allowance.

func (*RowContainer) Swap

func (c *RowContainer) Swap(i, j int)

Swap exchanges two rows. Used for sorting.

type RowDeleter

type RowDeleter struct {
	Helper               rowHelper
	FetchCols            []ColumnDescriptor
	FetchColIDtoRowIndex map[ColumnID]int
	Fks                  fkDeleteHelper
	// contains filtered or unexported fields
}

RowDeleter abstracts the key/value operations for deleting table rows.

func MakeRowDeleter

func MakeRowDeleter(
	txn *client.Txn,
	tableDesc *TableDescriptor,
	fkTables TableLookupsByID,
	requestedCols []ColumnDescriptor,
	checkFKs bool,
) (RowDeleter, error)

MakeRowDeleter creates a RowDeleter for the given table.

The returned RowDeleter contains a FetchCols field that defines the expectation of which values are passed as values to DeleteRow. Any column passed in requestedCols will be included in FetchCols.

func (*RowDeleter) DeleteIndexRow

func (rd *RowDeleter) DeleteIndexRow(
	ctx context.Context, b *client.Batch, idx *IndexDescriptor, values []parser.Datum,
) error

DeleteIndexRow adds to the batch the kv operations necessary to delete a table row from the given index.

func (*RowDeleter) DeleteRow

func (rd *RowDeleter) DeleteRow(ctx context.Context, b *client.Batch, values []parser.Datum) error

DeleteRow adds to the batch the kv operations necessary to delete a table row with the given values.

type RowFetcher

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

RowFetcher handles fetching kvs and forming table rows. Usage:

var rf RowFetcher
err := rf.Init(..)
// Handle err
err := rf.StartScan(..)
// Handle err
for {
   row, err := rf.NextRow()
   // Handle err
   if row == nil {
      // Done
      break
   }
   // Process row
}

func (*RowFetcher) GetRangeInfo

func (rf *RowFetcher) GetRangeInfo() []roachpb.RangeInfo

GetRangeInfo returns information about the ranges where the rows came from. The RangeInfo's are deduped and not ordered.

func (*RowFetcher) Init

func (rf *RowFetcher) Init(
	desc *TableDescriptor,
	colIdxMap map[ColumnID]int,
	index *IndexDescriptor,
	reverse, isSecondaryIndex bool,
	cols []ColumnDescriptor,
	valNeededForCol []bool,
	returnRangeInfo bool,
) error

Init sets up a RowFetcher for a given table and index. If we are using a non-primary index, valNeededForCol can only be true for the columns in the index.

func (*RowFetcher) Key

func (rf *RowFetcher) Key() roachpb.Key

Key returns the next key (the key that follows the last returned row). Key returns nil when there are no more rows.

func (*RowFetcher) NextKey

func (rf *RowFetcher) NextKey(ctx context.Context) (rowDone bool, err error)

NextKey retrieves the next key/value and sets kv/kvEnd. Returns whether a row has been completed. TODO(andrei): change to return error

func (*RowFetcher) NextKeyDebug

func (rf *RowFetcher) NextKeyDebug(
	ctx context.Context,
) (prettyKey string, prettyValue string, row EncDatumRow, err error)

NextKeyDebug processes one key at a time and returns a pretty printed key and value. If we completed a row, the row is returned as well (see nextRow). If there are no more keys, prettyKey is "".

func (*RowFetcher) NextRow

func (rf *RowFetcher) NextRow(ctx context.Context) (EncDatumRow, error)

NextRow processes keys until we complete one row, which is returned as an EncDatumRow. The row contains one value per table column, regardless of the index used; values that are not needed (as per valNeededForCol) are nil. The EncDatumRow should not be modified and is only valid until the next call. When there are no more rows, the EncDatumRow is nil.

func (*RowFetcher) NextRowDecoded

func (rf *RowFetcher) NextRowDecoded(ctx context.Context) (parser.Datums, error)

NextRowDecoded calls NextRow and decodes the EncDatumRow into a Datums. The Datums should not be modified and is only valid until the next call. When there are no more rows, the Datums is nil.

func (*RowFetcher) ProcessKV

func (rf *RowFetcher) ProcessKV(
	kv client.KeyValue, debugStrings bool,
) (prettyKey string, prettyValue string, err error)

ProcessKV processes the given key/value, setting values in the row accordingly. If debugStrings is true, returns pretty printed key and value information in prettyKey/prettyValue (otherwise they are empty strings).

func (*RowFetcher) ReadIndexKey

func (rf *RowFetcher) ReadIndexKey(k roachpb.Key) (remaining []byte, ok bool, err error)

ReadIndexKey decodes an index key for the fetcher's table.

func (*RowFetcher) StartScan

func (rf *RowFetcher) StartScan(
	ctx context.Context, txn *client.Txn, spans roachpb.Spans, limitBatches bool, limitHint int64,
) error

StartScan initializes and starts the key-value scan. Can be used multiple times.

type RowInserter

type RowInserter struct {
	Helper                rowHelper
	InsertCols            []ColumnDescriptor
	InsertColIDtoRowIndex map[ColumnID]int
	Fks                   fkInsertHelper
	// contains filtered or unexported fields
}

RowInserter abstracts the key/value operations for inserting table rows.

func MakeRowInserter

func MakeRowInserter(
	txn *client.Txn,
	tableDesc *TableDescriptor,
	fkTables TableLookupsByID,
	insertCols []ColumnDescriptor,
	checkFKs bool,
) (RowInserter, error)

MakeRowInserter creates a RowInserter for the given table.

InsertCols must contain every column in the primary key.

func (*RowInserter) InsertRow

func (ri *RowInserter) InsertRow(
	ctx context.Context, b puter, values []parser.Datum, ignoreConflicts bool,
) error

InsertRow adds to the batch the kv operations necessary to insert a table row with the given values.

type RowUpdater

type RowUpdater struct {
	Helper               rowHelper
	FetchCols            []ColumnDescriptor
	FetchColIDtoRowIndex map[ColumnID]int
	UpdateCols           []ColumnDescriptor

	Fks fkUpdateHelper
	// contains filtered or unexported fields
}

RowUpdater abstracts the key/value operations for updating table rows.

func MakeRowUpdater

func MakeRowUpdater(
	txn *client.Txn,
	tableDesc *TableDescriptor,
	fkTables TableLookupsByID,
	updateCols []ColumnDescriptor,
	requestedCols []ColumnDescriptor,
	updateType rowUpdaterType,
) (RowUpdater, error)

MakeRowUpdater creates a RowUpdater for the given table.

UpdateCols are the columns being updated and correspond to the updateValues that will be passed to UpdateRow.

The returned RowUpdater contains a FetchCols field that defines the expectation of which values are passed as oldValues to UpdateRow. Any column passed in requestedCols will be included in FetchCols.

func (*RowUpdater) IsColumnOnlyUpdate

func (ru *RowUpdater) IsColumnOnlyUpdate() bool

IsColumnOnlyUpdate returns true if this RowUpdater is only updating column data (in contrast to updating the primary key or other indexes).

func (*RowUpdater) UpdateRow

func (ru *RowUpdater) UpdateRow(
	ctx context.Context, b *client.Batch, oldValues []parser.Datum, updateValues []parser.Datum,
) ([]parser.Datum, error)

UpdateRow adds to the batch the kv operations necessary to update a table row with the given values.

The row corresponding to oldValues is updated with the ones in updateValues. Note that updateValues only contains the ones that are changing.

The return value is only good until the next call to UpdateRow.

type TableDescriptor

type TableDescriptor struct {
	// The table name. It should be normalized using sqlbase.NormalizeName()
	// before comparing it.
	Name string `protobuf:"bytes,1,opt,name=name" json:"name"`
	ID   ID     `protobuf:"varint,3,opt,name=id,casttype=ID" json:"id"`
	// ID of the parent database.
	ParentID ID `protobuf:"varint,4,opt,name=parent_id,json=parentId,casttype=ID" json:"parent_id"`
	// Monotonically increasing version of the table descriptor.
	//
	// Invariants:
	// 1. not more than two subsequent versions of the table
	// descriptor can be leased. This is to make the system
	// easy to reason about, by permiting mutation state
	// changes (reflected in the next version), only when the existing
	// state (reflected in the current version) is present on all
	// outstanding unexpired leases.
	// 2. A schema change command (ALTER, RENAME, etc) never directly
	// increments the version. This allows the command to execute without
	// waiting for the entire cluster to converge to a single version
	// preventing weird deadlock situations. For instance, a transaction
	// with a schema change command might use a descriptor lease that is
	// at version: v - 1, and therefore deadlock when it tries to wait
	// for version: v, in the process of incrementing it to v + 1.
	// Therefore, a schema change command never increments the version,
	// and instead, sets the up_version boolean to notify the schema
	// changer execution engine that runs a future transaction to
	// increment the version.
	//
	// The schema change commands must therefore make *safe* modifications
	// to the table descriptor, such as scheduling long running schema
	// changes through mutations for future execution, or making simple
	// schema changes like RENAME that only modify the table descriptor in a
	// single transaction.
	//
	// Multiple schema changes in the same transaction set up_version.
	// The actual schema change execution that follows a schema change
	// command sees the up_version boolean set, and increments the
	// table version after ensuring that there are no unexpired leases
	// for version - 1. The schema change execution must increment
	// the version before executing future state changes, to ensure
	// that the scheduled mutations made by the original commands are
	// visible on all leases. Multiple schema change mutations can be
	// grouped together on a particular version increment.
	//
	// If schema change commands are safe to run without incrementing
	// the version, why do it later on? We increment the version
	// to ensure that all the nodes renew their leases with the new version
	// and get to see what the schema change command has done quickly.
	Version DescriptorVersion `protobuf:"varint,5,opt,name=version,casttype=DescriptorVersion" json:"version"`
	// See comment above.
	UpVersion bool `protobuf:"varint,6,opt,name=up_version,json=upVersion" json:"up_version"`
	// Last modification time of the table descriptor.
	ModificationTime cockroach_util_hlc.Timestamp `protobuf:"bytes,7,opt,name=modification_time,json=modificationTime" json:"modification_time"`
	Columns          []ColumnDescriptor           `protobuf:"bytes,8,rep,name=columns" json:"columns"`
	// next_column_id is used to ensure that deleted column ids are not reused.
	NextColumnID ColumnID                 `protobuf:"varint,9,opt,name=next_column_id,json=nextColumnId,casttype=ColumnID" json:"next_column_id"`
	Families     []ColumnFamilyDescriptor `protobuf:"bytes,22,rep,name=families" json:"families"`
	// next_family_id is used to ensure that deleted family ids are not reused.
	NextFamilyID FamilyID        `protobuf:"varint,23,opt,name=next_family_id,json=nextFamilyId,casttype=FamilyID" json:"next_family_id"`
	PrimaryIndex IndexDescriptor `protobuf:"bytes,10,opt,name=primary_index,json=primaryIndex" json:"primary_index"`
	// indexes are all the secondary indexes.
	Indexes []IndexDescriptor `protobuf:"bytes,11,rep,name=indexes" json:"indexes"`
	// next_index_id is used to ensure that deleted index ids are not reused.
	NextIndexID IndexID              `protobuf:"varint,12,opt,name=next_index_id,json=nextIndexId,casttype=IndexID" json:"next_index_id"`
	Privileges  *PrivilegeDescriptor `protobuf:"bytes,13,opt,name=privileges" json:"privileges,omitempty"`
	// Columns or indexes being added or deleted in a FIFO order.
	Mutations []DescriptorMutation               `protobuf:"bytes,14,rep,name=mutations" json:"mutations"`
	Lease     *TableDescriptor_SchemaChangeLease `protobuf:"bytes,15,opt,name=lease" json:"lease,omitempty"`
	// An id for the next group of mutations to be applied together.
	NextMutationID MutationID `protobuf:"varint,16,opt,name=next_mutation_id,json=nextMutationId,casttype=MutationID" json:"next_mutation_id"`
	// format_version declares which sql to key:value mapping is being used to
	// represent the data in this table.
	FormatVersion FormatVersion                      `protobuf:"varint,17,opt,name=format_version,json=formatVersion,casttype=FormatVersion" json:"format_version"`
	State         TableDescriptor_State              `protobuf:"varint,19,opt,name=state,enum=cockroach.sql.sqlbase.TableDescriptor_State" json:"state"`
	Checks        []*TableDescriptor_CheckConstraint `protobuf:"bytes,20,rep,name=checks" json:"checks,omitempty"`
	// This array is populated if the descriptor was renamed. If the descriptor is
	// renamed multiple times before the schema chage is processed, there will be
	// one element for each rename.
	// When this is detected in a schema change, the records for the old names are
	// deleted and this field is cleared.
	Renames []TableDescriptor_RenameInfo `protobuf:"bytes,21,rep,name=renames" json:"renames"`
	// The TableDescriptor is used for views in addition to tables. Views
	// use mostly the same fields as tables, but need to track the actual
	// query from the view definition as well.
	//
	// For now we only track a string representation of the query. This prevents
	// us from easily supporting things like renames of the dependencies of a
	// view. Eventually we'll want to switch to a semantic encoding of the query
	// that relies on IDs rather than names so that we can support renames of
	// fields relied on by the query, as Postgres does.
	//
	// Note: The presence of this field is used to determine whether or not
	// a TableDescriptor represents a view.
	ViewQuery string `protobuf:"bytes,24,opt,name=view_query,json=viewQuery" json:"view_query"`
	// The IDs of all relations that this depends on.
	// Only ever populated if this descriptor is for a view.
	DependsOn []ID `protobuf:"varint,25,rep,name=dependsOn,casttype=ID" json:"dependsOn,omitempty"`
	// All references to this table/view from other views in the system, tracked
	// down to the column/index so that we can restrict changes to them while
	// they're still being referred to.
	DependedOnBy []TableDescriptor_Reference `protobuf:"bytes,26,rep,name=dependedOnBy" json:"dependedOnBy"`
}

A TableDescriptor represents a table or view and is stored in a structured metadata key. The TableDescriptor has a globally-unique ID, while its member {Column,Index}Descriptors have locally-unique IDs.

func GetTableDescFromID

func GetTableDescFromID(ctx context.Context, txn *client.Txn, id ID) (*TableDescriptor, error)

GetTableDescFromID retrieves the table descriptor for the table ID passed in using an existing txn. Returns an error if the descriptor doesn't exist or if it exists and is not a table.

func GetTableDescriptor

func GetTableDescriptor(kvDB *client.DB, database string, table string) *TableDescriptor

GetTableDescriptor retrieves a table descriptor directly from the KV layer.

func (*TableDescriptor) AddColumn

func (desc *TableDescriptor) AddColumn(col ColumnDescriptor)

AddColumn adds a column to the table.

func (*TableDescriptor) AddColumnMutation

func (desc *TableDescriptor) AddColumnMutation(
	c ColumnDescriptor, direction DescriptorMutation_Direction,
)

AddColumnMutation adds a column mutation to desc.Mutations.

func (*TableDescriptor) AddColumnToFamilyMaybeCreate

func (desc *TableDescriptor) AddColumnToFamilyMaybeCreate(
	col string, family string, create bool, ifNotExists bool,
) error

AddColumnToFamilyMaybeCreate adds the specified column to the specified family. If it doesn't exist and create is true, creates it. If it does exist adds it unless "strict" create (`true` for create but `false` for ifNotExists) is specified.

AllocateIDs must be called before the TableDesciptor will be valid.

func (*TableDescriptor) AddFamily

func (desc *TableDescriptor) AddFamily(fam ColumnFamilyDescriptor)

AddFamily adds a family to the table.

func (*TableDescriptor) AddIndex

func (desc *TableDescriptor) AddIndex(idx IndexDescriptor, primary bool) error

AddIndex adds an index to the table.

func (*TableDescriptor) AddIndexMutation

func (desc *TableDescriptor) AddIndexMutation(
	idx IndexDescriptor, direction DescriptorMutation_Direction,
)

AddIndexMutation adds an index mutation to desc.Mutations.

func (*TableDescriptor) Adding

func (desc *TableDescriptor) Adding() bool

Adding returns true if the table is being added.

func (*TableDescriptor) AllIndexSpans

func (desc *TableDescriptor) AllIndexSpans() roachpb.Spans

AllIndexSpans returns the Spans for each index in the table, including those being added in the mutations.

func (*TableDescriptor) AllNonDropIndexes

func (desc *TableDescriptor) AllNonDropIndexes() []IndexDescriptor

AllNonDropIndexes returns all the indexes, including those being added in the mutations.

func (*TableDescriptor) AllocateIDs

func (desc *TableDescriptor) AllocateIDs() error

AllocateIDs allocates column, family, and index ids for any column, family, or index which has an ID of 0.

func (TableDescriptor) CheckUniqueConstraints

func (desc TableDescriptor) CheckUniqueConstraints() error

CheckUniqueConstraints returns a non-nil error if a descriptor contains two constraints with the same name.

func (*TableDescriptor) Descriptor

func (*TableDescriptor) Descriptor() ([]byte, []int)

func (*TableDescriptor) Dropped

func (desc *TableDescriptor) Dropped() bool

Dropped returns true if the table is being dropped.

func (*TableDescriptor) FinalizeMutation

func (desc *TableDescriptor) FinalizeMutation() (MutationID, error)

FinalizeMutation returns the id that has been used by mutations appended with addMutation() since the last time this function was called. Future mutations will use a new ID.

func (*TableDescriptor) FindActiveColumnByID

func (desc *TableDescriptor) FindActiveColumnByID(id ColumnID) (*ColumnDescriptor, error)

FindActiveColumnByID finds the active column with specified ID.

func (*TableDescriptor) FindActiveColumnByName

func (desc *TableDescriptor) FindActiveColumnByName(name parser.Name) (ColumnDescriptor, error)

FindActiveColumnByName calls FindActiveColumnByNormalizedName on a normalized argument.

func (*TableDescriptor) FindActiveColumnByNormalizedName

func (desc *TableDescriptor) FindActiveColumnByNormalizedName(
	normName string,
) (ColumnDescriptor, error)

FindActiveColumnByNormalizedName finds an active column with the specified normalized name.

func (*TableDescriptor) FindActiveColumnsByNames

func (desc *TableDescriptor) FindActiveColumnsByNames(
	names parser.NameList,
) ([]ColumnDescriptor, error)

FindActiveColumnsByNames finds all requested columns (in the requested order) or returns an error.

func (*TableDescriptor) FindColumnByID

func (desc *TableDescriptor) FindColumnByID(id ColumnID) (*ColumnDescriptor, error)

FindColumnByID finds the column with specified ID.

func (*TableDescriptor) FindColumnByName

func (desc *TableDescriptor) FindColumnByName(name parser.Name) (DescriptorStatus, int, error)

FindColumnByName calls FindColumnByNormalizedName with a normalized argument.

func (*TableDescriptor) FindColumnByNormalizedName

func (desc *TableDescriptor) FindColumnByNormalizedName(
	normName string,
) (DescriptorStatus, int, error)

FindColumnByNormalizedName finds the column with the specified name. It returns DescriptorStatus for the column, and an index into either the columns (status == DescriptorActive) or mutations (status == DescriptorIncomplete).

func (*TableDescriptor) FindFamilyByID

func (desc *TableDescriptor) FindFamilyByID(id FamilyID) (*ColumnFamilyDescriptor, error)

FindFamilyByID finds the family with specified ID.

func (*TableDescriptor) FindIndexByID

func (desc *TableDescriptor) FindIndexByID(id IndexID) (*IndexDescriptor, error)

FindIndexByID finds an index (active or inactive) with the specified ID. Must return a pointer to the IndexDescriptor in the TableDescriptor, so that callers can use returned values to modify the TableDesc.

func (*TableDescriptor) FindIndexByName

func (desc *TableDescriptor) FindIndexByName(name parser.Name) (DescriptorStatus, int, error)

FindIndexByName calls FindIndexByNormalizedName on a normalized argument.

func (*TableDescriptor) FindIndexByNormalizedName

func (desc *TableDescriptor) FindIndexByNormalizedName(
	normName string,
) (DescriptorStatus, int, error)

FindIndexByNormalizedName finds the index with the specified name. It returns DescriptorStatus for the index, and an index into either the indexes (status == DescriptorActive) or mutations (status == DescriptorIncomplete).

func (*TableDescriptor) ForeachNonDropIndex

func (desc *TableDescriptor) ForeachNonDropIndex(f func(*IndexDescriptor) error) error

ForeachNonDropIndex runs a function on all indexes, including those being added in the mutations.

func (*TableDescriptor) GetChecks

func (*TableDescriptor) GetColumns

func (m *TableDescriptor) GetColumns() []ColumnDescriptor

func (TableDescriptor) GetConstraintInfo

func (desc TableDescriptor) GetConstraintInfo(
	ctx context.Context, txn *client.Txn,
) (map[string]ConstraintDetail, error)

GetConstraintInfo returns a summary of all constraints on the table.

func (TableDescriptor) GetConstraintInfoWithLookup

func (desc TableDescriptor) GetConstraintInfoWithLookup(
	tableLookup tableLookupFn,
) (map[string]ConstraintDetail, error)

GetConstraintInfoWithLookup returns a summary of all constraints on the table using the provided function to fetch a TableDescriptor from an ID.

func (*TableDescriptor) GetDependedOnBy

func (m *TableDescriptor) GetDependedOnBy() []TableDescriptor_Reference

func (*TableDescriptor) GetDependsOn

func (m *TableDescriptor) GetDependsOn() []ID

func (TableDescriptor) GetDescMetadataKey

func (desc TableDescriptor) GetDescMetadataKey() roachpb.Key

GetDescMetadataKey returns the descriptor key for the table.

func (*TableDescriptor) GetFamilies

func (m *TableDescriptor) GetFamilies() []ColumnFamilyDescriptor

func (*TableDescriptor) GetFormatVersion

func (m *TableDescriptor) GetFormatVersion() FormatVersion

func (*TableDescriptor) GetID

func (m *TableDescriptor) GetID() ID

func (*TableDescriptor) GetIndexes

func (m *TableDescriptor) GetIndexes() []IndexDescriptor

func (*TableDescriptor) GetLease

func (*TableDescriptor) GetModificationTime

func (m *TableDescriptor) GetModificationTime() cockroach_util_hlc.Timestamp

func (*TableDescriptor) GetMutations

func (m *TableDescriptor) GetMutations() []DescriptorMutation

func (*TableDescriptor) GetName

func (m *TableDescriptor) GetName() string

func (TableDescriptor) GetNameMetadataKey

func (desc TableDescriptor) GetNameMetadataKey() roachpb.Key

GetNameMetadataKey returns the namespace key for the table.

func (*TableDescriptor) GetNextColumnID

func (m *TableDescriptor) GetNextColumnID() ColumnID

func (*TableDescriptor) GetNextFamilyID

func (m *TableDescriptor) GetNextFamilyID() FamilyID

func (*TableDescriptor) GetNextIndexID

func (m *TableDescriptor) GetNextIndexID() IndexID

func (*TableDescriptor) GetNextMutationID

func (m *TableDescriptor) GetNextMutationID() MutationID

func (*TableDescriptor) GetParentID

func (m *TableDescriptor) GetParentID() ID

func (*TableDescriptor) GetPrimaryIndex

func (m *TableDescriptor) GetPrimaryIndex() IndexDescriptor

func (*TableDescriptor) GetPrivileges

func (m *TableDescriptor) GetPrivileges() *PrivilegeDescriptor

func (*TableDescriptor) GetRenames

func (m *TableDescriptor) GetRenames() []TableDescriptor_RenameInfo

func (*TableDescriptor) GetState

func (m *TableDescriptor) GetState() TableDescriptor_State

func (*TableDescriptor) GetUpVersion

func (m *TableDescriptor) GetUpVersion() bool

func (*TableDescriptor) GetVersion

func (m *TableDescriptor) GetVersion() DescriptorVersion

func (*TableDescriptor) GetViewQuery

func (m *TableDescriptor) GetViewQuery() string

func (*TableDescriptor) IndexSpan

func (desc *TableDescriptor) IndexSpan(indexID IndexID) roachpb.Span

IndexSpan returns the Span that corresponds to an entire index; can be used for a full index scan.

func (*TableDescriptor) InvalidateFKConstraints

func (desc *TableDescriptor) InvalidateFKConstraints()

InvalidateFKConstraints sets all FK constraints to un-validated.

func (*TableDescriptor) IsEmpty

func (desc *TableDescriptor) IsEmpty() bool

IsEmpty checks if the descriptor is uninitialized.

func (*TableDescriptor) IsInterleaved

func (desc *TableDescriptor) IsInterleaved() bool

IsInterleaved returns true if any part of this this table is interleaved with another table's data.

func (*TableDescriptor) IsPhysicalTable

func (desc *TableDescriptor) IsPhysicalTable() bool

IsPhysicalTable returns true if the TableDescriptor actually describes a physical Table that needs to be stored in the kv layer, as opposed to a different resource like a view or a virtual table. Physical tables have primary keys, column families, and indexes (unlike virtual tables).

func (*TableDescriptor) IsTable

func (desc *TableDescriptor) IsTable() bool

IsTable returns true if the TableDescriptor actually describes a Table resource, as opposed to a different resource (like a View).

func (*TableDescriptor) IsView

func (desc *TableDescriptor) IsView() bool

IsView returns true if the TableDescriptor actually describes a View resource rather than a Table.

func (*TableDescriptor) IsVirtualTable

func (desc *TableDescriptor) IsVirtualTable() bool

IsVirtualTable returns true if the TableDescriptor describes a virtual Table (like the information_schema tables) and thus doesn't need to be physically stored.

func (*TableDescriptor) KeysPerRow

func (desc *TableDescriptor) KeysPerRow(indexID IndexID) int

KeysPerRow returns the maximum number of keys used to encode a row for the given index. For secondary indexes, we always only use one, but for primary indexes, we can encode up to one kv per column family.

func (*TableDescriptor) MakeMutationComplete

func (desc *TableDescriptor) MakeMutationComplete(m DescriptorMutation)

MakeMutationComplete updates the descriptor upon completion of a mutation.

func (*TableDescriptor) Marshal

func (m *TableDescriptor) Marshal() (dAtA []byte, err error)

func (*TableDescriptor) MarshalTo

func (m *TableDescriptor) MarshalTo(dAtA []byte) (int, error)

func (*TableDescriptor) MaybeUpgradeFormatVersion

func (desc *TableDescriptor) MaybeUpgradeFormatVersion() bool

MaybeUpgradeFormatVersion transforms the TableDescriptor to the latest FormatVersion (if it's not already there) and returns true if any changes were made.

func (*TableDescriptor) PrimaryIndexSpan

func (desc *TableDescriptor) PrimaryIndexSpan() roachpb.Span

PrimaryIndexSpan returns the Span that corresponds to the entire primary index; can be used for a full table scan.

func (*TableDescriptor) ProtoMessage

func (*TableDescriptor) ProtoMessage()

func (*TableDescriptor) RemoveColumnFromFamily

func (desc *TableDescriptor) RemoveColumnFromFamily(colID ColumnID)

RemoveColumnFromFamily removes a colID from the family it's assigned to.

func (*TableDescriptor) RenameColumnNormalized

func (desc *TableDescriptor) RenameColumnNormalized(colID ColumnID, newColName string)

RenameColumnNormalized updates all references to a column name in indexes and families.

func (*TableDescriptor) Renamed

func (desc *TableDescriptor) Renamed() bool

Renamed returns true if the table is being renamed.

func (*TableDescriptor) Reset

func (m *TableDescriptor) Reset()

func (*TableDescriptor) SetID

func (desc *TableDescriptor) SetID(id ID)

SetID implements the DescriptorProto interface.

func (*TableDescriptor) SetName

func (desc *TableDescriptor) SetName(name string)

SetName implements the DescriptorProto interface.

func (*TableDescriptor) SetUpVersion

func (desc *TableDescriptor) SetUpVersion() error

SetUpVersion sets the up_version marker on the table descriptor (see the proto

func (*TableDescriptor) Size

func (m *TableDescriptor) Size() (n int)

func (*TableDescriptor) String

func (m *TableDescriptor) String() string

func (*TableDescriptor) TableSpan

func (desc *TableDescriptor) TableSpan() roachpb.Span

TableSpan returns the Span that corresponds to the entire table.

func (*TableDescriptor) TypeName

func (desc *TableDescriptor) TypeName() string

TypeName returns the plain type of this descriptor.

func (*TableDescriptor) Unmarshal

func (m *TableDescriptor) Unmarshal(dAtA []byte) error

func (*TableDescriptor) Validate

func (desc *TableDescriptor) Validate(ctx context.Context, txn *client.Txn) error

Validate validates that the table descriptor is well formed. Checks include both single table and cross table invariants.

func (*TableDescriptor) ValidateTable

func (desc *TableDescriptor) ValidateTable() error

ValidateTable validates that the table descriptor is well formed. Checks include validating the table, column and index names, verifying that column names and index names are unique and verifying that column IDs and index IDs are consistent. Use Validate to validate that cross-table references are correct.

func (*TableDescriptor) VisibleColumns

func (desc *TableDescriptor) VisibleColumns() []ColumnDescriptor

VisibleColumns returns all non hidden columns.

type TableDescriptor_CheckConstraint

type TableDescriptor_CheckConstraint struct {
	Expr     string             `protobuf:"bytes,1,opt,name=expr" json:"expr"`
	Name     string             `protobuf:"bytes,2,opt,name=name" json:"name"`
	Validity ConstraintValidity `protobuf:"varint,3,opt,name=validity,enum=cockroach.sql.sqlbase.ConstraintValidity" json:"validity"`
}

func (*TableDescriptor_CheckConstraint) Descriptor

func (*TableDescriptor_CheckConstraint) Descriptor() ([]byte, []int)

func (*TableDescriptor_CheckConstraint) Marshal

func (m *TableDescriptor_CheckConstraint) Marshal() (dAtA []byte, err error)

func (*TableDescriptor_CheckConstraint) MarshalTo

func (m *TableDescriptor_CheckConstraint) MarshalTo(dAtA []byte) (int, error)

func (*TableDescriptor_CheckConstraint) ProtoMessage

func (*TableDescriptor_CheckConstraint) ProtoMessage()

func (*TableDescriptor_CheckConstraint) Reset

func (*TableDescriptor_CheckConstraint) Size

func (m *TableDescriptor_CheckConstraint) Size() (n int)

func (*TableDescriptor_CheckConstraint) String

func (*TableDescriptor_CheckConstraint) Unmarshal

func (m *TableDescriptor_CheckConstraint) Unmarshal(dAtA []byte) error

type TableDescriptor_Reference

type TableDescriptor_Reference struct {
	// The ID of the relation that depends on this one.
	ID ID `protobuf:"varint,1,opt,name=id,casttype=ID" json:"id"`
	// If applicable, the ID of this table's index that is refenced by the
	// dependent relation.
	IndexID IndexID `protobuf:"varint,2,opt,name=index_id,json=indexId,casttype=IndexID" json:"index_id"`
	// The IDs of this table's columns that are referenced by the dependent
	// relation.
	ColumnIDs []ColumnID `protobuf:"varint,3,rep,name=column_ids,json=columnIds,casttype=ColumnID" json:"column_ids,omitempty"`
}

func (*TableDescriptor_Reference) Descriptor

func (*TableDescriptor_Reference) Descriptor() ([]byte, []int)

func (*TableDescriptor_Reference) Marshal

func (m *TableDescriptor_Reference) Marshal() (dAtA []byte, err error)

func (*TableDescriptor_Reference) MarshalTo

func (m *TableDescriptor_Reference) MarshalTo(dAtA []byte) (int, error)

func (*TableDescriptor_Reference) ProtoMessage

func (*TableDescriptor_Reference) ProtoMessage()

func (*TableDescriptor_Reference) Reset

func (m *TableDescriptor_Reference) Reset()

func (*TableDescriptor_Reference) Size

func (m *TableDescriptor_Reference) Size() (n int)

func (*TableDescriptor_Reference) String

func (m *TableDescriptor_Reference) String() string

func (*TableDescriptor_Reference) Unmarshal

func (m *TableDescriptor_Reference) Unmarshal(dAtA []byte) error

type TableDescriptor_RenameInfo

type TableDescriptor_RenameInfo struct {
	// The database that the table belonged to before the rename (tables can be
	// renamed from one db to another).
	OldParentID ID     `protobuf:"varint,1,opt,name=old_parent_id,json=oldParentId,casttype=ID" json:"old_parent_id"`
	OldName     string `protobuf:"bytes,2,opt,name=old_name,json=oldName" json:"old_name"`
}

func (*TableDescriptor_RenameInfo) Descriptor

func (*TableDescriptor_RenameInfo) Descriptor() ([]byte, []int)

func (*TableDescriptor_RenameInfo) Marshal

func (m *TableDescriptor_RenameInfo) Marshal() (dAtA []byte, err error)

func (*TableDescriptor_RenameInfo) MarshalTo

func (m *TableDescriptor_RenameInfo) MarshalTo(dAtA []byte) (int, error)

func (*TableDescriptor_RenameInfo) ProtoMessage

func (*TableDescriptor_RenameInfo) ProtoMessage()

func (*TableDescriptor_RenameInfo) Reset

func (m *TableDescriptor_RenameInfo) Reset()

func (*TableDescriptor_RenameInfo) Size

func (m *TableDescriptor_RenameInfo) Size() (n int)

func (*TableDescriptor_RenameInfo) String

func (m *TableDescriptor_RenameInfo) String() string

func (*TableDescriptor_RenameInfo) Unmarshal

func (m *TableDescriptor_RenameInfo) Unmarshal(dAtA []byte) error

type TableDescriptor_SchemaChangeLease

type TableDescriptor_SchemaChangeLease struct {
	NodeID github_com_cockroachdb_cockroach_pkg_roachpb.NodeID `protobuf:"varint,1,opt,name=node_id,json=nodeId,casttype=github.com/cockroachdb/cockroach/pkg/roachpb.NodeID" json:"node_id"`
	// Nanoseconds since the Unix epoch.
	ExpirationTime int64 `protobuf:"varint,2,opt,name=expiration_time,json=expirationTime" json:"expiration_time"`
}

The schema update lease. A single goroutine across a cockroach cluster can own it, and will execute pending schema changes for this table. Since the execution of a pending schema change is through transactions, it is legal for more than one goroutine to attempt to execute it. This lease reduces write contention on the schema change.

func (*TableDescriptor_SchemaChangeLease) Descriptor

func (*TableDescriptor_SchemaChangeLease) Descriptor() ([]byte, []int)

func (*TableDescriptor_SchemaChangeLease) Marshal

func (m *TableDescriptor_SchemaChangeLease) Marshal() (dAtA []byte, err error)

func (*TableDescriptor_SchemaChangeLease) MarshalTo

func (m *TableDescriptor_SchemaChangeLease) MarshalTo(dAtA []byte) (int, error)

func (*TableDescriptor_SchemaChangeLease) ProtoMessage

func (*TableDescriptor_SchemaChangeLease) ProtoMessage()

func (*TableDescriptor_SchemaChangeLease) Reset

func (*TableDescriptor_SchemaChangeLease) Size

func (m *TableDescriptor_SchemaChangeLease) Size() (n int)

func (*TableDescriptor_SchemaChangeLease) String

func (*TableDescriptor_SchemaChangeLease) Unmarshal

func (m *TableDescriptor_SchemaChangeLease) Unmarshal(dAtA []byte) error

type TableDescriptor_State

type TableDescriptor_State int32

State is set if this TableDescriptor is in the process of being added or deleted. A non-public table descriptor cannot be leased. A schema changer observing DROP set will truncate the table and delete the descriptor. It is illegal to transition DROP to any other state.

const (
	// Not used.
	TableDescriptor_PUBLIC TableDescriptor_State = 0
	// Descriptor is being added.
	TableDescriptor_ADD TableDescriptor_State = 1
	// Descriptor is being dropped.
	TableDescriptor_DROP TableDescriptor_State = 2
)

func (TableDescriptor_State) Enum

func (TableDescriptor_State) EnumDescriptor

func (TableDescriptor_State) EnumDescriptor() ([]byte, []int)

func (TableDescriptor_State) String

func (x TableDescriptor_State) String() string

func (*TableDescriptor_State) UnmarshalJSON

func (x *TableDescriptor_State) UnmarshalJSON(data []byte) error

type TableLookup

type TableLookup struct {
	Table    *TableDescriptor
	IsAdding bool
}

TableLookup is the value type of TableLookupsByID: An optional table descriptor, populated when the table is public/leasable, and an IsAdding flag.

type TableLookupsByID

type TableLookupsByID map[ID]TableLookup

TableLookupsByID maps table IDs to looked up descriptors or, for tables that exist but are not yet public/leasable, entries with just the IsAdding flag.

func TablesNeededForFKs

func TablesNeededForFKs(table TableDescriptor, usage FKCheck) TableLookupsByID

TablesNeededForFKs calculates the IDs of the additional TableDescriptors that will be needed for FK checking delete and/or insert operations on `table`.

NB: 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.

type UserPrivilegeString

type UserPrivilegeString struct {
	User       string
	Privileges []string
}

UserPrivilegeString is a pair of strings describing the privileges for a given user.

func (UserPrivilegeString) PrivilegeString

func (u UserPrivilegeString) PrivilegeString() string

PrivilegeString returns a string of comma-separted privilege names.

type UserPrivileges

type UserPrivileges struct {
	User string `protobuf:"bytes,1,opt,name=user" json:"user"`
	// privileges is a bitfield of 1<<Privilege values.
	Privileges uint32 `protobuf:"varint,2,opt,name=privileges" json:"privileges"`
}

UserPrivileges describes the list of privileges available for a given user.

func (*UserPrivileges) Descriptor

func (*UserPrivileges) Descriptor() ([]byte, []int)

func (*UserPrivileges) Marshal

func (m *UserPrivileges) Marshal() (dAtA []byte, err error)

func (*UserPrivileges) MarshalTo

func (m *UserPrivileges) MarshalTo(dAtA []byte) (int, error)

func (*UserPrivileges) ProtoMessage

func (*UserPrivileges) ProtoMessage()

func (*UserPrivileges) Reset

func (m *UserPrivileges) Reset()

func (*UserPrivileges) Size

func (m *UserPrivileges) Size() (n int)

func (*UserPrivileges) String

func (m *UserPrivileges) String() string

func (*UserPrivileges) Unmarshal

func (m *UserPrivileges) Unmarshal(dAtA []byte) error

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL