|
| 1 | +(connect-swift)= |
| 2 | + |
| 3 | +# Swift |
| 4 | + |
| 5 | +:::{include} /_include/links.md |
| 6 | +::: |
| 7 | + |
| 8 | +:::{div} sd-text-muted |
| 9 | +Connect to CrateDB from Swift applications. |
| 10 | +::: |
| 11 | + |
| 12 | +:::{rubric} About |
| 13 | +::: |
| 14 | + |
| 15 | +[postgres-kit] is a non-blocking, event-driven Swift client for PostgreSQL. |
| 16 | + |
| 17 | +:::{rubric} Synopsis |
| 18 | +::: |
| 19 | + |
| 20 | +`Package.swift` |
| 21 | +```swift |
| 22 | +// swift-tools-version: 5.7 |
| 23 | +// The swift-tools-version declares the minimum version of Swift required to build this package. |
| 24 | + |
| 25 | +import PackageDescription |
| 26 | + |
| 27 | +let package = Package( |
| 28 | + name: "CrateDbDemo", |
| 29 | + dependencies: [ |
| 30 | + .package(url: "https://github.com/vapor/postgres-kit.git", "2.0.0"..<"3.0.0") |
| 31 | + ], |
| 32 | + targets: [ |
| 33 | + .executableTarget( |
| 34 | + name: "CrateDbDemo", |
| 35 | + dependencies: [.product(name: "PostgresKit", package: "postgres-kit")], |
| 36 | + path: "Sources" |
| 37 | + ), |
| 38 | + ] |
| 39 | +) |
| 40 | +``` |
| 41 | +`Sources/main.swift` |
| 42 | +```swift |
| 43 | +import PostgresKit |
| 44 | + |
| 45 | +let configuration = try SQLPostgresConfiguration(url: "postgresql://crate:crate@localhost:5432/doc?tlsmode=disable") |
| 46 | +let source = PostgresConnectionSource(sqlConfiguration: configuration) |
| 47 | +let pool = EventLoopGroupConnectionPool( |
| 48 | + source: source, |
| 49 | + maxConnectionsPerEventLoop: 2, |
| 50 | + on: MultiThreadedEventLoopGroup.singleton |
| 51 | +) |
| 52 | +defer { pool.shutdown() } |
| 53 | + |
| 54 | +let db = pool.database(logger: .init(label: "test")).sql() |
| 55 | +let rows = try await db.raw("SELECT * FROM sys.summits ORDER BY height DESC LIMIT 3;").all().get() |
| 56 | + |
| 57 | +struct Record: Codable { |
| 58 | + var mountain: String |
| 59 | + var region: String |
| 60 | + var height: Int |
| 61 | +} |
| 62 | + |
| 63 | +for row in rows { |
| 64 | + let record = try row.decode(model: Record.self) |
| 65 | + print("\(record.mountain): \(record.height)") |
| 66 | +} |
| 67 | +``` |
| 68 | + |
| 69 | +Start CrateDB using Docker or Podman, then compile and invoke example program. |
| 70 | +```shell |
| 71 | +docker run --rm --publish=5432:5432 crate -Cdiscovery.type=single-node |
| 72 | +``` |
| 73 | +```shell |
| 74 | +swift run |
| 75 | +``` |
| 76 | + |
| 77 | +:::{rubric} CrateDB Cloud |
| 78 | +::: |
| 79 | + |
| 80 | +For connecting to CrateDB Cloud, use the `tlsmode=require` parameter, |
| 81 | +and replace username, password, and hostname with values matching |
| 82 | +your environment. |
| 83 | +```swift |
| 84 | +let configuration = try SQLPostgresConfiguration( url: "postgresql://admin:[email protected]:5432/doc?tlsmode=require") |
| 85 | +``` |
| 86 | + |
| 87 | + |
| 88 | +[postgres-kit]: https://swiftpackageindex.com/vapor/postgres-kit |
0 commit comments