SwiftlyS2
Development

Database

SwiftlyS2 provides a unified database service so plugins can fetch named connections from one global configuration.

Accessing Database Service

The database service is available through Core.Database.

public override void Load(bool hotReload)
{
    var database = Core.Database;
}

Global Database Configuration

Database connections are defined in configs/database.jsonc and then referenced by name in plugins.

{
    "default_connection": "host",
    "connections": {
        "host": "mysql://username:password@localhost:3306/database",
        "analytics": "postgresql://username:password@localhost:5432/database",
        "local": "sqlite://data/local.db"
    }
}

Supported connection URI formats:

  • MySQL: mysql://user:pass@host:3306/database
  • PostgreSQL: postgresql://user:pass@host:5432/database
  • SQLite: sqlite://path/to/database.db

Getting a Connection

Use GetConnection to receive an IDbConnection for a named connection.

using var connection = Core.Database.GetConnection("host");
connection.Open();

If the connection name is not found, SwiftlyS2 returns the default connection.

The GetConnection signature is:

IDbConnection GetConnection(string connectionName)

Getting Raw Connection Data

Get Connection String

string connectionString = Core.Database.GetConnectionString("host");

This also falls back to the default connection when the name is missing.

Get Parsed Connection Info

DatabaseConnectionInfo info = Core.Database.GetConnectionInfo("host");

Console.WriteLine($"Driver: {info.Driver}");
Console.WriteLine($"Host: {info.Host}:{info.Port}");
Console.WriteLine($"Database: {info.Database}");

This also falls back to the default connection when the name is missing.

DatabaseConnectionInfo Fields

DatabaseConnectionInfo contains parsed connection metadata:

FieldTypeDescription
DriverstringDatabase driver (for example mysql, postgresql, sqlite)
HoststringDatabase host
DatabasestringDatabase name
UserstringUsername
PassstringPassword
TimeoutuintConnection timeout
PortushortDatabase port
RawUristringOriginal URI from config

Avoid logging secrets like Pass in production.

Using ADO.NET or an ORM

GetConnection returns IDbConnection, so you can use either plain ADO.NET or any compatible ORM.

Common options:

  • Dapper
  • Dommel
  • FreeSql
  • Entity Framework Core

Dapper Example

using var connection = Core.Database.GetConnection("host");

var players = await connection.QueryAsync<PlayerRow>(
    "SELECT steam_id, name FROM players WHERE is_active = @IsActive",
    new { IsActive = true }
);

Reference

See IDatabaseService for service methods.

See DatabaseConnectionInfo for parsed connection info fields.

On this page