dbspec

package
v0.0.21 Latest Latest
Warning

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

Go to latest
Published: Nov 1, 2026 License: MIT Imports: 23 Imported by: 0

Documentation

Overview

Package dbspec parses, validates and emits dbspec documents, the schema language that docs/spec/dbspec.md specifies.

Parse reads one document together with the declared document set that its `use` lines name, validates every rule of the specification and returns either the document or every diagnostic in source order. Emit writes a document in its one canonical text, so Emit(Parse(s)) == s for canonical s.

Index

Constants

View Source
const (
	RuleSignature     = "signature"
	RuleHeader        = "header"
	RuleSyntax        = "syntax"
	RuleOrder         = "order"
	RuleNameFormat    = "name.format"
	RuleNameLength    = "name.length"
	RuleNameDuplicate = "name.duplicate"
	RuleType          = "type"
	RuleColumn        = "column"
	RuleKey           = "key"
	RuleForeignKey    = "foreign_key"
	RuleCheck         = "check"
	RuleSetting       = "setting"
	RuleUse           = "use"
	RuleDiagram       = "diagram"
	RuleLimit         = "limit"
	RuleEncoding      = "encoding"
)

Rules of a diagnostic, as listed in docs/spec/dbspec.md "Limits and errors".

View Source
const (
	RulePlan  = "plan"
	RuleChain = "chain"
)

RulePlan and RuleChain are the diagnostics of a plan document and a plan chain (docs/spec/plans.md).

View Source
const (
	PositionDocument     = "document"
	PositionUse          = "use"
	PositionUseTable     = "use_table"
	PositionTable        = "table"
	PositionColumn       = "column"
	PositionConstraint   = "constraint"
	PositionSetting      = "setting"
	PositionDiagram      = "diagram"
	PositionDiagramEntry = "diagram_entry"
)

The kinds of a Position.

View Source
const (
	RuleSetFile      = "set.file"
	RuleSetSymlink   = "set.symlink"
	RuleSetJSON      = "set.json"
	RuleSetSchema    = "set.schema"
	RuleSetKey       = "set.key"
	RuleSetEmpty     = "set.empty"
	RuleSetPath      = "set.path"
	RuleSetDuplicate = "set.duplicate"
)

The rules of the set reader (docs/spec/dbspec.md "Document sets").

View Source
const Code = "SCHEMA_INVALID"

Code is the error code of every dbspec diagnostic.

View Source
const RuleCompare = "compare"

RuleCompare is the diagnostic for a comparison target that is not schema text (docs/spec/plans.md "Comparison").

View Source
const RuleMermaid = "mermaid"

RuleMermaid is the diagnostic for a Mermaid line that import could not read (docs/spec/mermaid.md).

View Source
const SetFileName = "dbspec-set.json"

SetFileName is the only name of a set file.

View Source
const Signature = "dbspec "

Signature is the first bytes of every dbspec document file. The header `dbspec 1 <document>` starts with it (docs/spec/dbspec.md "Files").

Variables

This section is empty.

Functions

func CanonicalLiteral

func CanonicalLiteral(t Type, text string) (string, bool)

CanonicalLiteral returns the canonical text of text, a literal written as the default of a column of type t, or false when text is not a literal of t. A literal is one token on one line with no space around it: a number whose minus sign is attached, a word (true, false or now) or a quoted string. A text or bytes column has no literal.

func Chain

func Chain(plans []*Plan) ([]*Plan, []Diagnostic)

Chain returns the plans in the order in which they follow from empty. If there are no plans, it is the empty chain of a database that has no tables.

func CompareSchemas

func CompareSchemas(source, target *Document) ([]Difference, []Diagnostic)

CompareSchemas returns all differences from source to target without a plan. There is no rename; tables and columns are matched by name only. Both documents must be schema text, and for each one that is not, it returns a compare diagnostic in source, target order.

func Diff

func Diff(source *Document, p *Plan) ([]Change, []Diagnostic)

Diff returns the changes from the source schema (empty schema if nil) to the plan's target If the source schemaHash differs from the plan's from, it is a diagnostic.

func Emit

func Emit(document *Document) string

Emit writes document in canonical form (docs/spec/dbspec.md "Canonical form"). It writes the model as given and does not validate it; a document returned by Parse is valid and its literals are already in canonical form.

func EmitPlan

func EmitPlan(p *Plan) string

EmitPlan writes the plan as a canonical document: rename table, rename column, allow drop table, allow drop column, in that order, each in name order.

func ExternalDifferences

func ExternalDifferences(live *Document, documents []*Document) []string

ExternalDifferences checks that the tables the set uses from external documents exist in the database (docs/spec/dbspec.md "External documents"). live is the database introspected into a document. For each table used: it is a difference if the table is missing, if an external document's column is missing, if the type or null differs, if the primary key differs, or if a unique key has no column list, and the differences are returned in table, column order. It is nil if there are no external documents.

func Finalize

func Finalize(ctx context.Context, c Execer, dialect Dialect, plans []*Plan, now func() time.Time, events func(ApplyEvent) error) error

Finalize runs the finalize steps of all applied plans in chain order, deleting hidden tables and columns.

func ImportMermaid

func ImportMermaid(text, name string) (*Document, []Unsupported, []Diagnostic)

ImportMermaid reads a standard erDiagram as a dbspec document named name, and returns what it could not carry over (docs/spec/mermaid.md "Import"). A line that does not match the syntax is a diagnostic.

func InstalledDifferences

func InstalledDifferences(live *Document, unsupported []Unsupported, target *Document) []string

InstalledDifferences checks that the database equals the document set (docs/spec/schema.md "Schema installation"). live is the database of the connection, introspected into a document; unsupported is the objects that introspection could not read; target is the schema text document of the document set. Tables of the database that are not in the set are not compared. If a table of the set has an object that could not be read, that object is reported as "unsupported_<kind> <table>[.<name>]: <reason>"; otherwise all differences from the database's set tables up to the set are reported as "<kind> <table>[.<name>]". An empty list means they match.

func Introspect

func Introspect(ctx context.Context, q Querier, dialect Dialect, name string) (*Document, []Unsupported, error)

Introspect reads the connection's current database, schema, or main database and returns a dbspec document named name and the list of objects it could not read. The number of queries is unrelated to the number of tables. A query failure, or a catalog from which no document can be made, is an error.

func ManifestOf

func ManifestOf(documents []*Document) (*Manifest, []Diagnostic)

ManifestOf returns the manifest of the document set, whose documents are taken in document name order, or the diagnostics of an invalid set. The manifest text holds the owned documents; the external text holds, for each external document, the tables that owned documents use, with their columns, primary key, unique keys and the foreign keys between used tables; the schema text holds the owned tables and a use line for each external document they use; and manifestHash covers the manifest text followed by the external text.

func Parse

func Parse(text string, documents map[string]string) (*Document, []Position, []Diagnostic)

Parse parses and validates text. documents is the declared document set: each document name that a `use` line may name, mapped to its text. Parse returns the document, the positions of its declarations in source order (docs/spec/dbspec.md "Declaration positions") and nil diagnostics, or nil, nil and every diagnostic of the document ordered by line, column and rule; never both. An encoding, header or limit error stops parsing: it follows the diagnostics found before it, and later lines are not diagnosed.

func ParsePlan

func ParsePlan(text string) (*Plan, []Diagnostic)

ParsePlan reads a plan document. An invalid document is a diagnostic with its location.

func PlanSteps

func PlanSteps(source *Document, p *Plan, dialect Dialect) ([]PlanStep, []Diagnostic)

PlanSteps writes the plan's steps per dialect (docs/spec/plans.md "Steps"). source is the schema that the plan starts from; it is nil if the database is empty.

func ReadSet

func ReadSet(path string) (Set, []SetError)

ReadSet reads the set file at path (docs/spec/dbspec.md "Document sets"): the set file, its JSON, the normal form and the components of each listed path, and the bytes and identity of each listed file, in that order. It returns the listed files, or the errors ordered by step, then by path. It never checks the bytes of a listed file; the caller gives them to ReadBytes with their path.

func Recover

func Recover(ctx context.Context, c Execer, dialect Dialect, plans []*Plan, now func() time.Time, events func(ApplyEvent) error) error

Recover judges an interrupted plan from the effects in the catalog and carries it forward. If there is no interrupted plan, it changes nothing.

func RenderStatements

func RenderStatements(documents []*Document, dialect Dialect) ([]RenderedStatement, []Diagnostic)

RenderStatements writes the same statements, in the same order, as Render, and for each statement returns the table it creates or changes.

func Rollback

func Rollback(ctx context.Context, c Execer, dialect Dialect, plans []*Plan, now func() time.Time, events func(ApplyEvent) error) error

Rollback rolls the last plan in history back to step 0 with its rollback statements, and then deletes its row. If there is no row, it changes nothing.

Types

type Action

type Action string

Action is a foreign key action.

const (
	ActionRestrict Action = "restrict"
	ActionCascade  Action = "cascade"
	ActionSetNull  Action = "set_null"
)

The foreign key actions.

type Analysis

type Analysis struct {
	Document    *Document
	Positions   []Position
	Diagnostics []Diagnostic
	Tokens      []Token
}

Analysis is the result of Analyze: the result of Parse, unchanged, and the tokens of the text (docs/spec/dbspec.md "Syntax analysis").

func Analyze

func Analyze(text string, documents map[string]string) Analysis

Analyze parses text as Parse does and returns the result unchanged with the tokens of the text. A limit error yields no tokens (docs/spec/dbspec.md "Syntax analysis").

type ApplyError

type ApplyError struct {
	Code    string
	Plan    string
	Step    int
	Message string
	Err     error
}

ApplyError is a failure of the command. Code is one of locked, session, interrupted, drift, chain, failed, verify, irreversible, or nulls.

func (*ApplyError) Error

func (e *ApplyError) Error() string

func (*ApplyError) Unwrap

func (e *ApplyError) Unwrap() error

type ApplyEvent

type ApplyEvent struct {
	Kind      string
	Plan      string
	Step      int
	Steps     int
	Statement string
}

ApplyEvent is what apply, recover, rollback, and finalize report (docs/spec/plans.md "Apply"). Kind is one of plan, rollback, finalize, irreversible, statement, applied, verified, or done.

type ApplyResult added in v0.0.19

type ApplyResult struct {
	// Stopped is true when the events callback returned an error, which ended the run there. Stop is that error.
	Stopped bool
	Stop    error
	// Failure is the ApplyError that ended the run, when that error is the only failure of the run.
	Failure *ApplyError
}

ApplyResult is how an Apply run ended, apart from the error Apply returns.

func Apply

func Apply(ctx context.Context, c Execer, dialect Dialect, plans []*Plan, now func() time.Time, events func(ApplyEvent) error) (ApplyResult, error)

Apply applies, in chain order, the plans the database has not yet applied, up to the finalize step. It changes nothing on a database that is already applied to the end.

A stop by an event alone is reported by Stopped with a nil error, and an ApplyError alone is reported by Failure with a nil error. The error is non-nil for any other failure, and for a cleanup failure after a stop or a failure, which is returned joined with it.

type AuditSetting

type AuditSetting struct {
	Comments     []string
	History      string
	Column       string
	References   string
	Action       string
	Previous     string
	Tables       string
	TablesRecord string
	TablesName   string
	Exclude      []string
	Include      []string
}

AuditSetting is `audit into <history> column <column> references <table> action <column> previous <column> [tables <table> (<column>, <column>)] [exclude (<column>, ...) | include (<column>, ...)]`. Tables, TablesRecord and TablesName are the tables table and its record and name columns, all empty without the clause. Column is the column that holds the primary key of the audit record table that References names. It is the column that holds the key. If there is no list, Exclude and Include are nil, and a parsed setting has only one of them (docs/spec/dbspec.md "Audit").

func (*AuditSetting) Excluded

func (a *AuditSetting) Excluded(t *Table) []string

Excluded returns the columns of t that the audit trigger does not copy, in column order. This is the list that schema text writes.

func (*AuditSetting) Records

func (a *AuditSetting) Records(column string) bool

Records tells whether the audit trigger copies a column. Audit columns are always recorded, a column in the exclude list never is, and if there is an include list, only its columns are copied.

type Binary

type Binary struct {
	Op    string
	Left  Expr
	Right Expr
	// contains filtered or unexported fields
}

Binary is `<left> <op> <right>` for and, or and the comparisons.

type BlindIndexSetting

type BlindIndexSetting struct {
	Comments    []string
	AESColumn   string
	IndexColumn string
}

BlindIndexSetting is `blind_index <aes column> <index column>`.

type Change

type Change struct {
	Kind  string
	Table string
	Name  string
}

Change is one change of the diff (docs/spec/plans.md "Diff"). Table is the target name, and drop_table and drop_* objects use the source name.

type Check

type Check struct {
	Comments   []string
	Name       string
	Expression Expr
}

Check is a named check constraint.

type CheckboxSetting

type CheckboxSetting struct {
	Comments []string
	Column   string
	State    string
	Glyph    string
}

CheckboxSetting is the list glyph of one state.

type CodecSetting

type CodecSetting struct {
	Comments []string
	Column   string
	Stages   []string
}

CodecSetting is `codec <column> <stage> ...`.

type Column

type Column struct {
	Comments []string
	Name     string
	Type     Type
	Null     bool
	Identity bool
	// Default is nil when the column has no default.
	Default *Default
}

Column is one column line.

type ColumnName

type ColumnName struct{ Table, Name string }

ColumnName is the source table and column of `allow drop column <table>.<name>`.

type ColumnRef

type ColumnRef struct {
	Name string
	// contains filtered or unexported fields
}

ColumnRef refers to a column of the same table.

type ColumnRename

type ColumnRename struct{ Table, Old, New string }

ColumnRename is `rename column <table>.<old> <new>`, and Table is the target name.

type ColumnSetting

type ColumnSetting struct {
	Comments []string
	Column   string
}

ColumnSetting is a setting that names one column: `updated`, `soft_delete` or `aes_version`.

type Default

type Default struct {
	Now     bool
	Literal string
}

Default is a column default: Now for `default now`, otherwise Literal holds the literal in canonical form, such as 1.00 or 'pending'.

type Diagnostic

type Diagnostic struct {
	Rule    string
	Line    int
	Column  int
	Message string
}

Diagnostic is one SCHEMA_INVALID error: the rule it breaks, the 1-based line and column (in Unicode code points) of the offending token, and a message.

func Format

func Format(text string, documents map[string]string) (string, []Diagnostic)

Format returns the canonical text of a document with no diagnostic, and otherwise the diagnostics and no text: a document with a diagnostic is never rewritten (docs/spec/dbspec.md "Formatting").

func ReadBytes

func ReadBytes(name string, b []byte) (string, []Diagnostic)

ReadBytes checks the bytes of a dbspec document file that the caller read under its own rules, before parsing. name is the name the message uses for the file. Bytes that do not start with Signature give one RuleSignature diagnostic at line 1, column 1, with no text, and the message "<name> is not a dbspec document"; a byte that is not UTF-8 gives a diagnostic at the line and column of the first invalid byte with RuleEncoding and the message "<name> is not valid UTF-8". Other bytes become text as they are, with no diagnostic.

func ReadFile

func ReadFile(path string) (string, []Diagnostic, error)

ReadFile reads the dbspec document file at path, to parse, and checks its bytes with ReadBytes, using path as the name. A file that cannot be read returns the read error.

func Render

func Render(documents []*Document, dialect Dialect) ([]string, []Diagnostic)

Render writes the statements that create the tables of the document set in one dialect (docs/spec/dialects.md "Rendered statements"), or returns the diagnostics of an invalid set. A dialect other than the three constants is a programming error and panics.

type Diagram

type Diagram struct {
	Comments        []string
	Name            string
	Entries         []DiagramEntry
	ClosingComments []string
}

Diagram places tables for a view.

type DiagramEntry

type DiagramEntry struct {
	Comments []string
	Table    string
	X        int32
	Y        int32
}

DiagramEntry is `<table> at <x> <y>`.

type Dialect

type Dialect string

Dialect names a database whose statements Render writes.

const (
	DialectMySQL    Dialect = "mysql"
	DialectPostgres Dialect = "postgres"
	DialectSQLite   Dialect = "sqlite"
)

The dialects of docs/spec/dialects.md "Rendered statements".

type Difference

type Difference struct {
	Kind  string
	Table string
	Name  string
}

Difference is one difference between two schemas (docs/spec/plans.md "Comparison"). Name is the name of a column or object, and is an empty string for a table-level difference.

type Document

type Document struct {
	Name string
	// External means the document is not owned by the set; it is an external document that the owning document uses through use.
	// External documents are parsed and checked, but not rendered, installed, compared, or generated
	// (docs/spec/dbspec.md "Documents and use"). They do not appear in document text.
	External bool
	Uses     []Use
	Tables   []Table
	Diagrams []Diagram
	// TrailingComments are comment lines that no line follows.
	TrailingComments []string
}

Document is one parsed dbspec document. Slices keep document order; Emit applies the canonical order. Comments hold whole comment lines from `#` to the end of the line, attached to the line that follows them.

type Effect

type Effect struct {
	Kind    string
	Table   string
	Name    string
	Present bool
}

Effect is how to read, from the catalog or the table, whether a statement had its effect. Kind is one of table, column, index, constraint, trigger, function, sequence, rows, or repeat. Present is the state after the statement.

func (Effect) String

func (e Effect) String() string

String is the text form of docs/spec/plans.md "Effects".

type EntitySetting

type EntitySetting struct {
	Comments []string
	Name     string
}

EntitySetting is `entity <name>`.

type Execer

type Execer interface {
	Querier
	ExecContext(ctx context.Context, query string, args ...any) (sql.Result, error)
}

Execer is the one connection on which the command runs statements and reads the catalog. *sql.Conn satisfies it, and the command uses the lock and session settings only on that connection.

type Expr

type Expr interface {
	// contains filtered or unexported methods
}

Expr is a check predicate or its operand (docs/spec/dbspec.md "Checks"). The tree holds no parentheses; emission writes only the parentheses that an or inside an and requires.

type ForeignKey

type ForeignKey struct {
	Comments   []string
	Name       string
	Columns    []string
	Table      string
	References []string
	OnDelete   Action
	OnUpdate   Action
}

ForeignKey is a named foreign key from Columns to References of Table.

type HistorySetting

type HistorySetting struct {
	Comments []string
	Table    string
	Row      string
	From     string
	To       string
	At       string
}

HistorySetting is the history line of a state_machine. Row is the foreign key column of the history table, From, To, and At are the previous state, next state, and time columns of a state transition.

type ImmutableSetting

type ImmutableSetting struct {
	Comments []string
}

ImmutableSetting is `immutable`.

type In

type In struct {
	Operand Expr
	Negated bool
	List    []Literal
}

In is `<operand> [not] in (<literal>, ...)`.

type Index

type Index struct {
	Comments []string
	Name     string
	Columns  []IndexColumn
}

Index is a named index.

type IndexColumn

type IndexColumn struct {
	Name       string
	Descending bool
}

IndexColumn is one index column with its direction.

type IsNull

type IsNull struct {
	Operand Expr
	Negated bool
}

IsNull is `<operand> is [not] null`.

type KeyPrefixSetting

type KeyPrefixSetting struct {
	Comments []string
	Prefix   string
}

KeyPrefixSetting is `key_prefix '<p>'`: the assignment prefix of a character primary key.

type LimitSetting

type LimitSetting struct {
	Comments []string
	State    string
	Count    int64
}

LimitSetting is the limit line of a state_machine: rows of that state cannot exceed Count.

type Literal

type Literal struct {
	Text string
	// contains filtered or unexported fields
}

Literal is an integer, decimal, string, true or false literal in the canonical default form of the column it meets.

type Manifest

type Manifest struct {
	ManifestText string
	// ExternalText is the canonical text holding, for each external document, the tables that owned documents use,
	// with their columns, primary key, unique keys, the foreign keys between used tables and the indexes leading them.
	// It is empty if there are no external documents.
	ExternalText string
	SchemaText   string
	ManifestHash string
	SchemaHash   string
}

Manifest holds the manifest and schema texts of a document set and their hashes (docs/spec/dbspec.md, "Manifest and hashes").

type MarkSetting

type MarkSetting struct {
	Comments []string
	Column   string
}

MarkSetting is `markdown <column>`: a manifest-only mark of a prose column.

type NavigationSetting struct {
	Comments   []string
	ForeignKey string
	ChildName  string
	ParentName string
}

NavigationSetting is `navigation <foreign key> <child name> <parent name>`.

type NullCheck

type NullCheck struct {
	Table      string
	Column     string
	Default    string
	HasDefault bool
}

NullCheck is a column that the rollback returns to non-null. Column is its name in the applied plan; if HasDefault, Default is the SQL text of the source default.

type Plan

type Plan struct {
	Name          string
	From          string
	RenameTables  []TableRename
	RenameColumns []ColumnRename
	DropTables    []string
	DropColumns   []ColumnName
	// Schema is the document parsed from the target schema text, and To is its schemaHash.
	Schema *Document
	To     string
	// contains filtered or unexported fields
}

Plan is a parsed plan document. If From is an empty string, it starts from an empty database.

type PlanStep

type PlanStep struct {
	Statement    string
	Rollback     string
	Irreversible string
	Effect       Effect
	// Restore and RollbackRestore are the statements that run instead of Statement and Rollback when RestoreIf is true
	// (when a column that rollback hid and added is in the table).
	Restore         string
	RollbackRestore string
	RestoreIf       Effect
	NullChecks      []NullCheck
	Finalize        bool
}

PlanStep is one step of a plan (docs/spec/plans.md "Steps"). If Rollback is empty, it is a finalize step, or Irreversible gives the reason.

func AddTablesAndColumnsSteps

func AddTablesAndColumnsSteps(live *Document, unsupported []Unsupported, target *Document, dialect Dialect) (added []string, steps []PlanStep, differences []string)

AddTablesAndColumnsSteps writes the steps that the connection's addTablesAndColumns runs (docs/spec/schema.md "Adding tables and columns"). live is the connection's database, introspected document, unsupported is an object that introspection could not read, target is the document set's schema text document. Tables of the database that are not in the set are neither compared nor changed. For the database tables that exist in the database, the set's differences where the database lacks a table: create_table, and add_column for a column that is null or has a default, and add_index for non-unique indexes only, when the plan steps from the database's tables up to the set (docs/spec/plans.md "Steps"), ordered by table name Tables it creates are listed as "table", added columns as "table.column" in column order, then the added indexes are listed in index order as "table.index". Other differences are returned without a step in differences as "<kind> <table>[.<name>]", and a missing unique key can fail on existing rows, so it is returned with that reason.

type Position

type Position struct {
	Kind   string
	Path   []string
	Line   int
	Column int
}

Position is the place of one declaration of a parsed document (docs/spec/dbspec.md "Declaration positions"): its kind, its path of enclosing names and its own name, and the 1-based line and column, in Unicode code points, of its name token or, for a setting and the primary key, of its keyword.

type PrimaryKey

type PrimaryKey struct {
	Comments []string
	Columns  []string
}

PrimaryKey is the unnamed primary key of a table.

type Querier

type Querier interface {
	QueryContext(ctx context.Context, query string, args ...any) (*sql.Rows, error)
}

Querier is the connection on which introspection sends catalog queries. *sql.DB, *sql.Conn, and *sql.Tx satisfy it.

type QueryObserver

type QueryObserver interface {
	QueryEnded(query string, err error) error
}

QueryObserver, if the Querier implements it, is called for each catalog query when all its rows have been read or when reading fails. err is the query's error. The error that QueryEnded returns ends the introspection with that error.

type RenderedStatement

type RenderedStatement struct {
	SQL   string
	Table string
}

RenderedStatement is one statement of Render, and the table that the statement creates or changes.

type SelectExplicitSetting

type SelectExplicitSetting struct {
	Comments []string
	Columns  []string
}

SelectExplicitSetting is `select explicit <column> ...`.

type Set

type Set struct {
	Documents []SetFile
	External  []SetFile
}

Set is a document set read from its set file: the owned documents and the external documents, each in written order.

type SetDocument

type SetDocument struct {
	Name        string
	External    bool
	Document    *Document
	Positions   []Position
	Diagnostics []Diagnostic
}

SetDocument is the result of one text of a set (docs/spec/dbspec.md "Parsing a set"): the name that the parser reads from its header, empty when the header fails; whether the text is external; and what one parse of the text returns, its document and positions or its diagnostics.

func ParseSet

func ParseSet(owned, external []string) []SetDocument

ParseSet parses the texts of one document set (docs/spec/dbspec.md "Parsing a set") and returns one SetDocument per text, owned first, each in set order. Each text's name is the name the parser reads from its header; a text whose name an earlier text has is not parsed and carries the diagnostic name.duplicate. Every other text is parsed with the texts of all other named documents as the documents its use lines name.

type SetError

type SetError struct {
	Rule    string
	Path    string
	Message string
}

SetError is one error of the set reader: its rule, the path it concerns and a message that names that path.

func (SetError) Error

func (e SetError) Error() string

type SetFile

type SetFile struct {
	Path  string
	Bytes []byte
}

SetFile is one listed file of a document set: its joined path and its bytes.

type Settings

type Settings struct {
	Comments        []string
	Entity          *EntitySetting
	Updated         *ColumnSetting
	SoftDelete      *ColumnSetting
	SelectExplicit  *SelectExplicitSetting
	Codecs          []CodecSetting
	AESVersion      *ColumnSetting
	BlindIndexes    []BlindIndexSetting
	Navigations     []NavigationSetting
	Immutable       *ImmutableSetting
	Audit           *AuditSetting
	StateMachine    *StateMachineSetting
	Marks           []MarkSetting
	Store           *StoreSetting
	KeyPrefix       *KeyPrefixSetting
	Title           *ColumnSetting
	Body            *ColumnSetting
	Order           *ColumnSetting
	Checkboxes      []CheckboxSetting
	ClosingComments []string
}

Settings is the settings block of a table. A nil field or an empty slice is an absent setting. Codecs repeat per column, BlindIndexes per AES column and Navigations per foreign key.

type StateLineSetting

type StateLineSetting struct {
	Comments []string
	Initial  bool
	Terminal bool
	From     string
	To       string
	State    string
	Requires []string
}

StateLineSetting is a transition line, a terminal declaration line, or an initial declaration line.

type StateMachineSetting

type StateMachineSetting struct {
	Comments []string
	Column   string
	Lines    []StateLineSetting
	History  *HistorySetting
	Limits   []LimitSetting
}

StateMachineSetting is the state machine of one column. Its lines keep their declaration order.

type StoreSetting

type StoreSetting struct {
	Comments []string
	Kind     string
	Foreign  string
	Shape    string
	// Shard is the `shard <column> <period>` clause, or nil if there is no clause. The SQL backend does not read it.
	Shard *StoreShard
}

StoreSetting is the table's storage declaration. Kind is files, document, or block. For block, Foreign holds the foreign key name of the parent row; for document and block, Shape holds list or table.

type StoreShard

type StoreShard struct {
	Column string
	Period string
}

StoreShard is the time shard of the storage: Column is a non-null date or datetime column, and Period is year, month, or day.

type Table

type Table struct {
	Comments    []string
	Name        string
	Columns     []Column
	PrimaryKey  PrimaryKey
	Uniques     []Unique
	Indexes     []Index
	ForeignKeys []ForeignKey
	Checks      []Check
	// Settings is nil when the table has no settings block.
	Settings *Settings
	// ClosingComments precede the closing brace of the table.
	ClosingComments []string
}

Table is one table block.

type TableRename

type TableRename struct{ Old, New string }

TableRename is `rename table <old> <new>`.

type Token

type Token struct {
	Line  int
	Start int
	End   int
	Class string
}

Token is one token of the text: its 1-based line, the number of Unicode code points before it on the line, the number before the code point after it, and its class.

type Type

type Type struct {
	Kind      TypeKind
	Length    int
	Precision int
	Scale     int
}

Type is a column type with its parameters: Length for varchar(n), Precision and Scale for decimal(p,s), and Precision (fraction digits) for time(p) and datetime(p). Unused parameters are zero.

func (Type) String

func (t Type) String() string

String returns the canonical type text, such as decimal(13,2).

type TypeKind

type TypeKind string

TypeKind names a dbspec type.

const (
	TypeI16      TypeKind = "i16"
	TypeI32      TypeKind = "i32"
	TypeI64      TypeKind = "i64"
	TypeBool     TypeKind = "bool"
	TypeDecimal  TypeKind = "decimal"
	TypeF64      TypeKind = "f64"
	TypeVarchar  TypeKind = "varchar"
	TypeText     TypeKind = "text"
	TypeBytes    TypeKind = "bytes"
	TypeUUID     TypeKind = "uuid"
	TypeDate     TypeKind = "date"
	TypeTime     TypeKind = "time"
	TypeDatetime TypeKind = "datetime"
)

The dbspec types.

type Unique

type Unique struct {
	Comments []string
	Name     string
	Columns  []string
}

Unique is a named unique key; NULLs are distinct.

type Unsupported

type Unsupported struct {
	Kind   string
	Table  string
	Name   string
	Reason string
}

Unsupported is an object that introspection could not read as dbspec (docs/spec/dialects.md "Introspection"). Kind is one of column, index, unique, foreign_key, check, trigger, view, routine, sequence, event, partition, or table.

func ExportMermaid

func ExportMermaid(d *Document) (string, []Unsupported)

ExportMermaid writes one document as a standard erDiagram, and returns what the diagram could not hold and so left out, as [kind, table, name] (docs/spec/mermaid.md "Export").

type Use

type Use struct {
	Comments []string
	Document string
	Tables   []string
}

Use makes tables of another document of the declared set available as foreign key targets.

Jump to

Keyboard shortcuts

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