Skip to content

Latest commit

 

History

History
123 lines (90 loc) · 4.56 KB

File metadata and controls

123 lines (90 loc) · 4.56 KB

CosmoSQLClient-Swift

A lightweight, high-performance database client for Swift built natively on SwiftNIO. CosmoSQLClient-Swift provides a unified async/await API for Microsoft SQL Server, PostgreSQL, MySQL/MariaDB, and SQLite, with zero external C library dependencies for network protocols.

Key Features

  • Unified API: A single SQLDatabase protocol for all four database engines, enabling backend-agnostic application code.
  • Native Protocol Implementation: Pure Swift implementations of TDS 7.4 (SQL Server), PostgreSQL v3, and MySQL v10 wire protocols.
  • High-Performance Streaming: Reactive row streaming and industry-first JSON streaming (queryJsonStream) that yields objects as they arrive without full result buffering.
  • Zero-Dependency Core: No requirement for FreeTDS, ODBC, or other legacy C libraries.
  • Lightweight & Efficient: Designed for low-latency and high-throughput, matching or beating native drivers in many scenarios.
  • Strict Concurrency: Fully compatible with Swift 6 strict concurrency requirements.

Supported Database Engines

Engine Protocol Key Features
SQL Server TDS 7.4 Integrated Security (NTLM), Stored Procedures, Named Instances, TLS/SSL
PostgreSQL v3 MD5/Scram-SHA-256 Auth, Transactions, Parameterized Queries
MySQL / MariaDB v10 Standard Auth, Transactions, Parameterized Queries
SQLite Native In-memory support, WAL mode, Logical/Binary Backup

Installation

Add CosmoSQLClient-Swift to your Package.swift dependencies:

dependencies: [
    .package(url: "https://github.com/vkuttyp/CosmoSQLClient-Swift.git", from: "1.0.0")
]

Then, add the specific driver to your target:

.target(
    name: "MyApp",
    dependencies: [
        .product(name: "CosmoMSSQL", package: "CosmoSQLClient-Swift"),
        .product(name: "CosmoPostgres", package: "CosmoSQLClient-Swift"),
        .product(name: "CosmoMySQL", package: "CosmoSQLClient-Swift"),
        .product(name: "CosmoSQLite", package: "CosmoSQLClient-Swift")
    ]
)

Quick Start

Basic Query (SQL Server)

import CosmoMSSQL

let config = try MSSQLConnection.Configuration(connectionString: 
    "Server=localhost;Database=Sales;User Id=sa;Password=your_password;Encrypt=True;TrustServerCertificate=True;"
)

let conn = try await MSSQLConnection.connect(configuration: config)
defer { Task { try? await conn.close() } }

let rows = try await conn.query(
    "SELECT id, name, salary FROM employees WHERE active = @p1",
    [.bool(true)]
)

for row in rows {
    let name = row["name"].asString() ?? "Unknown"
    print("Employee: \(name)")
}

JSON Streaming (Industry First)

Stream large JSON results directly from the wire, yielding objects immediately as they are fully received.

// Decodes directly into your Codable model, one object at a time
for try await product in conn.queryJsonStream(
    "SELECT Id, Name, Price FROM Products FOR JSON PATH",
    as: Product.self) 
{
    print("Received: \(product.Name)")
}

Unified API (SQLDatabase Protocol)

Write business logic once and run it on any supported database:

func fetchUsers(db: any SQLDatabase) async throws -> [User] {
    return try await db.query("SELECT * FROM users", as: User.self)
}

// Works identically with any CosmoSQL driver
let mssqlUsers = try await fetchUsers(db: mssqlConn)
let pgUsers    = try await fetchUsers(db: postgresConn)

Technical Architecture

CosmoSQLClient-Swift utilizes a non-blocking I/O architecture powered by SwiftNIO.

  • Async/Await Native: Built from the ground up for Swift's modern concurrency model.
  • Stateful Parsing: Uses state machine based protocol decoders to ensure efficient, zero-copy processing of network packets.
  • Actor-Based Pooling: Built-in connection pooling ensures thread-safe and efficient connection management under load.

Performance Benchmarks

Measured on Apple Silicon (M-series) against local databases.

Scenario CosmoSQL (Swift) Native Driver / Competitor
MSSQL Warm Query 0.95 ms 1.58 ms (FreeTDS)
Postgres Single-Row 0.24 ms 0.30 ms (postgres-nio)

Related Projects

  • CosmoSQLClient-Dotnet — The .NET port of this library, offering the same unified API and performance principles.
  • SQLClient-Swift — The original MSSQL driver using FreeTDS (predecessor to this package).

License

Licensed under the MIT License.