sql

package
v1.4.3 Latest Latest
Warning

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

Go to latest
Published: Nov 10, 2026 License: MIT Imports: 46 Imported by: 1 module, 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 sql is the SQL extension (SPEC §10.21, D23): "SQL Databases", id emetos.sql. It is the SQL language pack (the grammar and the language configuration in assets/, copied by scripts/update-assets.sh; the licenses are in third_party/ and NOTICE) and the driver of PostgreSQL, MySQL and MariaDB, SQLite and SQL Server for the "Databases" side bar (extensions/internal/dbconn): it connects through database/sql with the pure Go drivers (pgx, go-sql-driver/mysql, modernc.org/sqlite, go-mssqldb), browses the schema of a connection in the explorer and generates statements from it. extensions/sql/dialect holds what differs between the engines.

The pieces are a Hub (made once by extensions.All, shared by the window tabs: the Service that holds the open connections and the dbconn.Driver registered with the Databases hub) and the Extension of each window tab (the command and the events of the tab). The query editors, the results panel and the safety checks (SPEC §10.21 "Query editors", "The results panel", "Safety") are the queries of each window tab (queries.go, panel.go, complete.go, export.go): a Runner (run.go) keeps a session of the connection for each SQL editor, and dialect.Split and dialect.Classify cut a script into statements and say which only read.

Index

Constants

View Source
const (
	// OptionShowSystem makes the explorer list the databases and schemas the engine keeps for itself ("true").
	OptionShowSystem = "showSystem"
	// OptionConnectTimeout is how long a connection may take to open, in seconds.
	OptionConnectTimeout = "connectTimeout"
	// OptionInstance is the named instance of a SQL Server.
	OptionInstance = "instance"
	// OptionCreate lets SQLite create the file when it is not there ("true").
	OptionCreate = "create"
)

The names of the options (dbconn.Connection.Options) the SQL engines have.

View Source
const (
	// NodeDatabase, NodeSchema and NodeFolder are the levels above the objects: a database, a schema, and a group of objects of a
	// kind (Tables, Views, Functions, Procedures, Columns, Indexes, Foreign Keys).
	NodeDatabase = "database"
	NodeSchema   = "schema"
	NodeFolder   = "folder"
	// NodeTable, NodeView, NodeRoutine are objects; NodeColumn, NodeIndex and NodeForeignKey are what is inside a table.
	NodeTable      = "table"
	NodeView       = "view"
	NodeRoutine    = "routine"
	NodeColumn     = "column"
	NodeIndex      = "index"
	NodeForeignKey = "foreignKey"
	// NodeMore is the last row of a listing that was cut.
	NodeMore = "more"
)

The kinds of node (dbconn.Node.Kind) the explorer makes.

View Source
const (
	// RunQuery runs the selection or the statement under the cursor of the active SQL editor (Ctrl+Enter), and RunAllQueries the
	// whole script (Ctrl+Shift+Enter).
	RunQuery      = ID + ".run"
	RunAllQueries = ID + ".runAll"
	// CancelQuery stops the statement that runs in the editor.
	CancelQuery = ID + ".cancel"
	// BeginTransaction, CommitTransaction and RollbackTransaction control the transaction of the editor's session.
	BeginTransaction    = ID + ".begin"
	CommitTransaction   = ID + ".commit"
	RollbackTransaction = ID + ".rollback"
	// ChooseConnection binds the active SQL editor to a connection and a database.
	ChooseConnection = ID + ".selectConnection"
	// ExportResult writes the result that the panel shows to a file; its argument is "csv", "json" or "sql", or none to ask.
	ExportResult = ID + ".exportResult"
	// ViewID is the panel tab "Query Results".
	ViewID = ID + ".results"
	// SettingMaxRows is the rows a result set reads at first and by each Fetch More; SettingConfirmDestructive asks before DROP,
	// TRUNCATE, ALTER and a DELETE or UPDATE without WHERE.
	SettingMaxRows            = "sql.maxRows"
	SettingConfirmDestructive = "sql.confirmDestructive"
	// RunningKey is true while the editor whose results show is running something; InTransactionKey while the active editor has a
	// transaction open.
	RunningKey       = ID + ".running"
	InTransactionKey = ID + ".inTransaction"
	// TopicQueryFinished is published when a statement ends: {"connection": id, "ok": bool, "rows": n, "millis": n}. It carries no
	// SQL text and no values.
	TopicQueryFinished = ID + ".queryFinished"
	// ProblemsOwner is the owner of the markers of the errors of statements.
	ProblemsOwner = "sql"
)

The ids of the commands, the view, the setting names, the context keys and the events of the query editors (SPEC §10.21 "Query editors", "The results panel", "Safety").

View Source
const (
	// DefaultMaxRows is the number of rows a result set reads before it offers Fetch More: the setting sql.maxRows.
	DefaultMaxRows = 1000
	// MaxResultBytes bounds one result set in memory: reading stops there with a note, and Fetch More offers the rest only as far as
	// this room goes.
	MaxResultBytes = 64 << 20
)

The limits of what a run keeps (SPEC §10.21 "The results panel").

View Source
const (
	// NewQuery opens a query editor for a connection (SPEC §10.21 "Query editors"); its argument is {"connection": id}, or none to
	// choose among the open connections.
	NewQuery = ID + ".newQuery"
	// TopicConnected and TopicDisconnected are published, in every window tab, when a SQL connection is opened or closed:
	// {"connection": id}.
	TopicConnected    = ID + ".connected"
	TopicDisconnected = ID + ".disconnected"
)

The ids of the commands and events of the extension.

View Source
const ID = "emetos.sql"

ID is the id of the extension.

Variables

This section is empty.

Functions

func Engines

func Engines() []dbconn.Engine

Engines returns the engines of the SQL extension in the order the dialects are listed: how the forms of PostgreSQL, MySQL and MariaDB, SQLite and SQL Server look.

func FactoryOf

func FactoryOf(h *Hub) extension.Factory

FactoryOf makes the Factory of the extension over the hub. Every call makes an extension of its own.

func WriteInserts

func WriteInserts(ctx context.Context, w io.Writer, d dialect.Dialect, table string, exp *resultgrid.Export) error

WriteInserts writes the result as one INSERT statement for each row, with the columns of the result, the values written as the engine of d reads them (strings quoted, NULL, numbers, hex for binary data). table is the name of the table, written as a person types it: schema.table, with quotes if a name needs them; a name with no quotes is quoted by d. It stops when ctx ends. The errors have the tag SQLExportWriteFailed, or ResultExportCancelled.

Types

type Catalog

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

Catalog is what the completion of a query editor knows of the schema of one connection: the schemas, the tables and views of each, and the columns of the tables that were asked about. It reads the catalog with the dialect's queries the first time a thing is asked for and keeps the answer for a few minutes, so that typing in an editor never waits for the server twice. It is safe for use from several goroutines.

func (*Catalog) Columns

func (c *Catalog) Columns(ctx context.Context, ref dialect.Ref) ([]dialect.Column, error)

Columns lists the columns of a table or view.

func (*Catalog) Invalidate

func (c *Catalog) Invalidate()

Invalidate makes the catalog forget everything it read.

func (*Catalog) Objects

func (c *Catalog) Objects(ctx context.Context, database, schema string) ([]dialect.Object, error)

Objects lists the tables and views of a schema (of a database, for MySQL).

func (*Catalog) Schemas

func (c *Catalog) Schemas(ctx context.Context, database string) ([]string, error)

Schemas lists the schemas of a database (of the connection, when the engine has one level: PostgreSQL's and SQL Server's schemas, SQLite's attached files). An engine with no schema level (MySQL) gives none.

type Extension

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

Extension is the extension in one window tab.

func (*Extension) Activate

func (e *Extension) Activate(ctx context.Context, api extension.API) error

Activate implements extension.Extension: it gives the engines to the Databases view, starts the query editors of the tab, and publishes the events of the connections.

func (*Extension) Manifest

func (e *Extension) Manifest() extension.Manifest

Manifest implements extension.Extension: the language pack's, with the command.

type Hub

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

Hub is what the window tabs of Emetos share: the open connections and the driver for the Databases view. extensions.All makes one.

func NewHub

func NewHub(db *dbconn.Hub) *Hub

NewHub makes the hub over the hub of the Databases extension. It opens nothing.

func (*Hub) Service

func (h *Hub) Service() *Service

Service is where the open connections are; the explorer and the query editors use it.

type QueryError

type QueryError struct {
	// Message is what the server said, without the code; Code is its code ("42601", "1064", "208"), or empty.
	Message, Code string
	// Offset is where the error is in the text of the statement, in bytes, and Length how much of the text to mark; Offset is -1
	// when the server does not say where.
	Offset, Length int
}

QueryError is a statement that failed, as the user is told of it: the server's words, its code and, when the server says where, the place in the statement.

func (QueryError) Text

func (q QueryError) Text() string

Text is the error as one line: "42601: syntax error at or near "FROM"".

type ResultSet

type ResultSet struct {
	// Columns are the columns of the set.
	Columns []resultgrid.Column
	// Table holds the rows read so far; Fetch More appends to it.
	Table *resultgrid.Table
	// Note says why the set is not whole: the server has more rows than were read, or the set reached its bound.
	Note string
	// contains filtered or unexported fields
}

ResultSet is the rows a statement returned, as the grid shows them.

func (*ResultSet) Bytes

func (s *ResultSet) Bytes() int64

Bytes is the estimated memory of the rows of the set.

func (*ResultSet) More

func (s *ResultSet) More() bool

More says that the server has more rows that Fetch More can read.

func (*ResultSet) Release

func (s *ResultSet) Release()

Release drops the rows of the set and closes its cursor: the set is discarded.

type RunOptions

type RunOptions struct {
	// MaxRows is the rows of a result set read at first and by each Fetch More; DefaultMaxRows when 0.
	MaxRows int
	// MaxBytes bounds the memory of one result set; MaxResultBytes when 0.
	MaxBytes int64
	// Started is called, on the goroutine that runs, before a statement is sent: i is its index in the statements given.
	Started func(i int, st dialect.Statement)
	// Finished is called, on the goroutine that runs, when a statement is done, with everything it gave. The result is the caller's
	// from then on, except for Fetch More on the last set.
	Finished func(r *StatementResult)
}

RunOptions say how many rows a statement reads.

type Runner

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

Runner runs statements in a session of a connection, for one query editor: the session is taken when the first statement runs and kept, so that a transaction, a temporary table and the settings of the session are there for the next statement. It runs one thing at a time. It is safe for use from several goroutines; Cancel is meant to be called from another one than Run.

func (*Runner) Begin

func (r *Runner) Begin(ctx context.Context) error

Begin opens a transaction on the session. The errors have the tags SQLTransactionOpen, SQLRunnerBusy, SQLNotConnected and SQLTransactionFailed.

func (*Runner) Cancel

func (r *Runner) Cancel() error

Cancel stops the statement that is running. It does nothing when none is.

func (*Runner) Close

func (r *Runner) Close() (rolledBack bool, err error)

Close ends the session: an open transaction is rolled back first, and the connection goes back to the pool. rolledBack tells that there was a transaction. The runner can be used again; it takes a new session.

func (*Runner) Commit

func (r *Runner) Commit(ctx context.Context) error

Commit commits the transaction. The errors have the tags SQLNoTransaction, SQLRunnerBusy and SQLTransactionFailed.

func (*Runner) Dispose

func (r *Runner) Dispose() (rolledBack bool, err error)

Dispose ends the runner for good: its session is closed as Close does, and the service forgets it.

func (*Runner) FetchMore

func (r *Runner) FetchMore(ctx context.Context, set *ResultSet, opts RunOptions) error

FetchMore reads the next rows of the last result set of the last run into the set. It does nothing for a set without a cursor. The errors have the tags SQLRunnerBusy and SQLFetchFailed.

func (*Runner) InTransaction

func (r *Runner) InTransaction() bool

InTransaction tells whether a transaction is open on the session.

func (*Runner) Rollback

func (r *Runner) Rollback(ctx context.Context) error

Rollback rolls the transaction back. The errors are those of Commit.

func (*Runner) Run

func (r *Runner) Run(ctx context.Context, stmts []dialect.Statement, opts RunOptions) ([]*StatementResult, error)

Run runs the statements one after the other and returns their results. It stops at the first statement that fails or is cancelled, or when ctx ends; the results are those of the statements that ran, the last being the one that failed. A batch (dialect Statement.Batch) with a repeat count runs that many times. The result sets of the last statement keep their cursor open, so that Fetch More can go on; those of the others are read up to MaxRows only. The errors (as opposed to a statement's own failure, which is in its result) have the tags SQLRunnerBusy, SQLNotConnected, SQLSessionFailed and SQLUseDatabaseFailed.

func (*Runner) Running

func (r *Runner) Running() bool

Running tells whether a statement is being run.

type Service

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

Service holds the open SQL connections of Emetos: one pool of connections to the server for each connection of the explorer (and one for each database of a PostgreSQL server that is browsed), opened with the password the user gave and closed when the connection is disconnected. The explorer, and the query editors of step 19.3, ask it for the catalog and for sessions. It is safe for use from several goroutines; every method that talks to a server takes a context and blocks, so it is called off the UI thread.

func NewService

func NewService() *Service

NewService makes a service with no connection open.

func (*Service) Catalog

func (s *Service) Catalog(connID string) (*Catalog, error)

Catalog returns the catalog cache of an open connection; the same one every time until the connection closes.

func (*Service) Children

func (s *Service) Children(ctx context.Context, c dbconn.Connection, parent *dbconn.Node) ([]dbconn.Node, error)

Children lists the nodes below a connection or a node: databases or schemas, then the folders of a schema, then the objects of a folder, then the columns, indexes and foreign keys of a table. It reads the catalog of the server, so it blocks. The errors are those of Service.Rows and SQLNodeUnknown.

func (*Service) Close

func (s *Service) Close(connID string) error

Close closes the pools of a connection. Closing one that is not open does nothing. The error is the first one a pool gave.

func (*Service) Create

func (s *Service) Create(ctx context.Context, connID string, kind dialect.Kind, r dialect.Ref) (string, error)

Create writes the statement that creates an object: the catalog's own text when the engine keeps one, the columns, keys and indexes written out for a table where it does not. The errors are those of Service.Rows.

func (*Service) DB

func (s *Service) DB(ctx context.Context, connID, database string) (*dbsql.DB, error)

DB returns the pool of a connection for a database ("" for the one it was opened on). Another database of a PostgreSQL server is opened the first time it is asked for.

func (*Service) Dialect

func (s *Service) Dialect(connID string) (dialect.Dialect, error)

Dialect returns the dialect of an open connection.

func (*Service) IsOpen

func (s *Service) IsOpen(connID string) bool

IsOpen tells whether the connection is open.

func (*Service) LoadTable

func (s *Service) LoadTable(ctx context.Context, connID string, kind dialect.Kind, r dialect.Ref) (dialect.Table, error)

LoadTable reads everything the generators need to know about a table or view.

func (*Service) NewRunner

func (s *Service) NewRunner(connID, database string) (*Runner, error)

NewRunner makes a runner for the connection and database. It takes no session before the first statement. The errors have the tag SQLNotConnected.

func (*Service) Open

func (s *Service) Open(ctx context.Context, c dbconn.Connection, password string) error

Open opens a connection: it makes the pool, connects once to see that the settings and the password work, and keeps the pool for the explorer. A connection that is open already is closed first. c has its ${env:} references expanded already. The errors have the tags SQLEngineUnknown, SQLFileNotAbsolute, SQLConnectionURLInvalid, SQLConnectionSettingsInvalid, SQLTLSCAFileUnreadable, SQLTLSCAFileInvalid, SQLTLSRootsUnavailable, SQLConnectFailed and SQLSessionInitFailed; none carries the password.

func (*Service) OpenTransactions

func (s *Service) OpenTransactions(connID string) int

OpenTransactions is the number of runners of the connection that have a transaction open: what a disconnect would roll back.

func (*Service) Rows

func (s *Service) Rows(ctx context.Context, connID, database string, q dialect.Query, limit int) (rows []dialect.Row, truncated bool, err error)

Rows runs a catalog query on a database and returns its rows as text; truncated says that there were more than limit rows (limit zero is maxListed). The errors have the tags SQLNotConnected, SQLQueryFailed and SQLRowsFailed.

func (*Service) Session

func (s *Service) Session(ctx context.Context, connID, database string) (*Session, error)

Session takes a connection of the pool for the database. It is given back with Close. For an engine whose cancel needs the id of the session (Cancel.SessionID) the id is read first. The errors have the tags SQLNotConnected, SQLSessionFailed and SQLQueryFailed.

func (*Service) Subscribe

func (s *Service) Subscribe(fn func(connID string, open bool)) (cancel func())

Subscribe calls fn after a connection is opened (open) or closed, on the goroutine that did it, and returns the function that stops the calls. fn must not block.

func (*Service) TableColumns

func (s *Service) TableColumns(ctx context.Context, connID string, d dialect.Dialect, r dialect.Ref) ([]dialect.Column, error)

TableColumns reads the columns of a table or view, with the ones a foreign key uses marked.

func (*Service) Text

func (s *Service) Text(ctx context.Context, connID, database string, q dialect.Query) (string, error)

Text runs a query that returns one text (a definition) and returns it; "" when the query returns no row.

type Session

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

Session is one connection of the pool kept for a series of statements (a query editor, a transaction), with the means to cancel the statement that is running on it.

func (*Session) Begin

func (s *Session) Begin(ctx context.Context) (context.Context, func())

Begin makes the context for one statement: Cancel ends it. The function it returns ends the statement's context and must be called when the statement is done.

func (*Session) Cancel

func (s *Session) Cancel() error

Cancel stops the statement that is running on the session. Where the dialect has a statement for it (KILL QUERY, pg_cancel_backend) it is run on another connection of the pool, which leaves the session as it was; if that cannot be done, or the engine has none, the context of the statement is ended and the driver cancels it. The error is that of the cancelling statement when the context could not be ended either.

func (*Session) Close

func (s *Session) Close() error

Close gives the connection back to the pool. It waits for a statement that is starting on the session; a second Close does nothing.

func (*Session) Conn

func (s *Session) Conn() *dbsql.Conn

Conn is the connection of the session. Statements go through ExecContext and QueryContext, which are safe against a Close that comes at the same time; Conn is for what needs the connection itself.

func (*Session) ExecContext

func (s *Session) ExecContext(ctx context.Context, query string, args ...any) (dbsql.Result, error)

ExecContext runs a statement that returns no rows on the session's connection. After Close it fails with sql.ErrConnDone.

func (*Session) QueryContext

func (s *Session) QueryContext(ctx context.Context, query string, args ...any) (*dbsql.Rows, error)

QueryContext runs a statement that returns rows on the session's connection. After Close it fails with sql.ErrConnDone. A Close that comes while the rows are open waits for them to be closed (database/sql's rule).

type StatementResult

type StatementResult struct {
	// Index is the place of the statement in the statements the run was given.
	Index int
	// Statement and Info are the statement and what Classify found.
	Statement dialect.Statement
	Info      dialect.Info
	// Elapsed is how long the statement took, up to the reading of the first rows.
	Elapsed time.Duration
	// Sets are the result sets, in order; none for a statement that returns no rows.
	Sets []*ResultSet
	// Affected is the number of rows a statement without a result set changed; HasAffected tells whether the engine said.
	Affected    int64
	HasAffected bool
	// Err is why the statement failed, and Cancelled that the user cancelled it (Err then says what the engine answered).
	Err       *QueryError
	Cancelled bool
}

StatementResult is everything one statement gave.

Directories

Path Synopsis
Package dialect is what differs between the four SQL engines the SQL extension speaks to (SPEC §10.21 "Drivers", D23): PostgreSQL, MySQL and MariaDB, SQLite and SQL Server.
Package dialect is what differs between the four SQL engines the SQL extension speaks to (SPEC §10.21 "Drivers", D23): PostgreSQL, MySQL and MariaDB, SQLite and SQL Server.

Jump to

Keyboard shortcuts

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