|
| 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:6.0 |
| 23 | + |
| 24 | +import PackageDescription |
| 25 | + |
| 26 | +let package = Package( |
| 27 | + name: "CrateDbDemo", |
| 28 | + dependencies: [ |
| 29 | + .package(url: "https://github.com/vapor/postgres-kit.git", "2.0.0"..<"3.0.0") |
| 30 | + ], |
| 31 | + targets: [ |
| 32 | + .executableTarget( |
| 33 | + name: "CrateDbDemo", |
| 34 | + dependencies: [.product(name: "PostgresKit", package: "postgres-kit")], |
| 35 | + path: "Sources" |
| 36 | + ), |
| 37 | + ] |
| 38 | +) |
| 39 | +``` |
| 40 | +`Sources/main.swift` |
| 41 | +```swift |
| 42 | +import PostgresKit |
| 43 | + |
| 44 | +let configuration = try SQLPostgresConfiguration(url: "postgresql://crate:crate@localhost:5432/doc?tlsmode=disable") |
| 45 | +let source = PostgresConnectionSource(sqlConfiguration: configuration) |
| 46 | +let pool = EventLoopGroupConnectionPool( |
| 47 | + source: source, |
| 48 | + maxConnectionsPerEventLoop: 2, |
| 49 | + on: MultiThreadedEventLoopGroup.singleton |
| 50 | +) |
| 51 | +defer { pool.shutdown() } |
| 52 | + |
| 53 | +let db = pool.database(logger: .init(label: "test")).sql() |
| 54 | +let rows = try db.raw("SELECT * FROM sys.summits ORDER BY height DESC LIMIT 3;").all().wait() |
| 55 | + |
| 56 | +struct Record: Codable { |
| 57 | + var mountain: String |
| 58 | + var region: String |
| 59 | + var height: Int |
| 60 | +} |
| 61 | + |
| 62 | +for row in rows { |
| 63 | + let record = try row.decode(model: Record.self) |
| 64 | + print("\(record.mountain): \(record.height)") |
| 65 | +} |
| 66 | +``` |
| 67 | + |
| 68 | +Start CrateDB using Docker or Podman, then compile and invoke the example program. |
| 69 | +```shell |
| 70 | +docker run --rm --publish=5432:5432 crate -Cdiscovery.type=single-node |
| 71 | +``` |
| 72 | +```shell |
| 73 | +swift run |
| 74 | +``` |
| 75 | + |
| 76 | +:::{rubric} CrateDB Cloud |
| 77 | +::: |
| 78 | + |
| 79 | +For connecting to CrateDB Cloud, use the `tlsmode=require` parameter, |
| 80 | +and replace username, password, and hostname with values matching |
| 81 | +your environment. |
| 82 | +```swift |
| 83 | +let configuration = try SQLPostgresConfiguration( url: "postgresql://admin:[email protected]:5432/doc?tlsmode=require") |
| 84 | +``` |
| 85 | + |
| 86 | + |
| 87 | +[postgres-kit]: https://swiftpackageindex.com/vapor/postgres-kit |
0 commit comments