createDatabase method

  1. @override
Future<bool> createDatabase(
  1. String name, {
  2. Map<String, Object?>? options,
})
override

Creates a new database with the given name.

Options are driver-specific:

  • MySQL: {charset: 'utf8mb4', collation: 'utf8mb4_unicode_ci'}
  • Postgres: {encoding: 'UTF8', owner: 'username', template: 'template0', locale: 'en_US.UTF-8', lc_collate: 'en_US.UTF-8', lc_ctype: 'en_US.UTF-8', tablespace: 'pg_default', connection_limit: -1}
  • SQLite: (no options - file-based)

Returns true if created, false if already exists. Throws DriverException on error.

Implementation

@override
Future<bool> createDatabase(
  String name, {
  Map<String, Object?>? options,
}) async {
  final sql = _schemaCompiler.dialect.compileCreateDatabase(name, options);
  if (sql == null) {
    throw UnsupportedError('PostgreSQL should support database creation');
  }

  // Postgres requires being outside a transaction block for CREATE DATABASE
  if (_transactionDepth > 0) {
    throw StateError('Cannot create database within a transaction');
  }

  try {
    await executeRaw(sql);
    return true;
  } on Exception catch (e) {
    // Check if error is "database exists" (error code 42P04)
    final errorMsg = e.toString();
    if (errorMsg.contains('42P04') ||
        errorMsg.toLowerCase().contains('already exists')) {
      return false;
    }
    rethrow;
  }
}