mysql library Open a database
Typed MySQL queries with explicit connection and transaction ownership.
Await mysql to connect and verify the server before using its generated table getters. Each database owns one queued physical connection. MySQL and MariaDB have distinct engine identities and migration histories.
Use package:orm/drivers/mysql.dart when only a raw driver is needed.
Classes
- AcquisitionEvent Observe and inspect
- Time until a driver lease is granted or acquisition fails. Includes native pool wait/connection setup; it does not separate those driver internals.
- AcquisitionOptions
- Limits waiting for a connection, including establishment and initialization. Cancellation after acquisition does not cancel the session callback.
- Assignment
- One typed column assignment prepared by a writable field.
- Backend
- Static engine identity used to constrain driver and transaction APIs.
-
BatchInsert<
F extends Fields> - Inserts consecutive rows of the same shape together, splitting at the driver's parameter limit. All chunks share one transaction by default.
-
BatchReturning<
R> - Typed returned rows from a prepared batch insert.
- CancellationToken
- A cancellation request. Await the operation itself to observe its actual database outcome; completion can win a race with cancellation.
- Capabilities Independent SQL drivers
- Features a concrete driver can execute for its actual engine and platform.
-
Change<
T> - A patch value that distinguishes omission, assignment and SQL DEFAULT.
- CheckSchema
- A row CHECK expression. A null name leaves naming to the database.
-
Codec<
T> - Converts a typed Dart value to database storage and decodes it on reads.
- Codecs
- Built-in conversions for SQL scalar values, JSON, and exact numeric types.
-
Column<
T> - Physical column metadata coupled to the Dart/storage Codec.
- ComputedColumn
- Database-computed SQL using physical column names.
-
Cte<
R, F extends Fields> - A CTE exports SQL expression identities. Dart mapper properties are not mistaken for SQL columns. ref() accepts only expressions the source selected.
-
CteFields<
F extends Fields> - SQL columns exported by a CTE, referenced through its original expressions.
- CursorTerm
- One ordering expression paired with its last-seen, encoded cursor value.
-
Database<
B extends Backend> Open a database - Typed queries and change notifications over an owned SQL runtime.
- Decimal
- A finite base-ten value, independent of binary floating point.
- DecodeEvent Observe and inspect
- Synchronous ORM decoding/mapping and associated row grouping. Excludes SQL, acquisition, compilation, waiting for the consumer and other client work.
-
Driver<
B extends Backend> Independent SQL drivers -
Owns or borrows connection resources for a specific engine
B. - ExecutionOptions
- Per-operation connection acquisition and statement execution controls.
-
Expr<
T> - A typed SQL expression that can also be selected as a result.
-
Field<
T> - A writable column expression that can create mutation assignments.
- Fields
- Typed expressions belonging to one table occurrence.
- ForeignKey
- A database foreign key described with ordered physical column names.
- IndexSchema
- A simple index over ordered physical columns.
- LocalDate
- A Gregorian calendar date, without a time or timezone. Year 0 is 1 BC; negative years use astronomical numbering.
- LocalDateTime
- Calendar date and wall-clock time, with no timezone or implied UTC instant.
- LocalTime
- A wall-clock time at microsecond resolution, including the endpoint 24:00. The fourth constructor argument is the full fractional second (0..999999).
- Mariadb
- Type marker for MariaDB drivers and sessions.
- MariadbTransaction
- MariaDB isolation and read-only settings applied to the next transaction.
-
Mutation<
F extends Fields> - A prepared insert, update, or delete that performs no I/O until executed.
- Mysql
- Type marker for MySQL drivers and sessions.
- MysqlDriver
- One physical connection. Whole leases are queued, including transactions. Create additional drivers explicitly when independent concurrent leases are required. Closing drains all leases accepted before close was called.
- MysqlOptions
- Configuration for one owned MySQL connection.
- MysqlTransaction
- MySQL isolation and read-only settings applied to the next transaction.
- OrderTerm
- An expression's sort direction and optional NULL ordering policy.
- Postgres
- Type marker for PostgreSQL drivers and sessions.
- PostgresTransaction
- PostgreSQL isolation and read-only settings for one transaction.
-
Query<
R, F extends Fields> - An immutable typed query bound to a SQL context.
- QueryContext
- Capabilities and an optional execution binding for typed query descriptions. The SQL layer knows no connection pool, platform adapter or runtime session.
- QueryEvent Observe and inspect
- Timing and outcome of one SQL statement or cursor operation.
- QueryPlan
- A non-executing description of one SQL statement and its dependent batches. Bound values are omitted; literal SQL text is retained. A batch SQL template contains one parent key tuple.
-
ReadField<
T> - A selectable column expression with no assignment operations.
-
Relation<
R, F extends Fields> - A relationship is a query description. Constructing or selecting it performs no I/O. List results are loaded in batches on the root query's connection.
- RelationLoadPlan
- One batch per chunk of distinct non-null parent keys, conditional on data. For nested loads, this rule applies separately to each returned parent batch.
-
ResultColumn<
T> - One result label and its storage/domain codec, with no write constraints.
-
ResultShape<
R> - Required result labels and typed decoding, independent of physical tables. Compositions are validated at construction. Mapping callbacks run once per actual row, never while compiling or binding empty results.
-
Returning<
R> -
A prepared mutation whose returned SQL rows decode to
R. -
Selection<
T> - A typed result description decoded when its containing query executes.
- Sql
- Immutable SQL text, values and composition, with no connection or row cache.
- SqlBuilder
- Builds and inspects typed SQL without constructing a driver or a database.
- SqlCheck
- Database preparation evidence; this never proves domain codecs/nullability.
- SqlCommand
- SQL text and separately bound values. Values are never interpolated into SQL.
- SqlConnection Independent SQL drivers
- Execution port for one physical connection during an active driver lease.
- SqlCursor
- Bounded row retrieval tied to the connection lease that opened it.
-
SqlDatabase<
B extends Backend> Sessions and transactions - Raw SQL execution with owned driver resources and explicit callback scopes.
- Sqlite
- Type marker for native and browser SQLite drivers and sessions.
- SqliteTransaction
- SQLite BEGIN mode for an explicit transaction.
- SqlJson
- A non-SQL-null JSON document. Its value may itself be JSON null. Drivers use this envelope for parsed JSON, including JSON string scalars.
-
SqlQuery<
R> - A reusable SQL statement and typed result contract, independent of a database.
- SqlReal
- Explicit floating-point SQL input. JavaScript cannot distinguish an integral double from int by runtime type; this preserves the SQL intention.
- SqlResult
- Raw row values and write metadata returned by a completed driver operation.
-
SqlValue<
T> - A value encoded once with an explicit storage codec, independent of a session. Mutable bytes are copied. Use a JSON codec for maps and lists.
-
Table<
R, F extends Fields> - A table's physical schema, typed fields and full-row decoder.
-
TableAlias<
R, F extends Fields> - Explicit aliases support self joins and any number of joins without adding a growing number of generic join-result types.
- TableRef
- A table occurrence has nominal identity, even when two row records have the same structural Dart type or a query joins the same physical table twice.
- TableSchema
- Immutable physical table metadata, independent of Dart model identity.
-
TableSet<
R, F extends Fields> - Typed access to a table, including full-row reads and prepared inserts.
-
TransactionOptions<
B extends Backend> Sessions and transactions - Engine-specific settings applied before a transaction callback starts.
- TransactionRetry Sessions and transactions
- Explicit opt-in: callback logic must be safe to repeat after rollback. The budget counts every scheduled retry, including commit-only retries.
-
UnionFields<
F extends Fields> - References refer to the left operand's exported SQL expressions.
Enums
- ComputedStorage
- How a database maintains a computed column, subject to engine capabilities.
- DecimalRounding
- Rounding is explicit; exact rejects a non-zero discarded remainder.
- Isolation
- Requested transaction isolation; exact visibility rules belong to the engine.
- MysqlTls
- Transport encryption and server identity checks for MySQL and MariaDB.
- NullOrder
- Explicit placement of SQL NULL relative to non-null sort values.
- QueryOperation
- The driver operation measured by a QueryEvent.
- SqlDialect
- SQL engine used for quoting, parameter syntax, and capability validation.
- SqliteTransactionMode
- When SQLite acquires its transaction locks.
- ToOneStrategy
- How a to-one selection is loaded when its parent query executes.
- WindowFrame
- Frame used by a window aggregate.
Extensions
-
ChangeField
on Field<
T> - Converts a generated patch input into zero or one SQL assignment.
-
ColumnSql
on Column<
T> - Reuses a physical column's codec for raw parameters and result labels.
-
DecimalExpression
on Expr<
T> - Exact decimal arithmetic using the selected database's capabilities.
-
FieldSql
on ReadField<
T> - Reuses a table field's codec without capturing its alias or connection.
-
InstantExpression
on Expr<
T> - Precision control for UTC instant expressions.
- InstantPrecision on DateTime
- Explicit precision conversion for resolved UTC instants.
-
KeysetQuery
on Query<
R, F> - Stable keyset pagination for a filtered table query.
-
LocalDateTimeExpression
on Expr<
T> - Precision control for local timestamps without a time zone.
-
NumericExpression
on Expr<
T> - SQL arithmetic and aggregation for Dart numeric values.
-
NumericField
on Field<
T> - Atomic numeric updates evaluated inside the database statement.
-
Predicate
on Expr<
bool?> - Boolean composition using SQL's three-valued NULL semantics.
-
QueryStreaming
on Query<
R, F> - Cursor-backed, demand-driven execution of a typed query.
-
Result2
on (ResultShape<
A> , ResultShape<B> ) - Combines 2 typed result descriptions, including nested result shapes.
-
Result3
on (ResultShape<
A> , ResultShape<B> , ResultShape<C> ) - Combines 3 typed result descriptions, including nested result shapes.
-
Result4
on (ResultShape<
A> , ResultShape<B> , ResultShape<C> , ResultShape<D> ) - Combines 4 typed result descriptions, including nested result shapes.
-
Result5
on (ResultShape<
A> , ResultShape<B> , ResultShape<C> , ResultShape<D> , ResultShape<E> ) - Combines 5 typed result descriptions, including nested result shapes.
-
Result6
on (ResultShape<
A> , ResultShape<B> , ResultShape<C> , ResultShape<D> , ResultShape<E> , ResultShape<F> ) - Combines 6 typed result descriptions, including nested result shapes.
-
Selection2
on (Selection<
A> , Selection<B> ) - Composes two independently typed selections into one decoded result.
-
Selection3
on (Selection<
A> , Selection<B> , Selection<C> ) - Composes three independently typed selections into one decoded result.
-
Selection4
on (Selection<
A> , Selection<B> , Selection<C> , Selection<D> ) - Composes four independently typed selections into one decoded result.
-
Selection5
on (Selection<
A> , Selection<B> , Selection<C> , Selection<D> , Selection<E> ) - Composes five independently typed selections into one decoded result.
-
Selection6
on (Selection<
A> , Selection<B> , Selection<C> , Selection<D> , Selection<E> , Selection<F> ) - Composes six independently typed selections into one decoded result.
-
SetQueries
on Query<
R, F> - SQL set operations over matching scalar or positional Record projections.
-
SqlDatabaseStreaming
on SqlDatabase<
Backend> Sessions and transactions - Demand-driven raw-row streaming with a bounded database cursor.
- SqlExecution on QueryContext
- Executes reusable SQL on the current database, session or transaction.
-
SqlRow2
on (Expr<
A> , Expr<B> ) - Projects two SQL expressions as a positional Dart Record.
-
SqlRow3
on (Expr<
A> , Expr<B> , Expr<C> ) - Projects three SQL expressions as a positional Dart Record.
-
SqlRow4
on (Expr<
A> , Expr<B> , Expr<C> , Expr<D> ) - Projects four SQL expressions as a positional Dart Record.
-
SqlRow5
on (Expr<
A> , Expr<B> , Expr<C> , Expr<D> , Expr<E> ) - Projects five SQL expressions as a positional Dart Record.
-
SqlRow6
on (Expr<
A> , Expr<B> , Expr<C> , Expr<D> , Expr<E> , Expr<F> ) - Projects six SQL expressions as a positional Dart Record.
-
TextExpression
on Expr<
String> - String operations evaluated by the selected database.
-
TimeExpression
on Expr<
T> - Precision control for SQL time expressions.
-
WatchQuery
on Query<
R, F> Observe and inspect - Re-executes a root database query after relevant committed changes.
-
WatchSql
on Database<
B> - Re-executes raw typed SQL after explicitly declared physical tables change.
Functions
-
checkSqlQuery<
R> (SqlDatabase< Backend> db, SqlQuery<R> query) → Future<SqlCheck> - Prepares a SELECT/WITH/VALUES query without executing application expressions. Uses a temporary projected subquery only for checking, never for execution. DML, including RETURNING, is outside this check's scope.
-
fields(
Map< String, Selection< selected) → Selection<Object?> >Map< String, Object?> > - Runtime field selection deliberately returns dynamic values.
-
mysql(
MysqlOptions options, {void onQuery(QueryEvent)?, void onAcquire(AcquisitionEvent)?, void onDecode(DecodeEvent)?}) → Future< Database< Mysql> > - Connects to MySQL 8.4+ and returns a typed database owning that connection.
-
rank(
{List< Expr< partitionBy = const [], required List<Object?> >OrderTerm> orderBy}) → Expr<int> - Builds one-based SQL rank, with ties sharing a rank and leaving later gaps.
-
rowNumber(
{List< Expr< partitionBy = const [], List<Object?> >OrderTerm> orderBy = const []}) → Expr<int> - Builds a one-based SQL row number within each partition.
-
sql<
T> (List< String> parts, List<Expr< values, Codec<Object?> >T> codec) → Expr<T> -
partsare trusted SQL,valuesare expressions. Never put user input in parts. -
value<
T> (T value, Codec< T> codec) → Expr<T> - Creates a bound SQL value using an explicit storage codec.
Typedefs
- PlannedColumn = ({String codecType, String? column, int index, bool presence, String? table})
- A physical SQL output slot, including association keys and presence markers. Expressions without a direct column source have null table/column names.
- PlannedJoin = ({bool left, bool relation, String table})
- A joined table name, join kind and whether a relation introduced it.
Exceptions / Errors
- MysqlFailure
- A server-reported error. Numeric codes are preserved; SQLSTATE is not exposed by mysql_client_plus and is not guessed from the error message.
- OrmException
- An ORM failure with a stable machine-readable code and optional cause.
- SqlFailure
- Adapter classification. Retrying also requires a confirmed rollback and an explicitly repeatable application callback; these flags alone are not enough.