-
Notifications
You must be signed in to change notification settings - Fork 0
Getting Started
To add SQLServerNIO to your project, declare it as a dependency in your Package.swift file.
// swift-tools-version: 6.0
import PackageDescription
let package = Package(
name: "MyServerApp",
dependencies: [
.package(url: "https://github.com/tashda/sqlserver-nio.git", from: "0.2.0")
],
targets: [
.target(
name: "MyServerApp",
dependencies: [
.product(name: "SQLServerNIO", package: "sqlserver-nio")
]
)
]
)Before you connect, you need to initialize a SQLServerClient.Configuration object. This defines the host, credentials, SSL requirements, retry policies, and session options for your database connections.
import SQLServerNIO
var configuration = SQLServerClient.Configuration(
hostname: "localhost", // Server address
port: 1433, // Standard SQL Server port
login: .init(
database: "master", // Default database to target
authentication: .sqlPassword(username: "sa", password: "<your_password>")
),
tlsConfiguration: .makeClientConfiguration() // Built-in NIO SSL tools
)You can mirror common SQL Server Management Studio defaults to optimize network IO. For example, NOCOUNT suppresses "X rows affected" messages which reduces network chatter:
configuration.connection.sessionOptions = .init(
nocount: true, // Recommended: suppress (1 row affected)
fmtOnlyOff: true,
additionalStatements: ["SET DEADLOCK_PRIORITY LOW;"] // Fire upon connection
)The recommended approach is to use the SQLServerClient. This encapsulates a connection pool that automatically spins up, validates, and recycles connections, providing massive performance gains for concurrent environments like vapor/hummingbird backends.
// Connect and initialize the pool
let client = try await SQLServerClient.connect(configuration: configuration)
// Execute queries using the connection pool
let rows = try await client.query("SELECT @@VERSION AS version")
if let versionString = rows.first?.column("version")?.string {
print("Connected to: \(versionString)")
}
// Gracefully shut down the client when your app stops
try await client.shutdownGracefully()If you are writing a script or a highly specialized administrative tool where you strictly need a single TCP stream, you can use SQLServerConnection.
// Note we pass `configuration.connection` here
let connection = try await SQLServerConnection.connect(configuration: configuration.connection)
let databases = try await connection.listDatabases()
print("Found \(databases.count) databases.")
try await connection.close()Note: The pooled client is capable of handling single-connection sequences natively (e.g., Transactions) using client.withConnection { conn in ... }.