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
- func Engines() []dbconn.Engine
- func FactoryOf(h *Hub) extension.Factory
- func WriteInserts(ctx context.Context, w io.Writer, d dialect.Dialect, table string, ...) error
- type Catalog
- func (c *Catalog) Columns(ctx context.Context, ref dialect.Ref) ([]dialect.Column, error)
- func (c *Catalog) Invalidate()
- func (c *Catalog) Objects(ctx context.Context, database, schema string) ([]dialect.Object, error)
- func (c *Catalog) Schemas(ctx context.Context, database string) ([]string, error)
- type Extension
- type Hub
- type QueryError
- type ResultSet
- type RunOptions
- type Runner
- func (r *Runner) Begin(ctx context.Context) error
- func (r *Runner) Cancel() error
- func (r *Runner) Close() (rolledBack bool, err error)
- func (r *Runner) Commit(ctx context.Context) error
- func (r *Runner) Dispose() (rolledBack bool, err error)
- func (r *Runner) FetchMore(ctx context.Context, set *ResultSet, opts RunOptions) error
- func (r *Runner) InTransaction() bool
- func (r *Runner) Rollback(ctx context.Context) error
- func (r *Runner) Run(ctx context.Context, stmts []dialect.Statement, opts RunOptions) ([]*StatementResult, error)
- func (r *Runner) Running() bool
- type Service
- func (s *Service) Catalog(connID string) (*Catalog, error)
- func (s *Service) Children(ctx context.Context, c dbconn.Connection, parent *dbconn.Node) ([]dbconn.Node, error)
- func (s *Service) Close(connID string) error
- func (s *Service) Create(ctx context.Context, connID string, kind dialect.Kind, r dialect.Ref) (string, error)
- func (s *Service) DB(ctx context.Context, connID, database string) (*dbsql.DB, error)
- func (s *Service) Dialect(connID string) (dialect.Dialect, error)
- func (s *Service) IsOpen(connID string) bool
- func (s *Service) LoadTable(ctx context.Context, connID string, kind dialect.Kind, r dialect.Ref) (dialect.Table, error)
- func (s *Service) NewRunner(connID, database string) (*Runner, error)
- func (s *Service) Open(ctx context.Context, c dbconn.Connection, password string) error
- func (s *Service) OpenTransactions(connID string) int
- func (s *Service) Rows(ctx context.Context, connID, database string, q dialect.Query, limit int) (rows []dialect.Row, truncated bool, err error)
- func (s *Service) Session(ctx context.Context, connID, database string) (*Session, error)
- func (s *Service) Subscribe(fn func(connID string, open bool)) (cancel func())
- func (s *Service) TableColumns(ctx context.Context, connID string, d dialect.Dialect, r dialect.Ref) ([]dialect.Column, error)
- func (s *Service) Text(ctx context.Context, connID, database string, q dialect.Query) (string, error)
- type Session
- func (s *Session) Begin(ctx context.Context) (context.Context, func())
- func (s *Session) Cancel() error
- func (s *Session) Close() error
- func (s *Session) Conn() *dbsql.Conn
- func (s *Session) ExecContext(ctx context.Context, query string, args ...any) (dbsql.Result, error)
- func (s *Session) QueryContext(ctx context.Context, query string, args ...any) (*dbsql.Rows, error)
- type StatementResult
Constants ¶
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.
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.
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").
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").
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.
const ID = "emetos.sql"
ID is the id of the extension.
Variables ¶
This section is empty.
Functions ¶
func Engines ¶
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 ¶
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) Invalidate ¶
func (c *Catalog) Invalidate()
Invalidate makes the catalog forget everything it read.
func (*Catalog) Objects ¶
Objects lists the tables and views of a schema (of a database, for MySQL).
type Extension ¶
type Extension struct {
// contains filtered or unexported fields
}
Extension is the extension in one window tab.
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.
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.
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 ¶
Begin opens a transaction on the session. The errors have the tags SQLTransactionOpen, SQLRunnerBusy, SQLNotConnected and SQLTransactionFailed.
func (*Runner) Close ¶
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 ¶
Commit commits the transaction. The errors have the tags SQLNoTransaction, SQLRunnerBusy and SQLTransactionFailed.
func (*Runner) Dispose ¶
Dispose ends the runner for good: its session is closed as Close does, and the service forgets it.
func (*Runner) FetchMore ¶
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 ¶
InTransaction tells whether a transaction is open on the session.
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.
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 (*Service) Catalog ¶
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 ¶
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 ¶
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) 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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
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.
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
ExecContext runs a statement that returns no rows on the session's connection. After Close it fails with sql.ErrConnDone.
func (*Session) QueryContext ¶
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.
Source Files
¶
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. |