aicoded.dev

The SQL database

sqldb.Open(ctx) returns the app's own MySQL database as a *sql.DB. There is no DSN and no password: the app talks to its runner, which logs in to the database as the app's own user, whose grants reach only the app's database.

Declaring and opening it

Declare the database in the permission list:

data:
  - source: sqldb
    classes: [internal]

Without it, sqldb.Open fails with E-MAN-010. App code never opens a database itself: aicoded check refuses sql.Open, sql.OpenDB, sql.Register and db.Driver() (E-LINT-006). Open the database once, in OnStart, and share it with the pages through deps.Deps. The people example opens it in Start, which main passes to app.Main as OnStart:

// Start opens the database and the photo store, fills the users table when it is empty and reads
// the team's address.
func (d *Deps) Start(ctx context.Context) error {
	db, err := sqldb.Open(ctx)
	if err != nil {
		return err
	}
	if err := fill(ctx, db); err != nil {
		return err
	}
	photos, err := filestore.Open(ctx, "photos")
	if err != nil {
		return err
	}
	team, err := config.String(ctx, "team_address")
	if err != nil {
		return err
	}
	d.DB, d.Photos, d.TeamAddress = db, photos, team
	return nil
}
// main.go
func main() {
	d := deps.New()
	app.Main(app.Options{Handler: pages.NewHandler(d), OnStart: d.Start})
}

Tables

App code reads and writes rows; it never changes the schema. The app's tables come from its draft of schema changes, .aicoded/migration.sql, which stays out of git: aicoded dev and aicoded check apply it on your computer, aicoded publish sends it with the commit, and the platform applies it when the release rolls out. people's draft creates its one table:

-- The contacts tab compares a login with the viewer's Subject, so the column holds any Subject, of
-- at most 512 bytes, and compares exactly, with no case folding and no trailing-space padding, so
-- "Alice" and "alice " are not "alice".
CREATE TABLE users (
	id BIGINT AUTO_INCREMENT PRIMARY KEY,
	login VARCHAR(512) COLLATE utf8mb4_0900_bin NOT NULL UNIQUE,
	name VARCHAR(100) NOT NULL,
	age TINYINT UNSIGNED NOT NULL,
	team VARCHAR(40) NOT NULL,
	languages VARCHAR(100) NOT NULL,
	on_site BOOL NOT NULL,
	remote BOOL NOT NULL,
	shift TINYINT UNSIGNED NOT NULL,
	bio TEXT NOT NULL
);

A draft adds tables, indexes and columns; a destructive change, such as a dropped column, needs an approval. Schema changes lists what it may hold and what happens at publish and at release. The app's database user may only read and write rows, and aicoded check refuses CREATE, ALTER, DROP, RENAME and TRUNCATE in app code (E-LINT-013). fill fills the table, in one transaction, with sample rows when it is empty.

Queries

// User returns the user with login, or ErrNoUser.
func (d *Deps) User(ctx context.Context, login string) (User, error) {
	u, err := scan(d.DB.QueryRowContext(ctx, "SELECT "+columns+" FROM users WHERE login = ?", login))
	if errors.Is(err, sql.ErrNoRows) {
		return User{}, ErrNoUser
	}
	return u, err
}

The page then turns ErrNoUser into web.NotFound().

A list of values

Since the SQL is a constant, a list of values for IN cannot be written into it. Pass the list as one JSON array through one placeholder, and let MySQL's JSON_TABLE turn it into rows:

logins, err := json.Marshal(list) // list is a []string
if err != nil {
	return err
}
rows, err := d.DB.QueryContext(ctx, `SELECT login, name FROM users
	WHERE login IN (SELECT login FROM JSON_TABLE(?, '$[*]' COLUMNS (login VARCHAR(512) COLLATE utf8mb4_0900_bin PATH '$')) AS l)`,
	string(logins))

Give the JSON column the type of the column it is compared with. An empty or nil list matches no row.

What the runner refuses

The connection runs queries and prepared statements only. Changing the database user or the connection's options, replication commands and other administrative commands are refused, and the connection ends (E-SQL-001). The runner needs no TLS on it, since it never leaves the machine, and refuses a client that asks for TLS or speaks an old protocol (E-SQL-003); sqldb.Open sets the client up correctly. When the runner cannot log in to the database, the app gets E-SQL-002.

Traces

Every statement is a span: sql.query, sql.exec or sql.begin, with the attribute db.operation, the statement's first word, such as SELECT. Outside aicoded dev, a failed statement records the MySQL error number and state, such as MySQL error 1062 (23000), or the kind of any other error, never the statement or its values. See telemetry.

In aicoded dev

An app that declares sqldb needs mysql: in its workspace in dev.yaml: the admin DSN of a MySQL 8 server on this machine, over a Unix socket, 127.0.0.1 or ::1 (E-DEV-006, E-DEV-007).

workspaces:
  /absolute/path/to/apps:
    mysql: root:<password>@unix(/run/mysqld/mysqld.sock)/

aicoded dev creates the app's own database there, ac-dev-<app>, and two users, each with a new password on every start: the data user ac-dev-<app>, which the app logs in as and which reads and writes rows only, and the owner ao-dev-<app>, which applies the app's migrations and draft before the app starts. The admin user needs CREATE USER, and ALL PRIVILEGES … WITH GRANT OPTION on the apps' databases, including CREATE to create them (E-DEV-008). See aicoded dev.

aicoded check makes a new test database the same way for the app's tests, which open it with sqltest.Open(t) from aicoded.dev/framework/sqldb/sqltest, and drops it after. Without mysql: in dev.yaml, sqltest.Open skips the test.

See also

Markdown · Source on GitHub · framework f46741f