Database Driver Design logo

Database Driver Design

Organization
wendylabsinc
database-driver-design

Expert guidance on building Swift database client libraries. Use when developers mention: (1) building a database driver, (2) wire protocol implementation, (3) connection pooling design, (4) state machines for protocol handling, (5) NIO channel handlers for databases, (6) backpressure in result streaming, (7) actor executor alignment with NIO.

Overview

Publisherwendylabsinc
Repositoryclaude-skills
Skill namedatabase-driver-design
Stars
62
Forks
5
Bundled files
Instructions only
Links
  • Markdown instructions

    A SKILL.md file the model loads on demand, so it only costs tokens when a request actually matches.

  • Works with any LLM

    AI skills are plain Markdown, not provider-specific code, so this works with GPT, Claude, Gemini, Grok, or a local model.

  • Self-contained

    Everything the model needs lives in the instructions — no extra files to sync.

  • Open source

    Published by wendylabsinc on GitHub. Read the source before you install it.

Installation

Install the Database Driver Design AI skill in TypingMind to use it with any LLM, or drop it into another agent that reads SKILL.md.

1

Install in TypingMind

TypingMind installs a skill straight from its GitHub folder — it reads SKILL.md, bundles the resource files, and stores the result locally.

  1. Open the app and go to Plugins → Skills.
  2. Choose "Install from GitHub".
  3. Paste the skill folder URL below and confirm.
    https://github.com/wendylabsinc/claude-skills/tree/main/database-driver-design
  4. Enable the skill in any chat where you want it available.
Plugins → Skills → Add skill → From GitHub URL, then paste the folder URL and press Continue.
2

Install in another agent

Any agent that reads the Agent Skills format can use this skill — copy the folder into that agent's skills directory.

Claude Code — .claude/skills
git clone --depth 1 https://github.com/wendylabsinc/claude-skills.git /tmp/claude-skills
mkdir -p .claude/skills
cp -r /tmp/claude-skills/database-driver-design .claude/skills/database-driver-design
Restart Claude Code after copying so it picks up the new skill.

Use it in TypingMind

Enable Database Driver Design in any TypingMind chat and the model takes it from there. Its name and description sit in the system prompt, and the moment a request matches, the model loads the full instructions itself — you never invoke it by hand, and it costs no tokens until it is actually used.

The model loads Database Driver Design on its own as soon as a request matches it.

Works with any AI model

AI skills are plain Markdown instructions rather than provider-specific code, so Database Driver Design is not tied to the model it was written for. Install it once in TypingMind and use it with GPT-5, Claude, Gemini, Grok, DeepSeek, Mistral, Llama, or a local model you run yourself — all on your own API keys.

  • Loaded only when it is needed

    The system prompt carries just the name and description. The instructions are fetched on the first matching request, so an idle skill costs nothing.

  • Switch models mid-chat

    Because the skill is instructions rather than code, changing model does not break it — the next model reads the same SKILL.md.

Skill instructions

This is the SKILL.md content the model loads. Read it before installing — a skill is instructions your model will follow.

Database Driver Design

This skill provides expert guidance on building production-quality database client libraries in Swift, covering wire protocol implementation, connection management, type-safe APIs, and integration with Swift Concurrency. Patterns are derived from exemplary implementations: valkey-swift and postgres-nio.

Agent Behavior Contract (Follow These Rules)

  1. Prefer parameterized queries - Never concatenate user input into SQL/command strings
  2. Use string interpolation for safety - Implement ExpressibleByStringInterpolation to convert values to bindings
  3. Design commands as types - Each command/query should be a struct with associated response type
  4. Implement state machines for protocols - Complex connection lifecycles need explicit state transitions
  5. Support backpressure - Row/result streaming must respect consumer demand
  6. Align actor executors - Use unownedExecutor to align with NIO event loops
  7. Pool connections properly - Implement keep-alive, idle timeout, and graceful shutdown

Core Patterns

Command as Type Pattern

Define commands as types with associated response types for compile-time safety:

swift
public protocol DatabaseCommand: Sendable, Hashable {
    associatedtype Response: Decodable
    static var name: String { get }
    func encode(into encoder: inout CommandEncoder)
}

public struct GET: DatabaseCommand {
    public typealias Response = String?
    public static var name: String { "GET" }
    public let key: String

    public func encode(into encoder: inout CommandEncoder) {
        encoder.encode(Self.name, key)
    }
}

SQL Injection Prevention via String Interpolation

swift
public struct Query: ExpressibleByStringInterpolation {
    public var sql: String
    public var bindings: Bindings

    public struct StringInterpolation: StringInterpolationProtocol {
        var sql: String = ""
        var bindings: Bindings = Bindings()

        public mutating func appendLiteral(_ literal: String) {
            sql.append(literal)
        }

        public mutating func appendInterpolation<T: Encodable>(_ value: T) {
            bindings.append(value)
            sql.append("$\(bindings.count)")
        }
    }
}

// Usage: let query: Query = "SELECT * FROM users WHERE id = \(userId)"
// Result: sql = "SELECT * FROM users WHERE id = $1", bindings = [userId]

Actor with NIO Executor Alignment

Eliminate context switches by aligning actor executor with NIO event loop:

swift
public final actor Connection: Sendable {
    nonisolated public let unownedExecutor: UnownedSerialExecutor

    init(channel: any Channel) {
        self.unownedExecutor = channel.eventLoop.executor.asUnownedSerialExecutor()
    }
}

State Machine with Actions Pattern

Manage complex protocol state with explicit transitions and actions:

swift
struct ConnectionStateMachine {
    enum State {
        case idle
        case executing(QueryStateMachine)
        case closing
        case closed
        case modifying // Prevents COW during mutations
    }

    enum Action {
        case sendMessage(Message)
        case forwardResult(Result)
        case closeConnection
        case none
    }

    private var state: State = .idle

    mutating func handle(_ message: Message) -> Action {
        switch (state, message) {
        case (.idle, .query(let q)):
            state = .executing(QueryStateMachine(q))
            return .sendMessage(.parse(q))
        // ... other transitions
        }
    }
}

Length-Prefixed Binary Encoding

Write length-prefixed data with placeholder and backfill:

swift
extension Encodable {
    func encodeRaw(into buffer: inout ByteBuffer) throws {
        // Write placeholder for length (4 bytes for Int32)
        let lengthIndex = buffer.writerIndex
        buffer.writeInteger(Int32(0))

        // Record position before encoding
        let startIndex = buffer.writerIndex

        // Encode the actual value
        try self.encode(into: &buffer)

        // Calculate and write actual length
        let length = buffer.writerIndex - startIndex
        buffer.setInteger(Int32(length), at: lengthIndex)
    }
}

Protocol Hierarchy for Encoding/Decoding

Design tiered protocols for different encoding guarantees:

swift
// Base: runtime-determined type, may throw
public protocol ThrowingDynamicTypeEncodable: Sendable {
    func encode(into byteBuffer: inout ByteBuffer) throws
    var dataType: DataType { get }
}

// Non-throwing variant
public protocol DynamicTypeEncodable: ThrowingDynamicTypeEncodable {
    func encode(into byteBuffer: inout ByteBuffer)
}

// Static type info known at compile time
public protocol StaticTypeEncodable: ThrowingDynamicTypeEncodable {
    static var dataType: DataType { get }
}

// Non-throwing + static type info (most efficient)
public protocol NonThrowingEncodable: StaticTypeEncodable, DynamicTypeEncodable {}

Variadic Generic Row Decoding

Decode multiple columns type-safely using parameter packs:

swift
extension Row {
    func decode<each T: Decodable>(
        _ types: (repeat each T).Type
    ) throws -> (repeat each T) {
        var index = 0
        return (repeat try decodeColumn((each T).self, at: &index))
    }
}

// Usage: let (id, name, email) = try row.decode((Int.self, String.self, String.self))

Backpressure-Aware Streaming

Implement adaptive buffer strategy for result streaming:

swift
struct AdaptiveBuffer: BackPressureStrategy {
    var lowWatermark: Int
    var highWatermark: Int
    var currentTarget: Int

    mutating func didYield(bufferDepth: Int) -> Bool {
        // Shrink target if buffer too deep
        if bufferDepth > currentTarget * 2 {
            currentTarget = max(lowWatermark, currentTarget / 2)
        }
        return bufferDepth < currentTarget
    }

    mutating func didConsume(bufferDepth: Int) -> Bool {
        // Grow target if buffer drains completely
        if bufferDepth == 0 {
            currentTarget = min(highWatermark, currentTarget * 2)
        }
        return bufferDepth < currentTarget
    }
}

Connection Pool Integration

Conform connections to pool protocols:

swift
extension Connection: PooledConnection {
    public typealias ConnectionID = Int
}

struct KeepAliveBehavior: ConnectionKeepAliveBehavior {
    typealias Connection = Connection

    let frequency: Duration

    func runKeepAlive(for connection: Connection) async throws {
        _ = try await connection.ping()
    }
}

final class ClientMetrics: ConnectionPoolObservabilityDelegate {
    func connectionCreated(id: Int) { /* metrics */ }
    func connectionLeased(id: Int) { /* metrics */ }
    func connectionReleased(id: Int) { /* metrics */ }
    func connectionClosed(id: Int) { /* metrics */ }
}

Depth-Limited Parsing

Prevent stack overflow with nested structures:

swift
mutating func parseToken(maxDepth: Int = 100) throws -> Token {
    guard maxDepth > 0 else {
        throw ParsingError.tooDeeplyNested
    }

    switch tokenType {
    case .array:
        var elements: [Token] = []
        for _ in 0..<count {
            elements.append(try parseToken(maxDepth: maxDepth - 1))
        }
        return .array(elements)
    // ... other cases
    }
}

Quick Decision Tree

  1. Implementing wire protocol encoding/decoding?

    • Use length-prefixed messages with placeholder + backfill
    • Define protocol tokens as enums with associated values
    • Implement depth limits for nested structures
  2. Designing type-safe query API?

    • Use ExpressibleByStringInterpolation for injection prevention
    • Create Encodable/Decodable protocol hierarchies for type coercion
    • Use variadic generics for multi-column row decoding
  3. Managing connections?

    • Use actors with NIO executor alignment
    • Implement hierarchical state machines
    • Support cancellation via request IDs
  4. Implementing connection pooling?

    • Conform to PooledConnection protocol
    • Implement keep-alive behavior
    • Track metrics via observability delegate

Triage-First Playbook

  • "SQL Injection vulnerability"

    • Implement ExpressibleByStringInterpolation on query type
    • Convert interpolated values to $1, $2... parameter placeholders
  • "Type mismatch when decoding results"

    • Define Decodable protocol with typed throws
    • Wrap errors with column/cell context
  • "Connection state corruption"

    • Use hierarchical state machines with explicit transitions
    • Add .modifying sentinel to prevent COW issues
  • "Backpressure not working"

    • Implement adaptive buffer strategy
    • Signal demand through data source protocol

Best Practices Summary

  1. Commands/Queries as types - Each operation is a struct with associated response type
  2. String interpolation for safety - Prevent injection by design
  3. Protocol hierarchies for encoding - Different guarantees (throwing, static types, etc.)
  4. Length-prefixed wire formats - Write placeholder, encode, backfill length
  5. Hierarchical state machines - Compose child machines for complex protocols
  6. Adaptive backpressure - Dynamically adjust buffer targets based on consumer rate
  7. Actor + NIO alignment - Eliminate context switches with unownedExecutor
  8. Cell/Row wrappers - Rich metadata for better error messages
  9. Prepared statement caching - Deduplicate concurrent preparations
  10. Graceful shutdown - Drain pending operations before closing

Key Libraries for Reference

  • valkey-swift (github.com/valkey-io/valkey-swift) - Excellent RESP3 protocol, cluster support, pub/sub
  • postgres-nio (github.com/vapor/postgres-nio) - Excellent query safety, type coercion, state machines

Frequently asked questions

What does the Database Driver Design AI skill do?

Expert guidance on building Swift database client libraries. Use when developers mention: (1) building a database driver, (2) wire protocol implementation, (3) connection pooling design, (4) state machines for protocol handling, (5) NIO channel handlers for databases, (6) backpressure in result streaming, (7) actor executor alignment with NIO.

Why use Database Driver Design on TypingMind?

Because you install it once and use it with any model. Database Driver Design is plain Markdown rather than provider-specific code, so the same skill runs on GPT-5, Claude, Gemini, Grok, or a local model — and you can switch model mid-chat without it breaking. TypingMind runs on your own API keys, so you pay providers directly instead of a per-seat subscription, and your skills and chats stay in your own storage.

How do I install Database Driver Design in TypingMind?

Open Plugins → Skills → Install from GitHub in TypingMind and paste https://github.com/wendylabsinc/claude-skills/tree/main/database-driver-design. TypingMind reads its SKILL.md and installs it as a skill you can enable per chat.

Which AI models can use Database Driver Design?

Any model you connect in TypingMind. AI skills are plain Markdown instructions rather than provider-specific code, so GPT, Claude, Gemini, Grok, and local models can all load this skill when a request matches it.

How many AI models can I use with Database Driver Design?

As many as you like. As long as a model supports skills, you can use Database Driver Design with it — GPT, Claude, Gemini, Grok, DeepSeek, Mistral, Llama and more — all on TypingMind with your own API keys.

Is the Database Driver Design AI skill free?

It is published on GitHub by wendylabsinc. Check the repository for licensing terms. You only pay your own AI provider for the tokens you use.

What are AI skills?

An AI skill is a reusable instruction bundle that teaches an AI model how to do one specific task. It follows the open Agent Skills format: a SKILL.md file with a name and description, plus any scripts, templates or reference files the model may need. The model reads the instructions only when your request matches the skill, so an installed skill costs nothing until it is used.

How are AI skills different from plugins or MCP servers?

A plugin or MCP server gives a model new tools to call — code that runs somewhere and returns a result. An AI skill gives the model knowledge and process instead: how to approach a task, which steps to follow, what good output looks like. Skills are plain Markdown, so they need no server, no API key and no runtime, and they work with any model.

View all

Set up your own AI workspace now

Get notified about new features and future giveaways by subscribing to our newsletter 👇