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")
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
Configure connection pooling for production workloads:
let poolConfig = ConnectionPoolConfiguration(
minConnections: 2,
maxConnections: 20,
idleTimeout: 300, // 5 minutes
acquireTimeout: 30, // 30 seconds
healthCheckInterval: 60 // 1 minute
)
let backend = PostgreSQLBackend(
hostname: "localhost",
port: 5432,
username: "postgres",
password: "password",
database: "myapp",
poolConfiguration: poolConfig
)
SSL/TLS
Enable SSL for secure connections:
let backend = PostgreSQLBackend(
hostname: "db.example.com",
port: 5432,
username: "postgres",
password: "password",
database: "myapp",
tlsConfiguration: .clientDefault // Enable SSL
)
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
let logger = PrintQueryLogger(level: .queries, includeParameters: true)
let backend = PostgreSQLBackend(
hostname: "localhost",
port: 5432,
username: "postgres",
password: "password",
database: "myapp",
queryLogger: logger
)
Requirements
- PostgreSQL 14 or later
- UUID-OSSP extension (for UUID generation)
Next Steps
- Migrations - Manage schema changes
- Vapor Integration - Use with Vapor