PostgreSQL
PostgreSQL is the recommended database for production deployments. It offers robust features, excellent performance, and full support for all SwiftDataServer capabilities.
Installation
Add the PostgreSQL backend to your target:
.product(name: "PostgreSQLBackend", package: "SwiftDataServer.SDK")
Configuration
import SwiftDataServer
import PostgreSQLBackend
let backend = PostgreSQLBackend(
hostname: "localhost",
port: 5432,
username: "postgres",
password: "password",
database: "myapp"
)
try await backend.connect()
Environment Variables
Use environment variables for production configuration:
let backend = PostgreSQLBackend(
hostname: Environment.get("DB_HOST") ?? "localhost",
port: Environment.get("DB_PORT").flatMap(Int.init) ?? 5432,
username: Environment.get("DB_USER") ?? "postgres",
password: Environment.get("DB_PASS") ?? "password",
database: Environment.get("DB_NAME") ?? "myapp"
)
Connection Pooling
Set the pool size with DatabaseConfiguration and use the configuration: initializer:
let config = DatabaseConfiguration(
hostname: "localhost",
port: 5432,
username: "postgres",
password: "password",
database: "myapp",
maxConnections: 20, // pool size (default 10)
connectionTimeout: 30 // seconds (default 30)
)
let backend = PostgreSQLBackend(configuration: config)
SSL/TLS
Enable SSL by passing a TLSConfiguration in the database configuration:
let config = DatabaseConfiguration(
hostname: "db.example.com",
port: 5432,
username: "postgres",
password: "password",
database: "myapp",
tlsConfiguration: TLSConfiguration() // TLS with full certificate verification
)
let backend = PostgreSQLBackend(configuration: config)
Type Mappings
| Swift Type | PostgreSQL Type |
|---|---|
String | TEXT |
Int | BIGINT |
Int32 | INTEGER |
Int16 | SMALLINT |
Double | DOUBLE PRECISION |
Float | REAL |
Bool | BOOLEAN |
Date | TIMESTAMP WITH TIME ZONE |
UUID | UUID |
Data | BYTEA |
[Codable] | JSONB |
Transactions
try await backend.transaction {
let context = container.mainContext
let user = User(name: "Alice", email: "alice@example.com", age: 28)
context.insert(user)
let post = Post(title: "Hello", content: "World")
post.author = user
context.insert(post)
try await context.saveAsync()
// Both saved atomically
}
Query Logging
Enable SQL query logging via DatabaseConfiguration:
let config = DatabaseConfiguration(
hostname: "localhost",
port: 5432,
username: "postgres",
password: "password",
database: "myapp",
logQueries: true
)
let backend = PostgreSQLBackend(configuration: config)
Requirements
- PostgreSQL 14 or later
- UUID-OSSP extension (for UUID generation)
Next Steps
- Migrations - Manage schema changes
- Vapor Integration - Use with Vapor