-
-
Notifications
You must be signed in to change notification settings - Fork 89
Docs: DocC prepared statements examples + PostgresCodable schema hints; fix tuple decoding in test #594
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
zamderax
wants to merge
5
commits into
vapor:main
Choose a base branch
from
wendylabsinc:add-docc-examples
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Docs: DocC prepared statements examples + PostgresCodable schema hints; fix tuple decoding in test #594
Changes from all commits
Commits
Show all changes
5 commits
Select commit
Hold shift + click to select a range
c5ed6a8
Update documentation for PostgresNIO with new features and examples
zamderax a178d29
Enhance PostgresRow decoding and documentation examples
zamderax 06f206f
docs(prepared-statements): add DocC examples using .query and .withTr…
zamderax 62f0ad4
docs(PostgresCodable): add example schemas (SQL) alongside code sampl…
zamderax a10c711
addressing backticks and accidental commits to gitignore
zamderax File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -26,9 +26,198 @@ applications. | |
| task cancellation. The query interface makes use of backpressure to ensure that memory can not grow | ||
| unbounded for queries that return thousands of rows. | ||
|
|
||
| ``PostgresNIO`` runs efficiently on Linux and Apple platforms. On Apple platforms developers can | ||
| configure ``PostgresConnection`` to use `Network.framework` as the underlying transport framework. | ||
|
|
||
| ``PostgresNIO`` runs efficiently on Linux and Apple platforms. On Apple platforms developers can | ||
| configure ``PostgresConnection`` to use `Network.framework` as the underlying transport framework. | ||
|
|
||
| ## Quick Start | ||
|
|
||
| ### 1. Create and Run a PostgresClient | ||
|
|
||
| First, create a ``PostgresClient/Configuration`` and initialize your client: | ||
|
|
||
| ```swift | ||
| import PostgresNIO | ||
|
|
||
| // Configure the client with individual parameters | ||
| let config = PostgresClient.Configuration( | ||
| host: "localhost", | ||
| port: 5432, | ||
| username: "my_username", | ||
| password: "my_password", | ||
| database: "my_database", | ||
| tls: .disable | ||
| ) | ||
|
|
||
| // Or parse from a PostgreSQL URL string | ||
| let urlString = "postgresql://username:password@localhost:5432/my_database" | ||
| let url = URL(string: urlString)! | ||
| let config = PostgresClient.Configuration( | ||
| host: url.host!, | ||
| port: url.port ?? 5432, | ||
| username: url.user!, | ||
| password: url.password, | ||
| database: url.path.trimmingPrefix("/"), | ||
| tls: .disable | ||
| ) | ||
|
|
||
| // Create the client | ||
| let client = PostgresClient(configuration: config) | ||
|
|
||
| // Run the client (required) | ||
| await withTaskGroup(of: Void.self) { taskGroup in | ||
| taskGroup.addTask { | ||
| await client.run() | ||
| } | ||
|
|
||
| // Your application code using the client goes here | ||
|
|
||
| // Shutdown when done | ||
| taskGroup.cancelAll() | ||
| } | ||
| ``` | ||
|
|
||
| ### 2. Running Queries with PostgresQuery | ||
|
|
||
| Use string interpolation to safely execute queries with parameters: | ||
|
|
||
| ```swift | ||
| // Simple SELECT query | ||
| let minAge = 21 | ||
| let rows = try await client.query( | ||
| "SELECT * FROM users WHERE age > \(minAge)", | ||
| logger: logger | ||
| ) | ||
|
|
||
| for try await row in rows { | ||
| let randomAccessRow = row.makeRandomAccess() | ||
| let id: Int = try randomAccessRow.decode(column: "id", as: Int.self, context: .default) | ||
| let name: String = try randomAccessRow.decode(column: "name", as: String.self, context: .default) | ||
| print("User: \(name) (ID: \(id))") | ||
| } | ||
|
|
||
| // INSERT query | ||
| let name = "Alice" | ||
| let email = "alice@example.com" | ||
| try await client.execute( | ||
| "INSERT INTO users (name, email) VALUES (\(name), \(email))", | ||
| logger: logger | ||
| ) | ||
| ``` | ||
|
|
||
| ### 3. Building Dynamic Queries with PostgresBindings | ||
|
|
||
| For complex or dynamic queries, manually construct bindings: | ||
|
|
||
| ```swift | ||
| func buildSearchQuery(filters: [String: Any]) -> PostgresQuery { | ||
| var bindings = PostgresBindings() | ||
| var sql = "SELECT * FROM products WHERE 1=1" | ||
|
|
||
| if let name = filters["name"] as? String { | ||
| bindings.append(name) | ||
| sql += " AND name = $\(bindings.count)" | ||
| } | ||
|
|
||
| if let minPrice = filters["minPrice"] as? Double { | ||
| bindings.append(minPrice) | ||
| sql += " AND price >= $\(bindings.count)" | ||
| } | ||
|
|
||
| return PostgresQuery(unsafeSQL: sql, binds: bindings) | ||
| } | ||
|
|
||
| // Execute the dynamic query | ||
| let filters = ["name": "Widget", "minPrice": 9.99] | ||
| let query = buildSearchQuery(filters: filters) | ||
| let rows = try await client.query(query, logger: logger) | ||
| ``` | ||
|
|
||
| ### 4. Using Transactions with withTransaction | ||
|
|
||
| Execute multiple queries atomically: | ||
|
|
||
| ```swift | ||
| try await client.withTransaction { connection in | ||
| // All queries execute within a transaction | ||
|
|
||
| // Debit from account | ||
| try await connection.execute( | ||
| "UPDATE accounts SET balance = balance - \(amount) WHERE id = \(fromAccount)", | ||
| logger: logger | ||
| ) | ||
|
|
||
| // Credit to account | ||
| try await connection.execute( | ||
| "UPDATE accounts SET balance = balance + \(amount) WHERE id = \(toAccount)", | ||
| logger: logger | ||
| ) | ||
|
|
||
| // If any query fails, the entire transaction rolls back | ||
| // If this closure completes successfully, the transaction commits | ||
| } | ||
| ``` | ||
|
|
||
| ### 5. Using withConnection for Multiple Queries | ||
|
|
||
| Execute multiple queries on the same connection for better performance: | ||
|
Collaborator
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Why does this yield better performance? |
||
|
|
||
| ```swift | ||
| try await client.withConnection { connection in | ||
| let userRows = try await connection.query( | ||
| "SELECT * FROM users WHERE id = \(userID)", | ||
| logger: logger | ||
| ) | ||
|
|
||
| let orderRows = try await connection.query( | ||
| "SELECT * FROM orders WHERE user_id = \(userID)", | ||
| logger: logger | ||
| ) | ||
|
|
||
| // Process results... | ||
| } | ||
| ``` | ||
|
|
||
| For more details, see <doc:running-queries>. | ||
|
|
||
| ### 6. Using Custom Types with PostgresCodable | ||
|
|
||
| Many Swift types already work out of the box. For custom types, implement ``PostgresEncodable`` and ``PostgresDecodable``: | ||
|
|
||
| ```swift | ||
| // Store complex data as JSONB | ||
| struct UserProfile: Codable { | ||
| let displayName: String | ||
| let bio: String | ||
| let interests: [String] | ||
| } | ||
|
|
||
| // Use directly in queries (encodes as JSONB automatically via Codable) | ||
| let profile = UserProfile( | ||
| displayName: "Alice", | ||
| bio: "Swift developer", | ||
| interests: ["coding", "hiking"] | ||
| ) | ||
|
|
||
| try await client.execute( | ||
| "UPDATE users SET profile = \(profile) WHERE id = \(userID)", | ||
| logger: logger | ||
| ) | ||
|
|
||
| // Decode from results | ||
| let rows = try await client.query( | ||
| "SELECT profile FROM users WHERE id = \(userID)", | ||
| logger: logger | ||
| ) | ||
|
|
||
| for try await row in rows { | ||
| let randomAccessRow = row.makeRandomAccess() | ||
| let profile = try randomAccessRow.decode(column: "profile", as: UserProfile.self, context: .default) | ||
|
Collaborator
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. I'm not sure this compiles. Shouldn't |
||
| print("Display name: \(profile.displayName)") | ||
| } | ||
| ``` | ||
|
|
||
| For advanced usage including custom PostgreSQL types, binary encoding, and RawRepresentable enums, see <doc:postgres-codable>. | ||
|
|
||
| ## Topics | ||
|
|
||
| ### Essentials | ||
|
|
@@ -40,6 +229,7 @@ configure ``PostgresConnection`` to use `Network.framework` as the underlying tr | |
|
|
||
| ### Advanced | ||
|
|
||
| - <doc:postgres-codable> | ||
| - <doc:coding> | ||
| - <doc:prepared-statement> | ||
| - <doc:listen> | ||
|
|
||
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
I consider this an anti-pattern. ask for the columns in the sql statement and then decode in one go.
row.makeRandomAccess()makes this slower than it needs to be.