d1

package
v0.37.0 Latest Latest
Warning

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

Go to latest
Published: Dec 3, 2026 License: MIT Imports: 21 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 d1 is the Cloudflare D1 backend of meta.Store. D1 has no wire protocol, so the backend speaks the HTTP and JSON protocol of docs/architecture.md "D1 proxy protocol" to a Worker that holds the D1 binding. Each write is one batch, which D1 runs as one transaction, and each read is one query.

Index

Constants

View Source
const DefaultMaxResponse = 16 << 20

DefaultMaxResponse is the largest response that a client reads. It is sized for one chunk of a manifest, base64 and JSON included, with room for the results of a batch.

View Source
const MaxInt = 1<<53 - 1

MaxInt is the largest integer that D1 holds exactly through its Worker binding, which reads and writes a JSON number as a double. The backend refuses an integer outside ±MaxInt.

View Source
const MaxManifest = 64 << 20

MaxManifest bounds a manifest. A swap stages it in requests of stageBytes each, so memory does not grow with it; the bound is the size that TestRealProxy runs through the Worker.

Variables

This section is empty.

Functions

func ParamCount

func ParamCount(sql string) int

ParamCount is the number of parameters that D1 needs to bind for sql: the highest number of a `?N` placeholder, or the count of bare `?` placeholders. D1 refuses a statement with another count.

func SplitScript

func SplitScript(script string) []string

SplitScript splits a script of plain statements at each semicolon outside a string, a quoted name and a comment. It does not read a trigger body, which holds semicolons; no migration has one.

Types

type Client

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

Client calls the proxy.

func NewClient

func NewClient(url, token string) *Client

NewClient returns a client of the proxy at url. It sends token as a bearer secret.

func (*Client) Batch

func (c *Client) Batch(ctx context.Context, stmts []Stmt) ([]Result, error)

Batch runs the statements as one transaction. It returns one result for each statement.

func (*Client) Query

func (c *Client) Query(ctx context.Context, s Stmt) (Result, error)

Query runs one statement and returns its rows.

type Option

type Option func(*Store)

Option changes how Open builds the store.

func MaxResponse

func MaxResponse(n int64) Option

MaxResponse sets the largest response that the store reads, in bytes.

func PageRows

func PageRows(n int) Option

PageRows sets the rows of one page of a listing, in place of the default of each listing.

type Result

type Result struct {
	Rows    []Row `json:"rows"`
	Changes int64 `json:"changes"`
}

Result is the answer to one statement: the rows that it returned, as arrays in column order, and the rows that it changed.

type Row

type Row []any

Row is one row of a result, in column order. A value is nil, a json.Number, a string or a {"$blob": base64} object.

func (Row) Scan

func (r Row) Scan(dst ...any) error

Scan stores the columns of the row in dst. A destination is *string, *int, *int64, *bool, *[]byte, *sql.NullString or *sql.NullInt64.

type StatementError

type StatementError struct{ Message string }

StatementError is a request that D1 refuses. D1 does not name the failing statement of a batch. No statement of the batch applied.

func (*StatementError) Error

func (e *StatementError) Error() string

type Stmt

type Stmt struct {
	SQL    string `json:"sql"`
	Params []any  `json:"params"`
}

Stmt is one SQL statement with its bound parameters.

func Q

func Q(sql string, args ...any) Stmt

Q builds a statement from sql and args. It drops the arguments that no placeholder of sql uses, because the statements of a batch share one argument list.

type Store

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

Store keeps the metadata in a D1 database that the proxy at the client's address serves.

func Open

func Open(ctx context.Context, url, token string, opts ...Option) (*Store, error)

Open connects to the proxy at url with the bearer secret token and applies the migrations that the database lacks.

func (*Store) AckLand

func (s *Store) AckLand(ctx context.Context, repo, id string) error

func (*Store) AcquireLandLease

func (s *Store) AcquireLandLease(ctx context.Context, repo, ref, owner string, now, until time.Time) (time.Time, error)

func (*Store) AcquireLease

func (s *Store) AcquireLease(ctx context.Context, id string, partition int, owner string, now, until time.Time) (meta.Lease, error)

func (*Store) AdvanceCursor

func (s *Store) AdvanceCursor(ctx context.Context, id string, partition int, owner string, cursor int64) error

func (*Store) BeginDelete

func (s *Store) BeginDelete(ctx context.Context, repo string, keys []string, now, staleBefore, retiredBefore time.Time) ([]string, error)

func (*Store) Claim

func (s *Store) Claim(ctx context.Context, id string, epoch uint64, owner, repo string) (meta.Workspace, error)

func (*Store) ClaimLands

func (s *Store) ClaimLands(ctx context.Context, repo, ref, owner string, now time.Time, limit int) ([]meta.LandItem, error)

func (*Store) Close

func (s *Store) Close() error

func (*Store) CreateRepo

func (s *Store) CreateRepo(ctx context.Context, r meta.Repo, repoText, commit string) error

func (*Store) CreateSubscription

func (s *Store) CreateSubscription(ctx context.Context, sub meta.Subscription) (meta.Subscription, error)

CreateSubscription is one batch. The cursor rows insert only while the subscription has none, which holds exactly when the first statement created it; the last statement reads the cursors back.

func (*Store) CreateUserToken

func (s *Store) CreateUserToken(ctx context.Context, hash string, t meta.UserToken) error

func (*Store) Delete

func (s *Store) Delete(ctx context.Context, id string) error

func (*Store) DeleteRef

func (s *Store) DeleteRef(ctx context.Context, ws string, epoch uint64, repo, name string, expect int64) error

func (*Store) DeleteSubscription

func (s *Store) DeleteSubscription(ctx context.Context, id string) error

func (*Store) EnqueueLand

func (s *Store) EnqueueLand(ctx context.Context, r meta.LandRequest, now time.Time) (meta.LandItem, error)

func (*Store) EventHeads

func (s *Store) EventHeads(ctx context.Context) ([]int64, error)

func (*Store) Events

func (s *Store) Events(ctx context.Context, partition int, after int64, limit int) ([]meta.Event, error)

Events reads the rows first and the floor second, so a prune between the reads gives ErrEventsPruned and never a silent gap.

func (*Store) FinishLands

func (s *Store) FinishLands(ctx context.Context, repo, ref, owner string, now time.Time, results []meta.LandDone) error

FinishLands is one batch: each item ends only while the lease holds, and the last statement reads the lease.

func (*Store) Flush

func (s *Store) Flush(ctx context.Context, ws string, epoch uint64, generation int64, prev, op, snapshot string) error

func (*Store) ForgetRetired

func (s *Store) ForgetRetired(ctx context.Context, repo string, keys []string) error

func (*Store) LandItem

func (s *Store) LandItem(ctx context.Context, repo, id string) (meta.LandItem, error)

func (*Store) LandLogSince

func (s *Store) LandLogSince(ctx context.Context, repo, ref, base string, limit int) ([]meta.LandLogRow, error)

LandLogSince plans the read with the row numbers and sizes only, and answers none when the rows after the base are more than limit. It then reads the rows in pages of at most landLogPageBytes of paths. A prune between the pages leaves a gap, which the read reports as none, as for a base that no row holds.

func (*Store) LandPending

func (s *Store) LandPending(ctx context.Context) ([]meta.LandKey, error)

func (*Store) LandRef

func (s *Store) LandRef(ctx context.Context, m meta.LandMove, owner string, now time.Time) (meta.Ref, error)

LandRef is one batch of conditional statements. Each carries the one condition applied: the event insert took its number in this batch. The last statement reads whether it applied, and the generation.

func (*Store) Live

func (s *Store) Live(ctx context.Context, id string, epoch uint64, repo string) error

func (*Store) Manifest

func (s *Store) Manifest(ctx context.Context, repo string) (meta.Manifest, error)

Manifest reads the published generation, the stage that holds it and its chunk count, then each chunk in its own query, so a response holds one chunk and a manifest of any size reads back. A published chunk never changes, and a swap only deletes it. A chunk that is gone, or a count that differs, means a swap ran in between, and the read starts again.

func (*Store) ManifestRepos

func (s *Store) ManifestRepos(ctx context.Context) ([]string, error)

ManifestRepos lists in pages by repo.

func (*Store) MergeDeleteRef

func (s *Store) MergeDeleteRef(ctx context.Context, repo, name string, expect int64) error

func (*Store) MergeRef

func (s *Store) MergeRef(ctx context.Context, repo, name string, expect int64, sha string) (meta.Ref, error)

func (*Store) OpHeads

func (s *Store) OpHeads(ctx context.Context, ws string) (meta.OpHeads, error)

func (*Store) Ping

func (s *Store) Ping(ctx context.Context) error

func (*Store) ProtectedRefs

func (s *Store) ProtectedRefs(ctx context.Context, repo string) ([]string, error)

func (*Store) PruneEvents

func (s *Store) PruneEvents(ctx context.Context, before time.Time) error

func (*Store) PruneLands

func (s *Store) PruneLands(ctx context.Context, before time.Time) error

func (*Store) Ref

func (s *Store) Ref(ctx context.Context, repo, name string) (meta.Ref, error)

func (*Store) Refs

func (s *Store) Refs(ctx context.Context, repo string) ([]meta.Ref, error)

Refs lists in pages by name.

func (*Store) ReleaseLandLease

func (s *Store) ReleaseLandLease(ctx context.Context, repo, ref, owner string) error

func (*Store) Repo

func (s *Store) Repo(ctx context.Context, path string) (meta.Repo, error)

func (*Store) Report

func (s *Store) Report(ctx context.Context, ws string, epoch uint64, repo string, generation int64, prev, op, snapshot string) error

func (*Store) Repos

func (s *Store) Repos(ctx context.Context) ([]meta.Repo, error)

Repos lists in pages by the key of its order, so no response holds all the repos. A repo that a writer adds or removes between two pages may be missed or not, as in any listing that is not one snapshot.

func (*Store) RetireFiles

func (s *Store) RetireFiles(ctx context.Context, repo string, keys []string, at time.Time) error

func (*Store) RetiredFiles

func (s *Store) RetiredFiles(ctx context.Context, repo string, retiredBefore, staleBefore time.Time, limit int) ([]meta.Retired, error)

func (*Store) RevokeUserToken

func (s *Store) RevokeUserToken(ctx context.Context, id string) error

func (*Store) SetProtectedRefs

func (s *Store) SetProtectedRefs(ctx context.Context, repo string, patterns []string) error

func (*Store) Subscriptions

func (s *Store) Subscriptions(ctx context.Context) ([]meta.Subscription, error)

Subscriptions lists in pages of subscriptions by creation order, and reads the cursors of each page in a second query, so a response holds neither every subscription nor the url of a subscription once for each partition.

func (*Store) SwapManifest

func (s *Store) SwapManifest(ctx context.Context, repo string, expect int64, body []byte) (int64, error)

SwapManifest stages the chunks under a random stage that no reader names, in requests of at most stageBytes of blobs, and then publishes with one small batch that binds no blob. The publish moves the head of the repo to the stage and deletes the chunks of the old stage, only while the generation is the expected one and every staged chunk is there. A batch rolls back on an error and never on a statement that changed no row, so each statement carries that condition, and a lost publish changes nothing that a reader sees. The writer then deletes its own stage; a stage that a crash or a failed delete leaves is removed by the next publish of the repo after maxStageAge.

func (*Store) SwapOpHeads

func (s *Store) SwapOpHeads(ctx context.Context, ws string, epoch uint64, repo string, expect int64, heads []string) (meta.OpHeads, error)

func (*Store) SwapRef

func (s *Store) SwapRef(ctx context.Context, ws string, epoch uint64, repo, name string, expect int64, sha string) (meta.Ref, error)

func (*Store) UpdateRef

func (s *Store) UpdateRef(ctx context.Context, repo, name, old, new, kind string) (meta.Ref, error)

UpdateRef compares on the commit of the ref instead of its generation. Its event insert has the condition of the write and runs first, as in swapRef.

func (*Store) UpdateSubscription

func (s *Store) UpdateSubscription(ctx context.Context, sub meta.Subscription) (meta.Subscription, error)

func (*Store) UserTokenByHash

func (s *Store) UserTokenByHash(ctx context.Context, hash string) (meta.UserToken, error)

func (*Store) UserTokens

func (s *Store) UserTokens(ctx context.Context) ([]meta.UserToken, error)

UserTokens lists in pages by the key of its order.

Jump to

Keyboard shortcuts

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