maxcompute

package
v0.21.0 Latest Latest
Warning

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

Go to latest
Published: Oct 29, 2026 License: MIT Imports: 33 Imported by: ? 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 maxcompute is a database/sql driver for Alibaba Cloud MaxCompute, which runs SQL over its REST API with HTTPS and XML. It registers the one name "maxcompute", and takes a DSN of the form maxcompute://<access key id>:<access key secret>@service.<region>.maxcompute.aliyun.com/<project> (D218).

db, err := sql.Open("maxcompute", "maxcompute://"+id+":"+secret+"@service.ap-southeast-5.maxcompute.aliyun.com/myproject")

The driver signs each request with signature version 4, and sends it to the host of the DSN only. It reads each result as CSV, and it types each column with the statement EXPLAIN OUTPUT (D219). A key of the DSN that starts with odps. is a setting of the server for every statement (D220). The server has no transaction, and it cuts a result at 10,000 rows with no sign. docs/MAXCOMPUTE.md holds what the driver knows about the server.

Example
package main

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

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

// count opens a project of MaxCompute and counts the rows of a table. The host
// names the region, and the path names the project. A key of the query that starts
// with odps. is a setting of the server for every statement.
func count(dsn string) (int64, error) {
	db, err := sql.Open(maxcompute.Name, dsn)
	if err != nil {
		return 0, fmt.Errorf("opening the project: %w", err)
	}
	defer db.Close()
	var n int64
	if err := db.QueryRowContext(context.Background(), "SELECT COUNT(*) FROM mytable").Scan(&n); err != nil {
		return 0, fmt.Errorf("counting the rows: %w", err)
	}
	return n, nil
}

func main() { //nolint:testableexamples // The example needs a project of MaxCompute.
	n, err := count("maxcompute://<access key id>:<access key secret>@service.ap-southeast-5.maxcompute.aliyun.com/myproject")
	if err != nil {
		log.Fatal(err)
	}
	fmt.Println(n)
}

Index

Examples

Constants

View Source
const (
	// ErrCanceled is the error of a statement that the server ended in the
	// state Cancelled, when the context of the statement did not end. Someone
	// else canceled it (recorded: "cancel: the result after the terminate").
	ErrCanceled dbimp.Error = "the statement was canceled"
	// ErrCut is the error of a result that ends before its end marker. After
	// a row, it comes wrapped with dbimp.ErrIncomplete (D21 and D107).
	ErrCut dbimp.Error = "the answer was cut short"
)

The sentinel errors of the driver. Each one wraps into a failure with errors.Is (D6).

View Source
const Name = "maxcompute"

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.

Types

type Config

type Config struct {
	// Host is the host of the service, such as
	// service.ap-southeast-5.maxcompute.aliyun.com.
	Host string
	// Port is the port of the server, 443 by default.
	Port int
	// ID and Secret are the access key id and the access key secret. They
	// are the user and the password of the DSN (D94).
	ID     string
	Secret string
	// Project is the project, which the path of the DSN holds.
	Project string
	// Region is the region that the signature names. A DSN with no key
	// region takes it from the host.
	Region string
	// Settings are the settings of the server that every statement sends,
	// such as odps.sql.submit.mode. Each key starts with odps. in the DSN.
	Settings map[string]string
	// Insecure makes the driver use HTTP and not HTTPS. A test of the driver
	// sets it, for a fake server on the local host. The DSN writes it as
	// tls=false.
	Insecure bool
}

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 maxcompute://<id>:<secret>@service.<region>.maxcompute.aliyun.com/<project> (D27, D35 and D218). The user is the access key id, the password is the secret, and the path is the project. The key region names the region of a host that is not of that form. The key tls is true by default, and tls=false makes the driver use HTTP. A key that starts with odps. is a setting of the server. Any other key is refused, and so is a repeated key.

func (*Config) FormatDSN

func (cfg *Config) FormatDSN() string

FormatDSN returns the DSN of cfg. ParseDSN reads it back as cfg, for a Config that ParseDSN filled.

type Connector

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

Connector opens connections to one project. 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, and fills each field that is zero with its default.

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.

func (*Connector) Driver

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

Driver satisfies driver.Connector.

type Driver

type Driver struct{}

Driver is the database/sql driver for MaxCompute.

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 XML body, such as ParseError or
	// SignatureNotMatch. It is empty for a task that failed.
	Code string
	// Message is the message, with no white space at its ends. For a task
	// that failed it starts with a code such as ODPS-0130131.
	Message string
	// RequestID is the id of the request, and empty when the body has none.
	RequestID string
	// contains filtered or unexported fields
}

Error is an error that MaxCompute reported. A statement that does not parse is HTTP 400 with an XML body of a code and a message. A statement that parses and then fails, such as one for a missing table, is HTTP 200 and 201 with a task in the state Failed, and the message in its result (recorded). A request that the server refuses is HTTP 403 or 404 with the same XML body.

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 ErrCanceled and the task ended in the state Cancelled. It reports whether target is dbimp.ErrAuthentication and the server refused the credential: HTTP 403 with the code SignatureNotMatch. Any other 403 is a missing permission, and it is not a refusal (D197).

func (*Error) Unwrap

func (err *Error) Unwrap() error

Unwrap returns the *dbimp.StatusError of the response, when the error came with an HTTP status that is not 2xx.

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 project of one statement, because a project is the database of MaxCompute. It is the same as WithProject.

func WithParameter

func WithParameter(name string, value any) Option

WithParameter sets a setting of the server for one statement, by its name, such as "odps.sql.timezone". It replaces the setting of the DSN with the same name (D109 and D220 item 3). The value is a string, a bool or a number, and the driver sends its text. A value of nil fails the statement with dbimp.ErrInvalidValue.

Example
package main

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

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

// run runs a statement of two parts in script mode, which the caller sets, because
// the driver never counts the statements of a query.
func run(dsn string) error {
	db, err := sql.Open(maxcompute.Name, dsn)
	if err != nil {
		return fmt.Errorf("opening the project: %w", err)
	}
	defer db.Close()
	script := maxcompute.WithParameter("odps.sql.submit.mode", "script")
	if _, err := db.ExecContext(context.Background(), "SET odps.sql.type.system.odps2=true; INSERT INTO t SELECT 1", script); err != nil {
		return fmt.Errorf("running the script: %w", err)
	}
	return nil
}

func main() { //nolint:testableexamples // The example needs a project of MaxCompute.
	if err := run("maxcompute://id:secret@service.ap-southeast-5.maxcompute.aliyun.com/myproject"); err != nil {
		log.Fatal(err)
	}
}

func WithProject

func WithProject(name string) Option

WithProject sets the project of one statement, in place of the project of the DSN.

func WithReadonly

func WithReadonly(readonly bool) Option

WithReadonly asks that the statement write nothing. The server has no such setting for one statement, so WithReadonly(true) fails the statement with dbimp.ErrNotSupported (D109).

func WithTimeout

func WithTimeout(d time.Duration) Option

WithTimeout sets the longest time that the driver waits for the statement, from the request to the end of the result. When it ends, the driver cancels the statement on the server, and the error is context.DeadlineExceeded. Zero waits as long as the context allows.

Jump to

Keyboard shortcuts

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