Keyboard shortcuts

Press ← or → to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

sql

import sql

One way to talk to a relational database, whichever one it is.

sql is the entry point for every database Zuri supports. It defines what a database adapter has to provide, supplies everything that is the same whichever engine answers, and picks the adapter from the connection string. Changing database means changing that string, and whatever SQL the engines genuinely spell differently.

import sql

var db = sql.open(':memory:')

db.exec('create table posts (id integer primary key, title text)')

var id = db.insert('posts', { title: 'Hello' })

for post in db.query('select * from posts where id = ?', [id]) {
  echo post.title
}

db.close()

The only line above that names an engine is the first. Point it at postgres://localhost/app or mysql://localhost/app and the rest runs unchanged: the ? becomes $1 on PostgreSQL and stays ? on MySQL, the insert gets a RETURNING clause where the engine has no last insert id, and a unique key violation still arrives as UniqueViolation.

What is here

open()opens a connection from a connection string
pool()opens a pool of them
register()adds an adapter of your own
Connectionwhat a program holds and runs statements on
Transactionan open transaction, and the savepoints inside it
Statementa statement compiled once and run many times
Cursora result read a row at a time
ResultSetthe rows a query returned
Decimalan exact decimal, for a column a float must not hold
Timea signed span of time, as a TIME column holds one
Schemawhat tables exist and what is in them
SqlErrorthe root of every error a database raises

Parameters

Values are bound, never pasted into the statement. Write ? for positional parameters or :name for named ones and sql translates them into whatever the adapter wants:

db.query('select * from posts where author = ? and year = ?', [name, 2026])
db.query('select * from posts where author = :who', { who: name })

Errors

Every error is a SqlError. The subclasses are the same on every engine, so the code that handles a duplicate key does not change when the engine does:

catch {
  db.insert('users', { email: address })
} as error {
  if instance_of(error, sql.UniqueViolation) {
    echo 'that address is already registered'
  } else {
    raise error
  }
}

Isolates

A connection belongs to the isolate that opened it and cannot be shared with another. An isolate that needs a database opens its own connection or its own pool.

The sql API

Every public name in sql, wherever it is declared. Each links to the page that documents it.

NameKindSummary
sql.AuthenticationErrorclassThe server rejected the credentials.
sql.CheckViolationclassA CHECK constraint rejected the row.
sql.ClosedErrorclassThe connection, statement, cursor, transaction or pool was already closed.
sql.ConnectionclassAn open connection to a database.
sql.ConnectionErrorclassThe database could not be reached, or the connection dropped.
sql.CursorclassA result being read a row at a time.
sql.DeadlockErrorclassTwo transactions were each waiting on the other, and the engine broke the tie by aborting this one.
sql.DecimalclassAn exact decimal number.
sql.DriverclassOpens connections to one kind of database.
sql.DriverConnectionclassOne open connection to a database, as the layer above it sees one.
sql.DriverCursorclassA result being read a batch at a time rather than all at once.
sql.DriverStatementclassA statement compiled once and run many times.
sql.ExecResultclassWhat a statement that changed something reports.
sql.ForeignKeyViolationclassA foreign key has no matching row, or a referenced row is still in use by another table.
sql.INDEXEDconstant?1, ?2 and so on.
sql.IntegrityErrorclassA constraint rejected the data.
sql.NUMBEREDconstant$1, $2 and so on, numbered from one in binding order.
sql.NotNullViolationclassA column declared NOT NULL was given nothing.
sql.NotSupportedErrorclassThe engine cannot do what was asked, and no approximation would be honest.
sql.PoolclassA pool of connections to one database.
sql.PoolErrorclassSomething went wrong with a connection pool rather than with a database.
sql.PoolExhaustedErrorclassEvery connection was busy and none came free within the acquire timeout.
sql.ProtocolErrorclassThe server sent something the adapter could not make sense of.
sql.QUESTIONconstantA bare ? for every parameter, in order.
sql.QueryErrorclassThe engine refused the statement.
sql.READ_COMMITTEDconstantEach transaction sees rows committed before its own statement started, and nothing a concurrent transaction…
sql.READ_UNCOMMITTEDconstantA transaction can see rows another has written and not committed.
sql.REPEATABLE_READconstantA transaction reads the same rows throughout, whatever anyone else commits while it runs.
sql.RawclassMarks a fragment of SQL to be used as written rather than bound.
sql.ResultSetclassThe rows a query returned, with the shape of the result beside them.
sql.SERIALIZABLEconstantConcurrent transactions produce a result some serial order of them could also have produced.
sql.SchemaclassIntrospection for one connection.
sql.SchemaAdapterclassThe introspection queries for one engine.
sql.SerializationErrorclassTwo transactions could not both be treated as though they ran alone.
sql.SqlErrorclassBase class for every error this module and its adapters raise.
sql.StatementclassA prepared statement.
sql.TimeclassA signed span of time, as a SQL TIME column holds one.
sql.TimeoutErrorclassAn operation ran out of time.
sql.TransactionclassAn open transaction.
sql.TransactionErrorclassA transaction could not be carried out as asked.
sql.UniqueViolationclassA unique index or primary key already holds this value.
sql.column_shapefunctionThe description of one column, as every adapter returns it.
sql.crud.deletefunctionBuilds a DELETE.
sql.crud.insertfunctionBuilds an INSERT.
sql.crud.insert_manyfunctionBuilds an INSERT carrying several rows in one statement.
sql.crud.quote_tablefunctionRenders a table name, which may carry a schema.
sql.crud.selectfunctionBuilds a SELECT.
sql.crud.updatefunctionBuilds an UPDATE.
sql.crud.wherefunctionBuilds the WHERE clause for a dictionary of conditions.
sql.decimalfunctionBuilds a decimal, the same as Decimal() but as a function.
sql.default_capabilitiesfunctionThe capability flags a driver reports, with the value each takes when a driver does not say otherwise.
sql.driverfunctionThe adapter registered under name.
sql.driver_forfunctionThe adapter a connection string names.
sql.driversfunctionThe names of every registered adapter.
sql.mysql.CACHING_SHA2constantThe default since MySQL 8.0.
sql.mysql.CAPABILITIESconstantWhat the client asks for and what the server offers.
sql.mysql.CLEARconstantSends the password as it is.
sql.mysql.COMMANDSconstantThe commands this adapter sends.
sql.mysql.DEFAULT_PORTconstantThe port a MySQL server listens on unless told otherwise.
sql.mysql.DRIVERconstantThe driver instance sql registers for MySQL.
sql.mysql.ED25519constantMariaDB’s signature-based plugin.
sql.mysql.FLAGSconstantWhat the server says about a column beyond its type.
sql.mysql.MARIADB_DRIVERconstantThe driver instance sql registers for MariaDB.
sql.mysql.MAX_PARAMETERSconstantMost parameters one statement can bind.
sql.mysql.MariaDbDriverclassOpens MariaDB connections.
sql.mysql.MySqlConnectionclassA connection to MySQL or MariaDB.
sql.mysql.MySqlCursorclassA result being read in batches.
sql.mysql.MySqlDriverclassOpens MySQL connections.
sql.mysql.MySqlStatementclassA prepared statement.
sql.mysql.NATIVEconstantMySQL’s original plugin, and still MariaDB’s default.
sql.mysql.SHA256constantMySQL 5.7’s stronger option, superseded by the caching one.
sql.mysql.SSL_MODESconstantWhat sslmode can be.
sql.mysql.TYPESconstantThe type byte the server puts on a column, and that a parameter carries back.
sql.mysql.auth.NONEconstantNamed in a handshake by a server that wants no password at all.
sql.mysql.auth.SUPPORTEDconstantThe plugins this adapter can answer.
sql.mysql.auth.caching_sha2_passwordfunctionThe fast caching_sha2_password response.
sql.mysql.auth.clear_passwordfunctionThe password as the server reads it when it is sent outright: the bytes and the zero that ends them.
sql.mysql.auth.ed25519_passwordfunctionThe client_ed25519 response, which MariaDB uses.
sql.mysql.auth.encrypt_passwordfunctionThe password encrypted to the server’s public key, for the plugins that need the password itself over a…
sql.mysql.auth.native_passwordfunctionThe mysql_native_password response.
sql.mysql.auth.obfuscatefunctionThe password masked with the scramble, which is the form the two RSA plugins encrypt.
sql.mysql.auth.response_forfunctionThe first response to send for plugin, before any back and forth.
sql.mysql.auth.supportsfunctionWhether plugin is one this adapter knows how to answer.
sql.mysql.class_forfunctionThe class that best describes an error the server reported.
sql.mysql.connectfunctionOpens a MySQL connection directly, without going through sql.
sql.mysql.connection.CACHE_LIMITconstantHow many compiled statements a connection keeps before releasing the one it has gone longest without using.
sql.mysql.driver.DEFAULT_TIMEOUTconstantHow long to wait for the socket and for each read, in milliseconds.
sql.mysql.ed25519.DconstantThe curve constant, -121665/121666.
sql.mysql.ed25519.D2constantTwice the curve constant, which is what the addition uses.
sql.mysql.ed25519.LconstantThe order of the base point’s subgroup.
sql.mysql.ed25519.PconstantThe field prime, 2^255 - 19.
sql.mysql.ed25519.password_keyfunctionExpands a password into the 64 bytes MariaDB signs with.
sql.mysql.ed25519.public_keyfunctionThe public key matching an expanded key.
sql.mysql.ed25519.signfunctionSigns message with an expanded key.
sql.mysql.errors.CLASSESconstantSQLSTATE classes, for numbers the table above does not name.
sql.mysql.errors.SPECIFICconstantError numbers specific enough to name a class of their own.
sql.mysql.packets.COMPRESS_THRESHOLDconstantBelow this, a compressed packet is sent uncompressed instead.
sql.mysql.packets.CursorclassReads values out of one packet payload, keeping its own position.
sql.mysql.packets.EXACT_INTEGER_LIMITconstantLargest integer a Zuri number holds exactly.
sql.mysql.packets.LENENC_NULLconstantThe first byte of a length-encoded integer that means the value is NULL.
sql.mysql.packets.MAX_PAYLOADconstantThe largest payload a single packet can carry.
sql.mysql.packets.WriterclassBuilds one packet payload.
sql.mysql.protocol.CURSOR_NONEconstantNo cursor: the whole result comes back at once.
sql.mysql.protocol.CURSOR_READ_ONLYconstantAsks the server to keep the result open rather than send it all.
sql.mysql.protocol.STATUSconstantWhat the server says about the session after each command.
sql.mysql.raise_forfunctionRaises the right class for a server error report.
sql.mysql.results.exec_resultfunctionWhat a statement run for its effect reports.
sql.mysql.results.select_resultfunctionWhat a statement run for its rows reports.
sql.mysql.schema.MySqlSchemaclassAnswers introspection questions about a MySQL database.
sql.mysql.type_name_offunctionThe name of a column’s type, as MySQL itself would write it.
sql.mysql.types.BINARY_CHARSETconstantThe collation id that means a column holds bytes rather than text.
sql.mysql.types.UNSIGNED_FLAGconstantThe flag byte that goes with a parameter’s type to mark it unsigned.
sql.mysql.types.decode_binaryfunctionReads one value out of a binary protocol row.
sql.mysql.types.decode_textfunctionReads one value out of a text protocol row.
sql.mysql.types.describe_columnsfunctionReduces the server’s column descriptors to the two fields the shared contract asks for.
sql.mysql.types.is_binaryfunctionWhether a column holds bytes rather than text.
sql.mysql.types.is_unsignedfunctionWhether a column’s values are unsigned.
sql.mysql.types.parameter_typefunctionThe type byte and flag a value is sent as.
sql.mysql.types.write_parameterfunctionAppends a value in the form its type byte promises.
sql.openfunctionOpens a connection.
sql.params.STYLESconstantEvery style a driver may declare.
sql.params.tokenizefunctionSplits sql into the pieces that matter, in order.
sql.parse_timefunctionReads a SQL TIME literal.
sql.placeholderfunctionThe placeholder text for the parameter at position, counting from one.
sql.poolfunctionOpens a pool of connections.
sql.pool.DEFAULT_IDLE_TIMEOUTconstantHow long an idle connection is kept before being closed, in milliseconds.
sql.pool.DEFAULT_MAXconstantHow many connections a pool opens at most, when it is not told.
sql.pool.DEFAULT_MAX_LIFETIMEconstantHow long any connection is kept before being replaced, in milliseconds.
sql.postgres.DEFAULT_PORTconstantThe port a PostgreSQL server listens on unless told otherwise.
sql.postgres.DEFAULT_REGISTRYconstantThe registry every connection uses unless given one of its own.
sql.postgres.DRIVERconstantThe driver instance sql registers for this engine.
sql.postgres.ListenerclassSubscribes a connection to channels and collects what arrives.
sql.postgres.MAX_PARAMETERSconstantMost parameters one statement can bind.
sql.postgres.OIDSconstantPostgreSQL’s built-in type OIDs, by name.
sql.postgres.PostgresConnectionclassAn open PostgreSQL connection.
sql.postgres.PostgresCursorclassA portal being read.
sql.postgres.PostgresDriverclassOpens PostgreSQL connections.
sql.postgres.PostgresStatementclassA compiled PostgreSQL statement.
sql.postgres.SSL_MODESconstantWhat sslmode can be.
sql.postgres.TypeRegistryclassWhich decoder and encoder each OID uses.
sql.postgres.affected_rowsfunctionThe number of rows a command tag reports.
sql.postgres.auth.SCRAM_SHA_256constantThe mechanism this adapter implements.
sql.postgres.auth.client_firstfunctionThe client’s opening SCRAM message.
sql.postgres.auth.client_prooffunctionWorks out the client’s proof from the server’s challenge.
sql.postgres.auth.md5_responsefunctionBuilds the response to an MD5 password request.
sql.postgres.auth.noncefunctionA fresh SCRAM nonce.
sql.postgres.auth.offers_scramfunctionWhether the server offered SCRAM-SHA-256 among its mechanisms.
sql.postgres.auth.parse_scramfunctionSplits a SCRAM message into its key=value parts.
sql.postgres.auth.verify_serverfunctionChecks the server’s closing message really is from a server that knows the password.
sql.postgres.class_forfunctionThe class that best describes sqlstate.
sql.postgres.connectfunctionOpens a PostgreSQL connection directly, without going through sql.
sql.postgres.connection.CACHE_LIMITconstantHow many compiled statements a connection keeps.
sql.postgres.describe_columnsfunctionReduces the server’s column descriptors to the two fields the shared contract asks for.
sql.postgres.driver.DEFAULT_TIMEOUTconstantHow long to wait for the socket and for each read, in milliseconds.
sql.postgres.errors.CLASSESconstantSQLSTATE classes, for codes the table above does not name.
sql.postgres.errors.SPECIFICconstantCodes specific enough to name a class of their own.
sql.postgres.messages.AUTHENTICATIONconstantMessages the server sends, by tag.
sql.postgres.messages.AUTH_CLEARTEXTconstant
sql.postgres.messages.AUTH_MD5constant
sql.postgres.messages.AUTH_OKconstantAuthentication requests, by the number that follows the tag.
sql.postgres.messages.AUTH_SASLconstant
sql.postgres.messages.AUTH_SASL_CONTINUEconstant
sql.postgres.messages.AUTH_SASL_FINALconstant
sql.postgres.messages.BACKEND_KEY_DATAconstant
sql.postgres.messages.BIND_COMPLETEconstant
sql.postgres.messages.CLOSE_COMPLETEconstant
sql.postgres.messages.COMMAND_COMPLETEconstant
sql.postgres.messages.COPY_DATAconstant
sql.postgres.messages.COPY_DONEconstant
sql.postgres.messages.COPY_IN_RESPONSEconstant
sql.postgres.messages.COPY_OUT_RESPONSEconstant
sql.postgres.messages.DATA_ROWconstant
sql.postgres.messages.EMPTY_QUERY_RESPONSEconstant
sql.postgres.messages.ERROR_RESPONSEconstant
sql.postgres.messages.NOTICE_RESPONSEconstant
sql.postgres.messages.NOTIFICATION_RESPONSEconstant
sql.postgres.messages.NO_DATAconstant
sql.postgres.messages.PARAMETER_DESCRIPTIONconstant
sql.postgres.messages.PARAMETER_STATUSconstant
sql.postgres.messages.PARSE_COMPLETEconstant
sql.postgres.messages.PORTAL_SUSPENDEDconstant
sql.postgres.messages.PROTOCOL_VERSIONconstantThe protocol version this adapter speaks: 3.0, as a single number with the major version in the high half.
sql.postgres.messages.READY_FOR_QUERYconstant
sql.postgres.messages.ROW_DESCRIPTIONconstant
sql.postgres.messages.ReaderclassReads framed messages from a connected stream.
sql.postgres.messages.SSL_REQUESTconstantThe number the server recognises as a request to start TLS.
sql.postgres.messages.WriterclassBuilds one outgoing message.
sql.postgres.messages.read_cstringfunctionSplits a run of zero-terminated strings.
sql.postgres.raise_forfunctionRaises the right class for a server error report.
sql.postgres.schema.PostgresSchemaclassAnswers introspection questions about a PostgreSQL database.
sql.postgres.type_name_offunctionThe name of the type an OID stands for, or the OID as text for one this adapter has no name for, which is…
sql.postgres.types.ARRAY_ELEMENTSconstantThe element type each array OID holds.
sql.postgres.types.EPOCH_OFFSETconstantSeconds between the Unix epoch and PostgreSQL’s, which is 2000-01-01 rather than 1970-01-01.
sql.postgres.types.date_from_microsfunctionTurns a count of microseconds since the PostgreSQL epoch into a date.Date in UTC.
sql.postgres.types.decode_arrayfunctionReads an array back, however many dimensions it has.
sql.postgres.types.decode_boolfunctionA decoder reads one column value from its binary form.
sql.postgres.types.decode_boxfunction
sql.postgres.types.decode_byteafunction
sql.postgres.types.decode_circlefunction
sql.postgres.types.decode_datefunctiondate is a count of days from 2000-01-01, with no time part.
sql.postgres.types.decode_float4function
sql.postgres.types.decode_float8function
sql.postgres.types.decode_inetfunctioninet and cidr share a form: address family, prefix bits, a flag saying which of the two it is, then the…
sql.postgres.types.decode_int2function
sql.postgres.types.decode_int4function
sql.postgres.types.decode_int8function
sql.postgres.types.decode_intervalfunctioninterval is a span rather than a point, so it comes back as its parts.
sql.postgres.types.decode_jsonfunction
sql.postgres.types.decode_jsonbfunctionjsonb carries a version byte in front of the text, which every server so far sets to 1.
sql.postgres.types.decode_lsegfunction
sql.postgres.types.decode_macaddrfunction
sql.postgres.types.decode_numericfunctionDecodes PostgreSQL’s numeric into an exact Decimal.
sql.postgres.types.decode_numeric_valuefunction
sql.postgres.types.decode_oidfunction
sql.postgres.types.decode_pointfunction
sql.postgres.types.decode_textfunction
sql.postgres.types.decode_timefunctiontime is microseconds since midnight, with no date part.
sql.postgres.types.decode_timestampfunctionBoth timestamp and timestamptz are microseconds from the PostgreSQL epoch.
sql.postgres.types.decode_timetzfunctiontimetz is a time followed by its offset in seconds west of UTC.
sql.postgres.types.decode_uuidfunction
sql.postgres.types.encode_arrayfunctionBuilds the binary form of an array.
sql.postgres.types.encode_boolfunctionAn encoder turns a Zuri value into the bytes of its binary form.
sql.postgres.types.encode_byteafunction
sql.postgres.types.encode_datefunction
sql.postgres.types.encode_float4function
sql.postgres.types.encode_float8function
sql.postgres.types.encode_int2function
sql.postgres.types.encode_int4function
sql.postgres.types.encode_int8function
sql.postgres.types.encode_jsonfunction
sql.postgres.types.encode_jsonbfunctionjsonb takes the same text behind the version byte the server expects.
sql.postgres.types.encode_numericfunctionEncodes a Decimal, a number or a bigint as numeric.
sql.postgres.types.encode_textfunction
sql.postgres.types.encode_timestampfunction
sql.postgres.types.encode_uuidfunction
sql.postgres.types.micros_from_datefunctionThe microseconds since the PostgreSQL epoch a date.Date stands for.
sql.postgres.types.read_int16functionReads a signed 16 bit big-endian integer.
sql.postgres.types.read_int32functionReads a signed 32 bit big-endian integer.
sql.postgres.types.read_int64functionReads a signed 64 bit big-endian integer.
sql.postgres.types.read_uint16functionReads an unsigned 16 bit big-endian integer.
sql.postgres.types.read_uint32functionReads an unsigned 32 bit big-endian integer.
sql.postgres.types.text_offunctionA bytes slice as a UTF-8 string.
sql.postgres.types.write_int16functionWrites a signed 16 bit big-endian integer.
sql.postgres.types.write_int32functionWrites a signed 32 bit big-endian integer.
sql.postgres.types.write_int64functionWrites a signed 64 bit big-endian integer.
sql.rawfunctionBuilds a Raw.
sql.registerfunctionRegisters an adapter, so open() recognises its connection strings.
sql.scanfunctionWhat placeholders sql uses, without needing any values.
sql.split_statementsfunctionSplits a script into its statements.
sql.sqlite.BackupclassA copy in progress between two connections.
sql.sqlite.BlobclassAn open blob handle.
sql.sqlite.DEFAULT_BUSY_TIMEOUTconstantHow long a statement waits for another writer by default.
sql.sqlite.DRIVERconstantThe driver instance sql registers for this engine.
sql.sqlite.MAX_PARAMETERSconstantMost parameters one statement can bind, which is SQLite’s own limit.
sql.sqlite.MEMORYconstantThe path that means a private database held in memory, which is discarded when the connection closes.
sql.sqlite.SqliteConnectionclassAn open SQLite database.
sql.sqlite.SqliteCursorclassA result being stepped.
sql.sqlite.SqliteDriverclassOpens SQLite databases.
sql.sqlite.SqliteStatementclassA prepared SQLite statement.
sql.sqlite.backup.DEFAULT_PAGESconstantHow many pages a step copies when no size is given.
sql.sqlite.base_typefunctionThe bare type name from a declaration, upper cased and without any size or precision.
sql.sqlite.class_forfunctionThe class that best describes code.
sql.sqlite.connectfunctionOpens a SQLite database directly, without going through sql.
sql.sqlite.connection.CACHE_LIMITconstantHow many compiled statements a connection keeps for reuse.
sql.sqlite.conversion_forfunctionWhich conversion a column’s declaration calls for: 'bool', 'date', 'json', or nil for a column that…
sql.sqlite.driver.OPEN_CREATEconstant
sql.sqlite.driver.OPEN_FULLMUTEXconstant
sql.sqlite.driver.OPEN_MEMORYconstant
sql.sqlite.driver.OPEN_NOMUTEXconstant
sql.sqlite.driver.OPEN_PRIVATECACHEconstant
sql.sqlite.driver.OPEN_READONLYconstant
sql.sqlite.driver.OPEN_READWRITEconstant
sql.sqlite.driver.OPEN_SHAREDCACHEconstant
sql.sqlite.driver.OPEN_URIconstant
sql.sqlite.errors.primaryfunctionAn extended code’s primary code, which is its low byte.
sql.sqlite.reraisefunctionRe-raises an error from the native layer as the right class.
sql.sqlite.schema.SqliteSchemaclassAnswers introspection questions about a SQLite database.
sql.sqlite.split_messagefunctionSplits the [code] message form the native layer raises.
sql.sqlite.statement.bind_allfunctionBinds values to a reset statement, in order.
sql.sqlite.statement.describefunctionDescribes the columns a compiled statement returns.
sql.sqlite.types.BOOLEAN_TYPESconstantDeclared types that mean a boolean.
sql.sqlite.types.JSON_TYPESconstantDeclared types that mean JSON held in a text column.
sql.sqlite.types.TEMPORAL_TYPESconstantDeclared types that mean a point in time.
sql.sqlite.types.conversions_forfunctionThe conversions for a whole result, one per column, worked out once so each row does not have to look at the…
sql.sqlite.types.decodefunctionApplies one column’s conversion to one stored value.
sql.sqlite.types.decode_rowfunctionApplies a result’s conversions to one row of stored values.
sql.timefunctionBuilds a Time.
sql.time_from_secondsfunctionBuilds a Time of total seconds, splitting it into parts.
sql.translatefunctionRewrites sql into style and puts the values in binding order.
sql.types.ISO_DATE_FORMATconstantThe same, without the time, for a column that holds only a date.
sql.types.ISO_FORMATconstantThe format this module writes timestamps in: ISO 8601 with microsecond precision and an explicit UTC offset.
sql.types.flattenfunctionReduces value to something an engine with no richer type can store: a timestamp becomes ISO text, a list or…
sql.types.from_isofunctionReads ISO 8601 text back into a date.Date.
sql.types.from_jsonfunctionDecodes JSON text, returning nil for anything that will not parse.
sql.types.integer_from_textfunctionReads an integer, however long, as a number where one holds it exactly and a bigint where it does not.
sql.types.is_intervalfunctionWhether value is a Time.
sql.types.is_structuredfunctionWhether value is something this module stores as JSON.
sql.types.is_temporalfunctionWhether value is a date.Date.
sql.types.to_isofunctionFormats a date.Date as ISO 8601 text.
sql.types.to_jsonfunctionEncodes value as JSON text.

Submodules

ModuleReached asSummary
sql.connectionsql.connection.*The connection a program holds.
sql.crudsql.crud.*Building the four statements that are the same everywhere.
sql.cursorsql.cursor.*Reading a result without holding all of it.
sql.decimalsql.decimal.*Exact decimal numbers, for the money column that must not be a float.
sql.driversql.driver.*The contract every database adapter implements, and the capability flags that let one adapter differ from…
sql.errorssql.*Every error a database raises, under one root, in one shape, whatever engine it came from.
sql.mysqlimport sql.mysqlThe MySQL and MariaDB adapter.
sql.paramssql.params.*Rewriting a statement’s placeholders into whatever the active adapter expects.
sql.poolsql.pool.*Keeping connections open and lending them out.
sql.postgresimport sql.postgresThe PostgreSQL adapter.
sql.resultsql.result.*What a statement hands back: the rows of a query, or the count of a statement that changed something.
sql.schemasql.schema.*Asking a database what is in it.
sql.sqliteimport sql.sqliteThe SQLite adapter.
sql.statementsql.statement.*A statement compiled once and run many times.
sql.transactionsql.transaction.*Transactions, and the nesting that savepoints make possible.
sql.typessql.types.*How Zuri values and database values correspond, for the parts that are the same whichever engine is…

Functions

register()

sql.register(driver) -> Driver

Registers an adapter, so open() recognises its connection strings.

An adapter is anything implementing Driver. Registering one under a name already taken replaces it, which is how a program swaps in an adapter of its own for an engine sql already knows.

sql.register(MyOracleDriver())

var db = sql.open('oracle://localhost/app')

Parameters

  • driver (Driver)

Returns Driver — The driver, so a registration can be an expression.

Raises SqlError if driver is not one.

drivers()

sql.drivers() -> list[string]

The names of every registered adapter.

Returns list[string]

driver()

sql.driver(name: string) -> Driver

The adapter registered under name.

Parameters

  • name (string)

Returns Driver

Raises SqlError if nothing is registered under that name.

driver_for()

sql.driver_for(dsn: string) -> Driver

The adapter a connection string names.

The scheme decides: sqlite:// and postgres:// reach the adapters of those names, and a string with no scheme at all is taken as a SQLite path, which is the only form that could not be anything else.

Parameters

  • dsn (string)

Returns Driver

Raises SqlError if no adapter claims the scheme.

open()

sql.open(dsn, options) -> Connection

Opens a connection.

sql.open('sqlite://./app.db')
sql.open('postgres://alice:secret@localhost/app')
sql.open('./app.db')

An options dictionary works too, and needs driver to say which adapter it is for:

sql.open({ driver: 'sqlite', path: './app.db', journal_mode: 'wal' })

Parameters

  • dsn (string|dict) — A connection string, or options.
  • options (dict|nil) — Extra options, merged over whatever the connection string carried. Anything an adapter accepts in its own options goes here.

Returns Connection

Raises ConnectionError if the database cannot be reached.

pool()

sql.pool(dsn, options) -> Pool

Opens a pool of connections.

Parameters

  • dsn (string|dict) — As open() takes.
  • options (dict|nil) — The pool’s own settings, and any the adapter accepts. See Pool for what the pool reads.

Returns Pool


2026, Richard Ore and Zuri contributors