Skip to content

Database configuration

A DatabaseConfig is a set of named DatabaseConnections with one default. Load it from YAML, from environment variables, or build it in code, then pass it to Database.connect.

import 'package:gisila_orm/gisila.dart';
final config = await DatabaseConfig.fromEnvironment(); // DATABASE_URL, else database.yaml
final db = await Database.connect(config);
default: main
connections:
main:
type: postgresql
host: localhost
port: 5432
database: blog
username: postgres
password: postgres
ssl_mode: disable
connection_timeout: 30
query_timeout: 30
max_connections: 10
additional_params:
application_name: blog-api
replica:
host: replica.internal
database: blog
username: readonly
password: secret
ssl_mode: verify-full
ssl_root_cert: /etc/ssl/certs/db-ca.pem
Key Type Default Description
default string default Name of the default connection.
connections map {} Connection name → settings below.
type string postgresql Only postgresql is supported; any other value throws ArgumentError.
host string localhost Server host.
port int 5432 Server port.
database string – (required) Database name.
username string postgres User name.
password string '' Password.
ssl bool false Older switch: true means require. Ignored when ssl_mode is set.
ssl_mode string none libpq-style TLS mode. See TLS modes.
ssl_root_cert string none PEM file of CA certificates to trust instead of the system store (for verify-full).
connection_timeout int (seconds) 30 Connect timeout.
query_timeout int (seconds) 30 Per-statement timeout.
max_connections int 10 Maximum connections in this pool.
min_connections int 2 Stored in the config, but not used by the pool.
additional_params map {} Extra values. Only application_name is applied.

Keep passwords out of committed YAML; use DATABASE_URL in deployed environments.

Variable Effect
DATABASE_URL Defines a connection named default and makes it the default, replacing any YAML connection of that name.
DB_CONNECTIONS Comma-separated extra connection names, for example replica,analytics.
DB_<NAME>_URL URL for each name in DB_CONNECTIONS (name upper-cased): DB_REPLICA_URL.

URLs take the form postgres://user:password@host:port/database?sslmode=...; see DatabaseConnection.fromUrl. Timeouts and pool size can’t be set through a URL; they take their defaults.

enum DatabaseSslMode { disable, prefer, require, verifyFull }
Mode Accepted spellings Behaviour
disable disable Plain TCP.
prefer allow, prefer TLS when the server offers it, decided once at connect. Certificates aren’t verified and an active attacker can force plain TCP.
require require Always TLS, certificate not verified.
verifyFull verify-ca, verify-full, verify_full, verifyfull Always TLS, verifying the chain and host name. verify-ca maps here because the driver can’t skip the host-name check.

DatabaseSslMode.parse(String value) accepts the spellings above (case-insensitive) and throws ArgumentError for anything else.

When to use: verify-full for any database reached over a network you don’t control, with ssl_root_cert when the server uses a private CA. disable only on localhost or a private network.

class DatabaseConfig {
DatabaseConfig({List<DatabaseConnection> connections = const [], String defaultConnection = 'default'});
static Future<DatabaseConfig> fromFile(String filePath);
static DatabaseConfig fromMap(Map<String, dynamic> config);
static Future<DatabaseConfig> fromEnvironment({String configFile = 'database.yaml', Map<String, String>? envOverrides});
}

When to use: fromEnvironment in applications (works both locally with a YAML file and in deployments with DATABASE_URL); the constructor in tests and tools that build the config in code.

Member Description
fromFile(path) Loads YAML. Throws FileSystemException if the file is missing.
fromMap(map) Builds from an already-parsed map with default and connections.
fromEnvironment({configFile, envOverrides}) Loads configFile if it exists, then applies DATABASE_URL, DB_CONNECTIONS and DB_<NAME>_URL on top. envOverrides replaces Platform.environment (handy in tests).
addConnection(c) Adds or replaces a connection.
removeConnection(name) Removes a connection. Throws ArgumentError for the default.
getConnection([name]) The named (or default) connection, or null.
defaultConnection The default connection. Throws DatabaseConfigurationException if it isn’t registered.
setDefaultConnection(name) Changes the default. Throws ArgumentError if unknown.
connectionNames All names.
hasConnection(name) Whether a name exists.
connections Unmodifiable map of all connections.
toMap() Serialises back to the YAML shape (passwords included).

Example

final config = DatabaseConfig(connections: [
DatabaseConnection.postgresql(
name: 'default',
host: 'localhost',
database: 'blog',
username: 'postgres',
password: 'postgres',
maxConnections: 5,
),
]);
class DatabaseConnection {
const DatabaseConnection({
required String name,
required DatabaseType type,
required String host,
required int port,
required String database,
required String username,
required String password,
bool useSSL = false,
DatabaseSslMode? sslMode,
String? sslRootCert,
int connectionTimeout = 30,
int queryTimeout = 30,
int maxConnections = 10,
int minConnections = 2,
Map<String, dynamic> additionalParams = const {},
});
}

One named connection’s settings.

Field Type Default Description
name String – Lookup name.
type DatabaseType – Always DatabaseType.postgresql.
host, port, database, username, password – Server and credentials.
useSSL bool false Older switch; true means require when sslMode is null.
sslMode DatabaseSslMode? null TLS mode; wins over useSSL.
sslRootCert String? null CA PEM file. An unreadable file makes pool creation throw DatabaseConfigurationException.
connectionTimeout int 30 Seconds.
queryTimeout int 30 Seconds.
maxConnections int 10 Pool size.
minConnections int 2 Not used by the pool.
additionalParams Map<String, dynamic> {} Only application_name is applied.
effectiveSslMode DatabaseSslMode (getter) sslMode, else require/disable from useSSL.
connectionString String (getter) postgresql://user:pass@host:port/db?sslmode=.... Contains the password; don’t log it.
Constructor / method Description
DatabaseConnection.postgresql({required name, required host, required database, required username, required password, port = 5432, ...}) Same fields, with type fixed and port defaulted.
DatabaseConnection.fromMap(String name, Map<String, dynamic> config) Parses one entry of the connections: YAML map.
DatabaseConnection.fromUrl(String name, String url) Parses a URL; see below.
toMap() Serialises back to the YAML shape.
URL part Handling
Scheme postgres or postgresql; anything else throws ArgumentError.
User info Percent-decoded. The password is everything after the first :. Defaults: user postgres, password empty.
Host, port Default localhost, 5432.
Path Database name, percent-decoded.
?sslmode= Any libpq value (see TLS modes).
?ssl=true Also 1, yes, require: means require when sslmode is absent.
?sslrootcert= CA file. system means the default trust store.
?user=, ?password= Override the user info, as in libpq.
final c = DatabaseConnection.fromUrl(
'default',
'postgres://app:s3cr%40t@db.internal:5432/blog?sslmode=verify-full',
);
Symbol Description
enum DatabaseType { postgresql } Backend type. Only PostgreSQL exists.

See also: Set up a project, Database, contexts and transactions.