tablestore

package
v0.25.1 Latest Latest
Warning

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

Go to latest
Published: Nov 8, 2026 License: MIT Imports: 26 Imported by: 0 modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Overview

Package tablestore is a database/sql driver for Alibaba Cloud Tablestore, which runs SQL over its HTTPS API. It registers the one name "tablestore", and takes a DSN of the form tablestore://key:secret@instance.region.ots.aliyuncs.com/instance (D222).

db, err := sql.Open("tablestore", "tablestore://key:secret@myinstance.ap-southeast-5.ots.aliyuncs.com/myinstance")

A request and an answer are protobuf, and the rows of an answer are FlatBuffers. The driver writes both encodings with the standard library (D13 and D222). It signs each request with the first version of the signature, and it reads no credential from the environment or from a file (D7).

A statement is one call, SQLQuery. The server binds no parameter, so the driver writes each argument into the text of the statement (D34 and D224). The SQL works over a mapping table, which names a table of Tablestore. The server runs SELECT, INSERT, UPDATE and DELETE, and refuses a second statement in the same call. The columns of a result come with their types, and the driver reads each value by the type of its column (D223).

Tablestore has no transaction in SQL, so BeginTx fails with dbimp.ErrNotSupported (D20). docs/TABLESTORE.md holds what the driver knows about the server.

Example

Example maps a table, then writes and reads it with SQL. The server binds no argument, so the driver writes each argument into the text of the statement.

package main

import (
	"context"
	"database/sql"
	"fmt"
	"log"
)

// exampleDSN is the DSN of an instance. SQL maps a table that the API made, so an
// example starts from a table named orders that the API created with the key id.
const exampleDSN = "tablestore://key:secret@myinstance.ap-southeast-5.ots.aliyuncs.com/myinstance"

func main() { //nolint:testableexamples // The example needs an instance, so it has no output to check.
	if err := exampleQuery(context.Background()); err != nil {
		log.Fatal(err)
	}
}

func exampleQuery(ctx context.Context) error {
	db, err := sql.Open("tablestore", exampleDSN)
	if err != nil {
		return fmt.Errorf("opening the database: %w", err)
	}
	defer db.Close()
	if _, err := db.ExecContext(ctx, "CREATE TABLE orders (id BIGINT, name MEDIUMTEXT, placed DATETIME, PRIMARY KEY(id));"); err != nil {
		return fmt.Errorf("mapping the table: %w", err)
	}
	if _, err := db.ExecContext(ctx, "INSERT INTO orders (id, name) VALUES (?, ?)", int64(1), "first"); err != nil {
		return fmt.Errorf("inserting: %w", err)
	}
	var name string
	if err := db.QueryRowContext(ctx, "SELECT name FROM orders WHERE id = ?", int64(1)).Scan(&name); err != nil {
		return fmt.Errorf("selecting: %w", err)
	}
	fmt.Println(name)
	return nil
}

Index

Examples

Constants

View Source
const (
	ErrExists   dbimp.Error = "object already exists"
	ErrNotFound dbimp.Error = "object does not exist"
)

ErrExists and ErrNotFound are the errors of CreateTable, CreateIndex, DeleteTable, CreateSearchIndex, DeleteSearchIndex and ListSearchIndexes for an object that is there, and for an object that is not. An *Error matches them by its code (D225). The calls on search indexes get the code OTSParameterInvalid for a table that is not there, so ErrNotFound also matches that code with the text "table [x] does not exist" (D226).

View Source
const ErrNoCredentials dbimp.Error = "the configuration has no access key id or secret"

ErrNoCredentials is the error of a connector whose Config holds no access key id and no secret, because the driver reads no credential from the environment (D7 and D222).

View Source
const Name = "tablestore"

Name is the name that the driver registers with database/sql, and the scheme of its DSN.

Variables

This section is empty.

Functions

func WithOptions

func WithOptions(ctx context.Context, opts ...Option) context.Context

WithOptions returns a context that carries opts. Each statement started with the context applies them after the options of the DSN.

Example

ExampleWithOptions sets the options of every statement that a context starts. The server has no setting for a timeout, so the context is the way to bound a statement.

package main

import (
	"context"
	"database/sql"
	"fmt"
	"log"
	"time"

	"github.com/xo/dbimp/tablestore"
)

// exampleDSN is the DSN of an instance. SQL maps a table that the API made, so an
// example starts from a table named orders that the API created with the key id.
const exampleDSN = "tablestore://key:secret@myinstance.ap-southeast-5.ots.aliyuncs.com/myinstance"

func main() { //nolint:testableexamples // The example needs an instance, so it has no output to check.
	ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
	err := examplePing(tablestore.WithOptions(ctx, tablestore.WithDatabase("myinstance")))
	cancel()
	if err != nil {
		log.Fatal(err)
	}
}

func examplePing(ctx context.Context) error {
	db, err := sql.Open("tablestore", exampleDSN)
	if err != nil {
		return fmt.Errorf("opening the database: %w", err)
	}
	defer db.Close()
	return db.PingContext(ctx)
}

Types

type Column added in v0.22.0

type Column struct {
	Name string
	Type ColumnType
}

Column is a column of a table.

type ColumnType added in v0.22.0

type ColumnType uint8

ColumnType is the type of a column of a table that CreateTable makes.

const (
	Integer ColumnType = iota + 1
	Double
	Boolean
	String
	Binary
)

The types of a column. A primary key column is an Integer, a String or a Binary. A defined column can be any of the five.

func (ColumnType) String added in v0.22.0

func (t ColumnType) String() string

String satisfies fmt.Stringer.

type Config

type Config struct {
	// Host is the host of the endpoint, such as
	// instance.ap-southeast-5.ots.aliyuncs.com.
	Host string
	// Port is the port of the endpoint. Zero means the port of the scheme, 443
	// for HTTPS and 80 for HTTP.
	Port int
	// TLS is true to speak HTTPS. The DSN turns it on by default, and only a
	// test with a fake server turns it off.
	TLS bool
	// Instance is the instance of Tablestore that a statement runs in, which the
	// path of the DSN names. It is the first label of the host.
	Instance string
	// User is the access key id, and Password is the access key secret, which
	// the driver signs each request with (D94 and D222). A Config with no User
	// and no Password opens no connection, because the driver reads no
	// credential from the environment (D7).
	User     string
	Password string
}

Config is the configuration of a connector, which the DSN holds. The caller owns it (D7).

func ParseDSN

func ParseDSN(dsn string) (*Config, error)

ParseDSN parses a DSN of the form tablestore://key:secret@instance.region.ots.aliyuncs.com/instance (D27, D35 and D222). The path is the instance, with no further slash, and the DSN needs it. The only key is tls, which is true by default. The access key id and the secret are the user and the password of the URL. They can be left out, and then the Config has none and the connector refuses to connect (D7). Any other key, and a key that appears twice, is refused.

func (*Config) FormatDSN

func (cfg *Config) FormatDSN() string

FormatDSN returns the DSN of cfg. ParseDSN reads it back as cfg.

type Connector

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

Connector opens connections to one endpoint. It owns its transport, and every connection shares it. A caller can build one from a Config and open it with sql.OpenDB.

func NewConnector

func NewConnector(cfg Config) *Connector

NewConnector returns a Connector for cfg. The connector keeps a copy of cfg.

func (*Connector) Close

func (c *Connector) Close() error

Close closes the idle connections of the transport.

func (*Connector) Connect

func (c *Connector) Connect(context.Context) (driver.Conn, error)

Connect satisfies driver.Connector. A connection holds nothing on the server, so it sends no request. It fails when the Config has no credentials, because the driver reads none from the environment (D7).

func (*Connector) CreateIndex added in v0.22.0

func (c *Connector) CreateIndex(ctx context.Context, table string, ix Index, opts ...IndexOption) error

CreateIndex makes the index on a table that exists, and fills it with the rows that the table holds, unless the option WithBaseData asks for no rows. It fails with an error that matches ErrExists when the index is there (D225).

The statement SHOW INDEX lists the index only when the call used WithBaseData(false) and the table was mapped with CREATE TABLE after the index was made. DescribeTable names the index in every case.

func (*Connector) CreateSearchIndex added in v0.23.0

func (c *Connector) CreateSearchIndex(ctx context.Context, table string, ix SearchIndex, opts ...SearchIndexOption) error

CreateSearchIndex makes the search index on a table that exists. It sends one request, which fails with an error that matches ErrExists when the index is there. A table that is not there gives OTSParameterInvalid, and no error that matches ErrNotFound. With no option, a row of the index never expires (D226).

func (*Connector) CreateTable added in v0.22.0

func (c *Connector) CreateTable(ctx context.Context, t Table, opts ...TableOption) error

CreateTable makes the table. It sends one request, which fails with an error that matches ErrExists when the table is there. The options change what the table keeps: with none, a row never expires, the table keeps one version of a cell, and the reserved throughput is zero (D225).

func (*Connector) DeleteSearchIndex added in v0.23.0

func (c *Connector) DeleteSearchIndex(ctx context.Context, table, name string, opts ...DeleteOption) error

DeleteSearchIndex deletes the search index of a table. It fails with an error that matches ErrNotFound when the table has no such index, unless the option WithIfExists is given. A table that is not there also gives an error that matches ErrNotFound, but WithIfExists does not ignore it, because only a missing index is ignored (D226). DeleteTable refuses a table that has a search index, so a caller deletes each search index first (D226).

func (*Connector) DeleteTable added in v0.22.0

func (c *Connector) DeleteTable(ctx context.Context, name string, opts ...DeleteOption) error

DeleteTable deletes the table and its data, with the secondary indexes that it holds. It fails with an error that matches ErrNotFound when there is no such table, unless the option WithIfExists is given. The server refuses a table that has a search index, with OTSParameterInvalid, so a caller deletes each search index with DeleteSearchIndex first (D225 and D226).

func (*Connector) Driver

func (c *Connector) Driver() driver.Driver

Driver satisfies driver.Connector.

func (*Connector) ListSearchIndexes added in v0.23.0

func (c *Connector) ListSearchIndexes(ctx context.Context, table string) ([]string, error)

ListSearchIndexes returns the names of the search indexes of a table, in the order that the server gives, which is the order of their names. A table with none gives an empty list. A table that is not there gives an error that matches ErrNotFound (D226).

func (*Connector) ListTables added in v0.23.0

func (c *Connector) ListTables(ctx context.Context) ([]string, error)

ListTables returns the names of every table of the instance, in the order that the server gives. It includes a table that no mapping names, which SQL does not show (D226). The driver keeps the whole list in memory.

type DeleteOption added in v0.22.0

type DeleteOption = dbimp.Option[deleteOptions]

DeleteOption sets an option of DeleteTable.

func WithIfExists added in v0.22.0

func WithIfExists() DeleteOption

WithIfExists makes DeleteTable succeed for a table that is not there, as DROP TABLE IF EXISTS does in SQL.

type Driver

type Driver struct{}

Driver is the database/sql driver for Tablestore.

func (Driver) Open

func (Driver) Open(string) (driver.Conn, error)

Open satisfies driver.Driver. database/sql opens a connection through OpenConnector, and Open returns an error, because opening a connection needs a context.

func (Driver) OpenConnector

func (Driver) OpenConnector(dsn string) (driver.Connector, error)

OpenConnector satisfies driver.DriverContext. It parses the DSN.

type Error

type Error struct {
	// HTTPStatus is the status code of the response.
	HTTPStatus int
	// Code is the code of the error, such as OTSParameterInvalid.
	Code string
	// Message is the text of the error.
	Message string
	// RequestID is the id that the server gave the request, in the header
	// X-Ots-Requestid. It can be empty.
	RequestID string
	// contains filtered or unexported fields
}

Error is an error that Tablestore reported. A request that the server refuses answers HTTP 400 or 403 with a protobuf message that holds a code and a text, such as OTSParameterInvalid with the text of a syntax error (recorded: "a syntax error"). A request with no credentials answers HTTP 400 with the same two members as XML (recorded: "no credentials").

func (*Error) AuthenticationRefused added in v0.24.0

func (err *Error) AuthenticationRefused() bool

AuthenticationRefused reports whether the server refused the credential. It returns what Is reports for dbimp.ErrAuthentication, and a caller that does not import this module reads it through an interface of its own (D227).

func (*Error) ErrVerbose added in v0.25.0

func (err *Error) ErrVerbose(_ string) string

ErrVerbose returns the error as psql writes it for \errverbose: the code and the message on the first line, and then each field that the server sent, one on each line with its name in upper case. A caller that does not import this module reads it through an interface of its own (D231).

func (*Error) Error

func (err *Error) Error() string

Error satisfies the error interface.

func (*Error) Is

func (err *Error) Is(target error) bool

Is reports whether target is dbimp.ErrAuthentication and the server refused the credential (D197), or ErrExists or ErrNotFound and the code says so (D225).

func (*Error) Unwrap

func (err *Error) Unwrap() error

Unwrap returns the *dbimp.StatusError of the response.

type Index added in v0.22.0

type Index struct {
	Name    string
	Keys    []string
	Columns []string
	Sync    bool
}

Index is a global secondary index. Keys are the names of the columns that form the primary key of the index table, in order. Each is a defined column or a primary key column of the table. Columns are the names of the defined columns that the index table holds besides its key. The server fills the index table in the background, so a row can appear in it a moment after the write. A true Sync asks the server to update the index with each write, which the protocol has as the update mode of an index, and the server can refuse it for a global index (D225).

type IndexOption added in v0.22.0

type IndexOption = dbimp.Option[indexOptions]

IndexOption sets an option of CreateIndex.

func WithBaseData added in v0.22.0

func WithBaseData(include bool) IndexOption

WithBaseData says whether CreateIndex copies the rows that the table holds into the index. With no option it does.

type Option

type Option = dbimp.Option[options]

Option sets an option of one statement (D109). An option comes from the DSN, then from the context through WithOptions, then from an argument of the statement, and a later one wins.

func WithDatabase

func WithDatabase(name string) Option

WithDatabase sets the instance of one statement, as the path of the DSN does. The host of the DSN names the instance too, so a name that differs from the instance of the DSN fails the statement with dbimp.ErrNotSupported.

func WithParameter

func WithParameter(name string, value any) Option

WithParameter sets a member of SQLQueryRequest by its name. The driver sets sql_version (an integer, 1 by default) and search_token (a string, empty by default), and a value here replaces them. The member version is not open to the caller, because the driver reads FlatBuffers only (D223). Any other name fails the statement with dbimp.ErrInvalidValue.

Example

ExampleWithParameter sends the member sql_version of the request for one statement.

package main

import (
	"context"
	"database/sql"
	"fmt"
	"log"

	"github.com/xo/dbimp/tablestore"
)

// exampleDSN is the DSN of an instance. SQL maps a table that the API made, so an
// example starts from a table named orders that the API created with the key id.
const exampleDSN = "tablestore://key:secret@myinstance.ap-southeast-5.ots.aliyuncs.com/myinstance"

func main() { //nolint:testableexamples // The example needs an instance, so it has no output to check.
	if err := exampleParameter(context.Background()); err != nil {
		log.Fatal(err)
	}
}

func exampleParameter(ctx context.Context) error {
	db, err := sql.Open("tablestore", exampleDSN)
	if err != nil {
		return fmt.Errorf("opening the database: %w", err)
	}
	defer db.Close()
	var version string
	if err := db.QueryRowContext(ctx, "SELECT @@version", tablestore.WithParameter("sql_version", 1)).Scan(&version); err != nil {
		return fmt.Errorf("reading the version: %w", err)
	}
	fmt.Println(version)
	return nil
}

func WithReadonly

func WithReadonly(readonly bool) Option

WithReadonly asks that the statement write nothing. Tablestore has no setting that makes it refuse a write for one request, so WithReadonly(true) fails the statement with dbimp.ErrNotSupported. A policy that allows reads only makes a read-only principal.

func WithTimeout

func WithTimeout(d time.Duration) Option

WithTimeout sets the time that the server gives the statement. The server accepts the hint MAX_EXECUTION_TIME in the text, but a test did not show that it stops a statement, so a positive value fails the statement with dbimp.ErrNotSupported. The context of the statement is the way to bound it. Zero asks for nothing.

type SearchField added in v0.23.0

type SearchField struct {
	Name  string
	Type  SearchFieldType
	Sort  bool
	Store bool
}

SearchField is a field of a search index. The index of the field is always on. A true Sort lets a query sort and aggregate on the field, and a true Store keeps the value in the index so that a search can return it. The server turns Store off for a field that has Sort (D226). Name is a column of the table, but the server does not check that, and it makes an index for a name that no column has.

type SearchFieldType added in v0.23.0

type SearchFieldType uint8

SearchFieldType is the type of a field of a search index.

const (
	SearchLong SearchFieldType = iota + 1
	SearchDouble
	SearchBoolean
	SearchKeyword
	SearchText
)

The types of a field. A Text field uses the analyzer that the server picks when the request names none, which is the single word analyzer (D226).

func (SearchFieldType) String added in v0.23.0

func (t SearchFieldType) String() string

String satisfies fmt.Stringer.

type SearchIndex added in v0.23.0

type SearchIndex struct {
	Name   string
	Fields []SearchField
}

SearchIndex is a search index of a table. The server fills it from the rows of the table in the background, and the index is there at once, with the state "index is running" (D226).

type SearchIndexOption added in v0.23.0

type SearchIndexOption = dbimp.Option[searchOptions]

SearchIndexOption sets an option of CreateSearchIndex (D109 and D226).

func WithSearchTimeToLive added in v0.23.0

func WithSearchTimeToLive(d time.Duration) SearchIndexOption

WithSearchTimeToLive sets the time after which the server deletes a row from the index. The protocol counts whole seconds, so d must be a positive number of them. The server accepts a value of one day or more, and only for a table that refuses updates (WithAllowUpdate(false)). It refuses any other call with OTSParameterInvalid. With no option, a row of the index never expires.

type Table added in v0.22.0

type Table struct {
	Name    string
	Keys    []Column
	Columns []Column
	Indexes []Index
}

Table describes a table that CreateTable makes. Keys are the primary key columns, in order, and Columns are the defined columns, which a mapping table and an index can name. The table keeps one version of each cell and never expires a row (D225).

type TableOption added in v0.22.0

type TableOption = dbimp.Option[tableOptions]

TableOption sets an option of CreateTable (D109 and D225). The options are the settings of the request that a table can have, and a call with none keeps the defaults of D225.

func WithAllowUpdate added in v0.22.0

func WithAllowUpdate(allow bool) TableOption

WithAllowUpdate says whether the table accepts an update of a row. With no option, the server uses its own default, which is to accept it.

func WithDeviation added in v0.22.0

func WithDeviation(d time.Duration) TableOption

WithDeviation sets how far the version of a written cell can differ from the time of the server, which the protocol counts in whole seconds. d must be a positive number of them. With no option, the server uses its own default.

func WithLocalTransaction added in v0.22.0

func WithLocalTransaction(enable bool) TableOption

WithLocalTransaction turns on the local transactions of the table. With no option, they are off.

func WithMaxVersions added in v0.22.0

func WithMaxVersions(n int) TableOption

WithMaxVersions sets the number of versions of a cell that the table keeps, which is 1 with no option. It must be at least 1.

func WithReservedThroughput added in v0.22.0

func WithReservedThroughput(read, write int) TableOption

WithReservedThroughput sets the capacity units that the table reserves for reads and for writes, which are zero with no option. A value cannot be negative. An instance in the mode of capacity that the service bills by use refuses a value above zero.

func WithStream added in v0.22.0

func WithStream(d time.Duration) TableOption

WithStream turns on the stream of the table, and sets the time that the server keeps a record of it, which the protocol counts in whole hours. d must be a positive number of them. With no option, the table has no stream.

func WithTimeToLive added in v0.22.0

func WithTimeToLive(d time.Duration) TableOption

WithTimeToLive sets the time after which the server deletes a row. The protocol counts whole seconds, so d must be a positive number of them. The server accepts a value of one day or more, and refuses a smaller one with OTSParameterInvalid. With no option, a row never expires.

Jump to

Keyboard shortcuts

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