# Swift

Connect to ParticleDB from Swift, run parameterized queries, handle transactions and errors.

Source: https://particledb.ai/sdks/swift/

Use the configured address for your client. See [connection addresses](/installation/ports/) and [security](/guides/security/). The examples use the SQL client address unless they explicitly select the HTTP API or ParticleDB JDBC driver.

Use [PostgresNIO](https://github.com/vapor/postgres-nio) over the SQL client interface (port 5432) from
server-side Swift (macOS or Linux). Interpolated values are sent as bind parameters.

## Install

```swift
// swift-tools-version:5.9
import PackageDescription

let package = Package(
    name: "Demo",
    platforms: [.macOS(.v13)],
    dependencies: [
        .package(url: "https://github.com/vapor/postgres-nio.git", from: "1.33.0"),
    ],
    targets: [
        .executableTarget(name: "Demo", dependencies: [
            .product(name: "PostgresNIO", package: "postgres-nio"),
        ]),
    ]
)
```

## Quick start

The example connects as `postgres` with the password `secret`, for a server started with
`particledb start --auth-method scram-sha-256 --pg-password secret`. With the server's default
`--auth-method password`, connect with TLS (`tls: .require(...)`); see
[TLS and authentication](/connectivity/tls/#authentication).

```swift
import PostgresNIO
import Logging

let config = PostgresClient.Configuration(
    host: "localhost",
    port: 5432,
    username: "postgres",
    password: "secret",
    database: "particledb",
    tls: .disable
)
let client = PostgresClient(configuration: config)

try await withThrowingTaskGroup(of: Void.self) { group in
    group.addTask { await client.run() }   // drives the connection pool

    try await client.query("CREATE TABLE users (id BIGINT PRIMARY KEY, name TEXT)")

    let id: Int64 = 1
    let name = "Alice"
    // Interpolated values are sent as bind parameters, not spliced into the SQL text
    try await client.query("INSERT INTO users (id, name) VALUES (\(id), \(name))")

    let rows = try await client.query("SELECT id, name FROM users WHERE id = \(id)")
    for try await (rowID, rowName) in rows.decode((Int64, String).self) {
        print(rowID, rowName)
    }

    // Transaction: commits if the closure returns, rolls back if it throws
    let logger = Logger(label: "app")
    try await client.withTransaction(logger: logger) { conn in
        try await conn.query("INSERT INTO users (id, name) VALUES (\(Int64(2)), \("Bob"))",
                             logger: logger)
    }
    let count = try await client.query("SELECT count(*) FROM users")
    for try await n in count.decode(Int64.self) { print("count", n) }

    group.cancelAll()
}
```

Output:

```
1 Alice
count 2
```

## iOS and macOS apps

An app installed on users' devices should not hold database credentials. Call your own
backend service from the app, and let that service talk to ParticleDB.

## Next steps

- [SQL Reference](/sql/overview/). SQL syntax and examples
- [SQL client connections](/connectivity/pg-wire/). connection settings and compatibility
- [Vector Search](/sql/vector-search/). vector search SQL syntax
