Skip to main content

MySQL / MariaDB

The MySQL adapter also supports MariaDB. Configure via URL or explicit fields; common alias keys are accepted.

Install

Add the driver package:

dependencies:
ormed: ^0.1.0
ormed_mysql: ^0.1.0

Configure (ormed.yaml)

driver:
type: mysql # or mariadb
options:
url: mysql://root:secret@localhost:6605/orm_test
charset: utf8mb4
collation: utf8mb4_general_ci
timezone: "+00:00"
sqlMode: STRICT_ALL_TABLES
timeoutMs: 10000
session:
sql_notes: 0
init:
- SET NAMES utf8mb4
- SET time_zone = "+00:00"

Use in code (DataSource)

The recommended way is to use the generated createDataSource() helper, but you can also initialize it manually:

import 'package:ormed/ormed.dart';
import 'package:ormed_mysql/ormed_mysql.dart';

void main() async {
ensureMySqlDriverRegistration();

final config = loadOrmConfig();
final ds = DataSource.fromConfig(config);
await ds.init();
}

Options

OptionTypeDefaultDescription
urlString?Full connection string. Aliases: uri, dsn. When set, it becomes the primary source for host/port/database/user/password and can also read query params like charset, collation, timezone, sql_mode, timeoutMs, ssl, secure, and password.
hostString127.0.0.1Database host (ignored when url/uri/dsn is set).
portint3306Database port (ignored when url/uri/dsn is set).
databaseStringconnection name or testDatabase name (ignored when url/uri/dsn is set).
usernameStringrootDatabase username (ignored when url/uri/dsn is set).
passwordString?Database password.
sslboolfalseEnable TLS (alias: secure). URL schemes mysqls/mariadbs and +ssl imply TLS.
timeoutMsint (ms)10000Connect timeout in milliseconds (alias: connectTimeout).
charsetStringutf8mb4Charset used for SET NAMES ....
collationString?utf8mb4_general_ciCollation for the connection and SET NAMES ... COLLATE ....
timezoneString+00:00Session timezone applied via SET time_zone = ....
sqlModeString?Session SQL mode string (alias: sql_mode).
sessionMap<String, Object?>{}Session variables applied via SET @@key = value.
initList<String>[]SQL statements executed after connecting and applying charset/timezone/sqlMode.
schemaString?Optional schema/database qualifier used when compiling fully-qualified table names.

Extensions

Driver extensions let you register custom clause compilers for MySQL/MariaDB without dropping down to raw SQL helpers.

class MySqlCaseInsensitiveExtensions extends DriverExtension {
const MySqlCaseInsensitiveExtensions();


List<DriverExtensionHandler> get handlers => const [
DriverExtensionHandler(
kind: DriverExtensionKind.where,
key: 'ci_equals',
compile: _compileMySqlCaseInsensitive,
),
];
}

DriverExtensionFragment _compileMySqlCaseInsensitive(
DriverExtensionContext context,
Object? payload,
) {
final data = payload as Map<String, Object?>;
final column = context.grammar.wrapIdentifier(data['column'] as String);
final placeholder = context.grammar.parameterPlaceholder();
return DriverExtensionFragment(
sql: 'LOWER(${context.tableIdentifier}.$column) = LOWER($placeholder)',
bindings: [data['value']],
);
}
Future<List<Map<String, Object?>>> searchDocumentsMySql(
DataSource dataSource,
String query,
) {
return dataSource.context
.table('documents')
.whereExtension('ci_equals', {'column': 'title', 'value': query})
.rows();
}

Future<DataSource> createMySqlExtensionDataSource() async {
final dataSource = DataSource(
DataSourceOptions(
name: 'docs-mysql-extensions',
driver: MySqlDriverAdapter.fromUrl(
'mysql://root:secret@localhost:3306/app',
),
entities: generatedOrmModelDefinitions,
driverExtensions: const [MySqlCaseInsensitiveExtensions()],
),
);
await dataSource.init();
return dataSource;
}

Data types

Ormed uses driver codecs to map some MySQL/MariaDB column types to richer Dart types when they appear as model fields.

final uuid = UuidValue.fromString('00000000-0000-0000-0000-000000000000');
final amount = Decimal.parse('12.34');
final duration = const Duration(hours: 1, minutes: 2, seconds: 3);
final tags = <String>{'alpha', 'beta'};
final bits = MySqlBitString.parse('1010');
final geometry = MySqlGeometry.fromHex('000000000101000000000000000000F03F0000000000000040');
final payload = Uint8List.fromList([1, 2, 3, 4]);

Supported mappings

Column typeDart typeNotes
DECIMAL / NUMERICDecimalPreserves precision (avoid double when you need exact values).
TIMEDurationEncoded as [-]HH:MM:SS[.ffffff].
UUIDUuidValueStored as CHAR(36) by default.
SET(...)Set<String>Encoded/decoded as the comma-separated value returned by MySQL.
BIT(n)MySqlBitStringUse when you need bit-level data rather than booleans.
GEOMETRYMySqlGeometryRaw bytes wrapper; decode/encode without lossy conversions.
JSONMap<String, Object?> / List<Object?>Stored as JSON strings, decoded into Dart collections.
BLOB / BINARYUint8ListBinary data (no string coercion).

Notes

  • Uses ON DUPLICATE KEY UPDATE for upserts and supports JSON columns on MySQL 8+/MariaDB 10.5+.
  • Set driver.type: mariadb to target MariaDB specifically; the same options apply.
  • Migrations and seeds are configured separately in ormed.yaml. See Getting Started → Configuration.
  • For plan/previews/schema internals, see Drivers → Internals.