### Execute CreateTestEnvironment.sql script Source: https://github.com/codewinsdotcom/postgresclientkit/blob/master/Docs/setting_up_a_postgres_database_for_testing.md Commands to navigate to the script directory and execute the database setup script using psql. ```bash cd /Tests/Scripts psql --host= --port= --dbname= --username= < CreateTestEnvironment.sql ``` ```bash psql --host=127.0.0.1 --port=5432 --dbname=postgres --username=root < CreateTestEnvironment.sql ``` -------------------------------- ### Configure and Use Connection Pool Source: https://context7.com/codewinsdotcom/postgresclientkit/llms.txt Demonstrates setting up a connection pool with custom configurations for maximum connections, timeouts, and logging. Shows both automatic connection release using `withConnection` and manual management with `acquireConnection` and `releaseConnection`. Includes an example of retrieving pool performance metrics. ```swift import PostgresClientKit import Foundation // Configure the connection pool var poolConfig = ConnectionPoolConfiguration() poolConfig.maximumConnections = 10 // Max connections in pool poolConfig.maximumPendingRequests = 100 // Max queued requests poolConfig.pendingRequestTimeout = 30 // Seconds to wait for connection poolConfig.allocatedConnectionTimeout = 300 // Max time to hold a connection poolConfig.metricsLoggingInterval = 3600 // Log metrics every hour // Configure connections in the pool var connConfig = ConnectionConfiguration() connConfig.host = "localhost" connConfig.database = "myapp" connConfig.user = "appuser" connConfig.credential = .scramSHA256(password: "secret") // Create the pool let pool = ConnectionPool( connectionPoolConfiguration: poolConfig, connectionConfiguration: connConfig ) def pool.close() } // Acquire connection with automatic release using withConnection pool.withConnection { result in do { let connection = try result.get() // Connection is automatically released when this block exits let statement = try connection.prepareStatement( text: "SELECT COUNT(*) FROM users" ) defer { statement.close() } let cursor = try statement.execute() if let row = try cursor.next()?.get() { let count = try row.columns[0].int() print("User count: \(count)") } } catch { print("Database error: \(error)") } } // Manual connection management with acquireConnection pool.acquireConnection { result in do { let connection = try result.get() defer { pool.releaseConnection(connection) } // Must release manually // Use connection... let statement = try connection.prepareStatement(text: "SELECT now()") defer { statement.close() } let cursor = try statement.execute() if let row = try cursor.next()?.get() { let now = try row.columns[0].timestampWithTimeZone() print("Server time: \(now)") } } catch { print("Error: \(error)") } } // Get pool performance metrics let metrics = pool.computeMetrics(reset: false) print("Successful requests: \(metrics.successfulRequests)") print("Avg acquire time: \(metrics.averageTimeToAcquireConnection)s") print("Connections: \(metrics.connectionsAtEndOfPeriod)") ``` -------------------------------- ### Configure CocoaPods Dependency Source: https://github.com/codewinsdotcom/postgresclientkit/blob/master/README.md Add the pod specification to your Podfile and run pod install. ```ruby target 'MyApp' do pod 'PostgresClientKit', '~> 1.0' end ``` -------------------------------- ### Initialize PostgresByteA from Hex String Source: https://github.com/codewinsdotcom/postgresclientkit/blob/master/Docs/API/Structs/PostgresByteA.html Creates a PostgresByteA instance from a hex-formatted string. The string should start with \x and be followed by two hex digits per byte. Supports both uppercase and lowercase hex digits. ```swift public init?(_ hexEncoded: String) ``` -------------------------------- ### Create PostgresDate from String Source: https://github.com/codewinsdotcom/postgresclientkit/blob/master/Docs/API/Structs/PostgresDate.html Initializes a PostgresDate from a string. The string must conform to the 'yyyy-MM-dd' format. For example, '2019-03-14'. ```swift public init?(_ string: String) ``` -------------------------------- ### Decode Row by Column Index Source: https://github.com/codewinsdotcom/postgresclientkit/blob/master/Docs/API/Structs/Row.html Example demonstrating how to decode a row into a custom struct using column index order. ```Swift struct Weather: Decodable { let city: String let lowestTemperature: Int let highestTemperature: Int let precipitation: Double? let date: PostgresDate } let connection: Connection = ... // Notice that the columns must be in the same order as the Weather // properties, but may have different names. let text = "SELECT city, temp_lo, temp_hi, prcp, date FROM weather;" let statement = try connection.prepareStatement(text: text) let cursor = try statement.execute() for row in cursor { let weather = try row.get().decodeByColumnIndex(Weather.self) ... } ``` -------------------------------- ### Initialize and Use Logger - PostgresClientKit Source: https://github.com/codewinsdotcom/postgresclientkit/blob/master/Docs/API/Classes/Logger.html Demonstrates how to initialize a Logger, set its level and handler, create a LogRecord, and log it. Also shows the use of convenience methods for logging. ```swift let logger = Logger() logger.level = .warning logger.handler = ConsoleLogHandler() let record = LogRecord(level: .warning, message: "Watch out!", context: "Session-14", timestamp: Date(), file: #file, function: #function, line: #line) logger.log(record) // the record is logged (because LogLevel.warning >= logger.level) // Convenience methods make logging more concise. logger.warning("Watch out!", context: "Session-14") // Examples of other log levels: logger.severe("This is also logged") // because LogLevel.severe >= logger.level logger.info("This is not logged") // because LogLevel.info < logger.level ``` -------------------------------- ### Get PostgresTimestampWithTimeZone from Date Source: https://github.com/codewinsdotcom/postgresclientkit/blob/master/Docs/API/Extensions/Date.html Provides a PostgresTimestampWithTimeZone representation for the Swift Date. Equivalent to `PostgresTimestampWithTimeZone(date: self)`. ```swift var postgresTimestampWithTimeZone: PostgresTimestampWithTimeZone { get } ``` -------------------------------- ### Configure Connection Parameters Source: https://context7.com/codewinsdotcom/postgresclientkit/llms.txt Sets up host, port, database, and authentication credentials for a PostgreSQL connection. ```swift import PostgresClientKit var configuration = PostgresClientKit.ConnectionConfiguration() // Server connection settings configuration.host = "127.0.0.1" // Default: "localhost" configuration.port = 5432 // Default: 5432 configuration.database = "myapp" // Default: "postgres" // Authentication configuration.user = "appuser" configuration.credential = .scramSHA256(password: "secretpassword") // SSL/TLS encryption (recommended for production) configuration.ssl = true // Default: true configuration.socketTimeout = 30 // Timeout in seconds, 0 = no timeout // Application identification (visible in pg_stat_activity) configuration.applicationName = "MySwiftApp" // Default: "PostgresClientKit" ``` -------------------------------- ### Get TimeZone from PostgresTimeWithTimeZone Source: https://github.com/codewinsdotcom/postgresclientkit/blob/master/Docs/API/Structs/PostgresTimeWithTimeZone.html Retrieve the TimeZone associated with a PostgresTimeWithTimeZone instance. This indicates the time zone in which the time was specified. ```swift public var timeZone: TimeZone { get } ``` -------------------------------- ### Establish Database Connection Source: https://context7.com/codewinsdotcom/postgresclientkit/llms.txt Initializes a connection to the server and executes a simple query. ```swift import PostgresClientKit do { var configuration = ConnectionConfiguration() configuration.host = "localhost" configuration.database = "example" configuration.user = "bob" configuration.credential = .scramSHA256(password: "welcome1") let connection = try Connection(configuration: configuration) defer { connection.close() } // Always close when done // Check connection status print("Connection closed: \(connection.isClosed)") // false // Use connection for SQL operations... let statement = try connection.prepareStatement(text: "SELECT version()") defer { statement.close() } let cursor = try statement.execute() for row in cursor { let version = try row.get().columns[0].string() print("PostgreSQL version: \(version)") } } catch { print("Connection error: \(error)") } ``` -------------------------------- ### Build and Test Swift Package Source: https://github.com/codewinsdotcom/postgresclientkit/blob/master/README.md Commands to clean, build, and run tests for a Swift package. Requires a pre-configured PostgreSQL database for testing. ```bash cd swift package clean swift build swift test ``` -------------------------------- ### Initialize PostgresTime from components Source: https://github.com/codewinsdotcom/postgresclientkit/blob/master/Docs/API/Structs/PostgresTime.html Creates a PostgresTime instance using hour, minute, second, and nanosecond components. Nanoseconds are recorded in the same way as Foundation DateComponents. ```swift let time = PostgresTime(hour: 16, minute: 25, second: 19, nanosecond: 365000000) ``` -------------------------------- ### Decoding Row to Decodable Type Source: https://github.com/codewinsdotcom/postgresclientkit/blob/master/Docs/API/Structs/Row.html Example of mapping a database row to a Swift struct using decodeByColumnName. Requires retrieveColumnMetadata to be set to true during statement execution. ```Swift struct Weather: Decodable { let date: PostgresDate let city: String let temp_lo: Int let temp_hi: Int let prcp: Double? } let connection: Connection = ... // Note that the columns must have the same names as the Weather // properties, but may be in a different order. let text = "SELECT city, temp_lo, temp_hi, prcp, date FROM weather;" let statement = try connection.prepareStatement(text: text) let cursor = try statement.execute(retrieveColumnMetadata: true) for row in cursor { let weather = try row.get().decodeByColumnName(Weather.self) ... } ``` -------------------------------- ### PostgresTimestamp Initializers and Methods Source: https://github.com/codewinsdotcom/postgresclientkit/blob/master/Docs/API/Structs/PostgresTimestamp.html Methods for creating and converting PostgresTimestamp instances. ```APIDOC ## Initializers ### init(year:month:day:hour:minute:second:nanosecond:) Creates a PostgresTimestamp from individual date and time components. ### init(date:in:) Creates a PostgresTimestamp by interpreting a Foundation Date in a specified time zone. ### init(_:) Creates a PostgresTimestamp from a string conforming to 'yyyy-MM-dd HH:mm:ss.SSS' or 'yyyy-MM-dd HH:mm:ss'. ## Properties and Methods ### dateComponents Returns a DateComponents object containing the year, month, day, hour, minute, second, and nanosecond of the timestamp. ### date(in:) Creates a Foundation Date by interpreting the PostgresTimestamp in a specified time zone. ``` -------------------------------- ### Get DateComponents from PostgresDate Source: https://github.com/codewinsdotcom/postgresclientkit/blob/master/Docs/API/Structs/PostgresDate.html Provides a DateComponents value for the PostgresDate, setting the year, month, and day components. This is useful for accessing the date's components in a structured format. ```swift public var dateComponents: DateComponents { get } ``` -------------------------------- ### Initialize PostgresTimestamp from Components Source: https://github.com/codewinsdotcom/postgresclientkit/blob/master/Docs/API/Structs/PostgresTimestamp.html Creates a PostgresTimestamp by providing individual date and time components. Fractional seconds are specified in nanoseconds, though only millisecond resolution is preserved due to a Foundation DateFormatter bug. ```swift let timestamp = PostgresTimestamp(year: 2019, month: 3, day: 14, hour: 16, minute: 25, second: 19, nanosecond: 365000000) ``` -------------------------------- ### Declare ConnectionConfiguration Source: https://github.com/codewinsdotcom/postgresclientkit/blob/master/Docs/API/Structs.html Configuration settings for establishing a connection to a Postgres server. ```Swift public struct ConnectionConfiguration ``` -------------------------------- ### Create PostgresDate from components Source: https://github.com/codewinsdotcom/postgresclientkit/blob/master/Docs/API/Structs/PostgresDate.html Use this initializer to create a PostgresDate by providing year, month, and day components. This is useful for representing specific calendar dates. ```swift let date = PostgresDate(year: 2019, month: 3, day: 14) ``` -------------------------------- ### Initialize a ConnectionPool Source: https://github.com/codewinsdotcom/postgresclientkit/blob/master/Docs/API/Classes/ConnectionPool.html Creates a new instance of ConnectionPool using the specified pool and connection configurations. ```Swift public init(connectionPoolConfiguration: ConnectionPoolConfiguration, connectionConfiguration: ConnectionConfiguration, connectionDelegate: ConnectionDelegate? = nil) ``` -------------------------------- ### Initialize PostgresClientKit Connection Source: https://github.com/codewinsdotcom/postgresclientkit/blob/master/Docs/API/Classes/Connection.html Use this initializer to create a new Postgres connection with specified configuration and an optional delegate. It may throw a PostgresError if configuration fails. ```swift public init(configuration: ConnectionConfiguration, delegate: ConnectionDelegate? = nil) throws ``` -------------------------------- ### PostgresValue Initialization and Properties Source: https://github.com/codewinsdotcom/postgresclientkit/blob/master/Docs/API/Structs/PostgresValue.html Methods for creating a PostgresValue instance and inspecting its state. ```APIDOC ## init(_ rawValue: String?) ### Description Creates a PostgresValue from the raw value used in the Postgres network protocol. ### Parameters - **rawValue** (String?) - Required - The raw value, or nil to represent a SQL NULL value. ## rawValue ### Description The raw value used in the Postgres network protocol, or nil to represent a SQL NULL value. ## isNull ### Description Whether this PostgresValue represents a SQL NULL value. ### Response - **isNull** (Bool) - Returns true if the value is SQL NULL. ``` -------------------------------- ### Work with Postgres Date, Time, and Timestamp Types Source: https://context7.com/codewinsdotcom/postgresclientkit/llms.txt Illustrates the creation and usage of specialized PostgreSQL date, time, and timestamp types to maintain precision and avoid timezone conversion issues. Shows conversion to Foundation Date and usage as query parameters. ```swift import PostgresClientKit import Foundation // PostgresDate - year, month, day only let date1 = PostgresDate(year: 2024, month: 3, day: 14)! let date2 = PostgresDate("2024-03-14")! let date3 = PostgresDate(date: Date(), in: TimeZone.current) print("Date: \(date1)") // 2024-03-14 // Convert to Foundation Date (at midnight in specified timezone) let foundationDate = date1.date(in: TimeZone(identifier: "America/New_York")!) // PostgresTime - hour, minute, second, microsecond let time1 = PostgresTime(hour: 14, minute: 30, second: 45, nanosecond: 123_000_000)! let time2 = PostgresTime("14:30:45.123")! print("Time: \(time1)") // 14:30:45.123 // PostgresTimestamp - date + time without timezone let ts1 = PostgresTimestamp(year: 2024, month: 3, day: 14, hour: 14, minute: 30, second: 45, nanosecond: 0)! let ts2 = PostgresTimestamp("2024-03-14 14:30:45")! print("Timestamp: \(ts1)") // 2024-03-14 14:30:45 // PostgresTimestampWithTimeZone - includes timezone info let tstz1 = PostgresTimestampWithTimeZone( year: 2024, month: 3, day: 14, hour: 14, minute: 30, second: 45, nanosecond: 0, timeZone: TimeZone(identifier: "America/New_York")! )! let tstz2 = PostgresTimestampWithTimeZone(date: Date(), in: TimeZone.current) print("Timestamp with TZ: \(tstz1)") // 2024-03-14 14:30:45-04:00 // Convert to Foundation Date let moment: Date = tstz1.date // Using date/time types as parameters do { let statement = try connection.prepareStatement( text: "INSERT INTO events (name, event_date, event_time, created_at) VALUES ($1, $2, $3, $4)" ) defer { statement.close() } try statement.execute(parameterValues: [ "Conference", date1, // PostgresDate time1, // PostgresTime tstz2 // PostgresTimestampWithTimeZone ]) } catch { print("Error: \(error)") } ``` -------------------------------- ### Configure postgresql.conf settings Source: https://github.com/codewinsdotcom/postgresclientkit/blob/master/Docs/setting_up_a_postgres_database_for_testing.md Required settings for SSL and password encryption in the Postgres configuration file. ```text ssl = on password_encryption = scram-sha-256 ``` -------------------------------- ### Implement ConnectionDelegate for Server Notifications Source: https://context7.com/codewinsdotcom/postgresclientkit/llms.txt Shows how to implement the ConnectionDelegate protocol to receive asynchronous notifications, notices, and parameter status updates from the PostgreSQL server. Subscribe to a channel using 'LISTEN' to receive notifications. ```swift import PostgresClientKit class MyConnectionDelegate: ConnectionDelegate { // Called when server sends a NOTIFY func connection(_ connection: Connection, didReceiveNotification notification: (processId: Int, channel: String, payload: String)) { print("Notification on '\(notification.channel)': \(notification.payload)") } // Called when server sends a notice (warnings, info messages) func connection(_ connection: Connection, didReceiveNotice notice: Notice) { print("Server notice: \(notice.message ?? "")") } // Called when server parameter changes func connection(_ connection: Connection, didReceiveParameterStatus status: (name: String, value: String)) { print("Parameter \(status.name) = \(status.value)") } } do { let delegate = MyConnectionDelegate() let connection = try Connection(configuration: configuration, delegate: delegate) defer { connection.close() } // Subscribe to a notification channel let listenStmt = try connection.prepareStatement(text: "LISTEN my_events") defer { listenStmt.close() } try listenStmt.execute() // From another connection, you can send: NOTIFY my_events, 'payload data' // The delegate's didReceiveNotification will be called // Keep connection open to receive notifications... } catch { print("Error: \(error)") } ``` -------------------------------- ### Connect to Postgres using psql Source: https://github.com/codewinsdotcom/postgresclientkit/blob/master/Docs/troubleshooting.md Use the psql command-line tool to verify direct connectivity to your Postgres server, specifying host, port, database, and username. This helps isolate connection issues. ```bash psql --host 127.0.0.1 --port 5432 --dbname example --username bob ``` -------------------------------- ### Clean and Build Swift Package Source: https://github.com/codewinsdotcom/postgresclientkit/blob/master/README.md Commands to clean the build artifacts and compile the Swift package. This is a standard procedure for Swift projects. ```bash cd swift package clean swift build ``` -------------------------------- ### ConnectionPool Initialization Source: https://github.com/codewinsdotcom/postgresclientkit/blob/master/Docs/API/Classes/ConnectionPool.html Initializes a new ConnectionPool with specified configurations for the pool, individual connections, and an optional delegate. ```APIDOC ## ConnectionPool Initialization ### Description Creates a `ConnectionPool` with the provided configurations. ### Method `init(connectionPoolConfiguration:connectionConfiguration:connectionDelegate:)` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example None ### Response None #### Success Response (200) None #### Response Example None ``` -------------------------------- ### Connect to PostgreSQL and Query Data Source: https://github.com/codewinsdotcom/postgresclientkit/blob/master/README.md Connect to a PostgreSQL database, execute a parameterized SELECT query, and process the results. Ensure proper error handling and resource management using defer. ```swift import PostgresClientKit do { var configuration = PostgresClientKit.ConnectionConfiguration() configuration.host = "127.0.0.1" configuration.database = "example" configuration.user = "bob" configuration.credential = .scramSHA256(password: "welcome1") let connection = try PostgresClientKit.Connection(configuration: configuration) defer { connection.close() } let text = "SELECT city, temp_lo, temp_hi, prcp, date FROM weather WHERE city = $1;" let statement = try connection.prepareStatement(text: text) defer { statement.close() } let cursor = try statement.execute(parameterValues: [ "San Francisco" ]) defer { cursor.close() } for row in cursor { let columns = try row.get().columns let city = try columns[0].string() let tempLo = try columns[1].int() let tempHi = try columns[2].int() let prcp = try columns[3].optionalDouble() let date = try columns[4].date() print("\(city) on \(date): low: \(tempLo), high: \(tempHi), \ precipitation: \(String(describing: prcp))") } } catch { print(error) // better error handling goes here } ``` -------------------------------- ### Initialize PostgresByteA from Data Source: https://github.com/codewinsdotcom/postgresclientkit/blob/master/Docs/API/Structs/PostgresByteA.html Creates a PostgresByteA instance from the specified Data object. This is used when you have raw byte data to represent as a BYTEA value. ```swift public init(data: Data) ``` -------------------------------- ### PostgresValue initialization and properties Source: https://github.com/codewinsdotcom/postgresclientkit/blob/master/Docs/API/Structs/PostgresValue.html Defines the structure initialization and basic property accessors for PostgresValue. ```Swift public init(_ rawValue: String?) ``` ```Swift public let rawValue: String? ``` ```Swift public var isNull: Bool { get } ``` -------------------------------- ### Initialize PostgresTimestampWithTimeZone from Components Source: https://github.com/codewinsdotcom/postgresclientkit/blob/master/Docs/API/Structs/PostgresTimestampWithTimeZone.html Creates a PostgresTimestampWithTimeZone from its constituent date and time components, including nanosecond precision and a specified time zone. Ensure the time zone is correctly provided. ```swift let moment = PostgresTimestampWithTimeZone(year: 2019, month: 3, day: 14, hour: 16, minute: 25, second: 19, nanosecond: 365000000, timeZone: TimeZone(secondsFromGMT: 0)!) ``` -------------------------------- ### PostgresClientKit Components Source: https://github.com/codewinsdotcom/postgresclientkit/blob/master/Docs/API/Classes/Cursor.html An overview of the main components available in the PostgresClientKit library. ```APIDOC ## PostgresClientKit Components ### Classes * `Connection` * `ConnectionPool` * `ConsoleLogHandler` * `Cursor` * `Logger` * `Statement` ### Enumerations * `Credential` * `LogLevel` * `PostgresError` ### Extensions * `Bool` * `Date` * `Decimal` * `Double` * `Int` * `Optional` * `String` ### Protocols * `ConnectionDelegate` * `LogHandler` * `PostgresValueConvertible` ### Structures * `ColumnMetadata` * `ConnectionConfiguration` * `ConnectionPoolConfiguration` * `ConnectionPoolMetrics` * `LogRecord` * `Notice` * `Postgres` * `PostgresByteA` * `PostgresDate` * `PostgresTime` * `PostgresTimeWithTimeZone` * `PostgresTimestamp` * `PostgresTimestampWithTimeZone` * `PostgresValue` * `Row` ``` -------------------------------- ### Create PostgresDate from Foundation Date Source: https://github.com/codewinsdotcom/postgresclientkit/blob/master/Docs/API/Structs/PostgresDate.html Initializes a PostgresDate by interpreting a Foundation Date in a specified time zone. Hour, minute, second, and fractional second components are discarded. ```swift public init(date: Date, in timeZone: TimeZone) ``` -------------------------------- ### Initialize PostgresTimeWithTimeZone from Components Source: https://github.com/codewinsdotcom/postgresclientkit/blob/master/Docs/API/Structs/PostgresTimeWithTimeZone.html Creates a PostgresTimeWithTimeZone from hour, minute, second, nanosecond, and time zone components. The time zone must have a fixed offset from UTC/GMT. ```swift let time = PostgresTimeWithTimeZone(hour: 20, minute: 10, second: 05, nanosecond: 128000000, timeZone: TimeZone(secondsFromGMT: -7 * 60 * 60)!) ``` -------------------------------- ### PostgresTimeWithTimeZone Initializers Source: https://github.com/codewinsdotcom/postgresclientkit/blob/master/Docs/API/Structs/PostgresTimeWithTimeZone.html Methods to initialize a PostgresTimeWithTimeZone instance from various data sources. ```APIDOC ## Initializers for PostgresTimeWithTimeZone ### Description Creates a new instance of PostgresTimeWithTimeZone using components, a Date object, or a formatted string. ### Parameters #### init(hour:minute:second:nanosecond:timeZone:) - **hour** (Int) - Required - The hour value - **minute** (Int) - Required - The minute value - **second** (Int) - Required - The second value - **nanosecond** (Int) - Optional - The nanosecond value (default 0) - **timeZone** (TimeZone) - Required - The time zone with a fixed offset #### init(date:in:) - **date** (Date) - Required - The moment in time - **timeZone** (TimeZone) - Required - The time zone to interpret the date #### init(_:) - **string** (String) - Required - A string in format HH:mm:ss.SSSxxxxx or HH:mm:ssxxxxx ``` -------------------------------- ### Store and Retrieve Binary Data with PostgresByteA Source: https://context7.com/codewinsdotcom/postgresclientkit/llms.txt Demonstrates storing and retrieving binary data using the PostgresByteA type for PostgreSQL's BYTEA column. Ensure the 'files' table has 'name' (TEXT) and 'content' (BYTEA) columns. ```swift import PostgresClientKit import Foundation do { let connection = try Connection(configuration: configuration) defer { connection.close() } // Store binary data let imageData = Data([0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A]) // PNG header let byteA = PostgresByteA(data: imageData) let insertStmt = try connection.prepareStatement( text: "INSERT INTO files (name, content) VALUES ($1, $2) RETURNING id" ) defer { insertStmt.close() } let cursor = try insertStmt.execute(parameterValues: ["image.png", byteA]) var fileId: Int? if let row = try cursor.next()?.get() { fileId = try row.columns[0].int() print("Stored file with id: \(fileId!)") } // Retrieve binary data let selectStmt = try connection.prepareStatement( text: "SELECT content FROM files WHERE id = $1" ) defer { selectStmt.close() } let cursor2 = try selectStmt.execute(parameterValues: [fileId!]) if let row = try cursor2.next()?.get() { let retrievedByteA = try row.columns[0].byteA() let retrievedData: Data = retrievedByteA.data print("Retrieved \(retrievedData.count) bytes") } } catch { print("Error: \(error)") } ``` -------------------------------- ### PostgresTimestampWithTimeZone Initializers Source: https://github.com/codewinsdotcom/postgresclientkit/blob/master/Docs/API/Structs/PostgresTimestampWithTimeZone.html Methods to create a new PostgresTimestampWithTimeZone instance from various data sources. ```APIDOC ## Initializers for PostgresTimestampWithTimeZone ### Description Creates a new instance of PostgresTimestampWithTimeZone using components, a Foundation Date, or a formatted string. ### Parameters #### init(year:month:day:hour:minute:second:nanosecond:timeZone:) - **year** (Int) - Required - The year value - **month** (Int) - Required - The month value - **day** (Int) - Required - The day value - **hour** (Int) - Required - The hour value - **minute** (Int) - Required - The minute value - **second** (Int) - Required - The second value - **nanosecond** (Int) - Optional - The nanosecond value - **timeZone** (TimeZone) - Required - The time zone to interpret components #### init(date:) - **date** (Date) - Required - The moment in time #### init(_:) - **string** (String) - Required - A string conforming to yyyy-MM-dd HH:mm:ss.SSSxxxxx or yyyy-MM-dd HH:mm:ssxxxxx ``` -------------------------------- ### Prepare and Execute SQL Statement Source: https://github.com/codewinsdotcom/postgresclientkit/blob/master/Docs/API/Classes/Connection.html Use `prepareStatement` to parse SQL text and `execute` to run it. This process returns a `Cursor` for retrieving results. Any previous cursor is closed when a new statement is prepared or executed. ```swift let statement = try connection.prepareStatement(text: "SELECT * FROM users WHERE id = :id") let cursor = try statement.execute(parameterValues: [User.ID(id: 1)]) ``` -------------------------------- ### Initialize PostgresTimestampWithTimeZone from Date Source: https://github.com/codewinsdotcom/postgresclientkit/blob/master/Docs/API/Structs/PostgresTimestampWithTimeZone.html Creates a PostgresTimestampWithTimeZone directly from a Foundation Date instance. This is useful when you already have a moment in time represented as a Date. ```swift public init(date: Date) ``` -------------------------------- ### Set Authentication Methods Source: https://context7.com/codewinsdotcom/postgresclientkit/llms.txt Defines the credential strategy for the connection configuration. ```swift import PostgresClientKit // Trust authentication (no password required - for development only) configuration.credential = .trust // Cleartext password (only use with SSL/TLS enabled) configuration.credential = .cleartextPassword(password: "mypassword") // MD5 password hash configuration.credential = .md5Password(password: "mypassword") // SCRAM-SHA-256 (recommended - most secure) configuration.credential = .scramSHA256(password: "mypassword") ``` -------------------------------- ### Configure Swift Package Manager Dependencies Source: https://github.com/codewinsdotcom/postgresclientkit/blob/master/README.md Add the package URL and version to the dependencies array in your Package.swift file. ```swift dependencies: [ .package(url: "https://github.com/codewinsdotcom/PostgresClientKit", from: "1.0.0"), ], ``` -------------------------------- ### Configure Swift Package Manager Targets Source: https://github.com/codewinsdotcom/postgresclientkit/blob/master/README.md Include PostgresClientKit as a dependency for your target in Package.swift. ```swift targets: [ .target( name: "MyProject", dependencies: ["PostgresClientKit"]), ] ``` -------------------------------- ### PostgresClientKit Structures Source: https://github.com/codewinsdotcom/postgresclientkit/blob/master/Docs/API/Structs/PostgresDate.html Overview of the structures available in the PostgresClientKit library. ```APIDOC ## PostgresClientKit Structures ### Structures * [ColumnMetadata](../Structs/ColumnMetadata.html) * [ConnectionConfiguration](../Structs/ConnectionConfiguration.html) * [ConnectionPoolConfiguration](../Structs/ConnectionPoolConfiguration.html) * [ConnectionPoolMetrics](../Structs/ConnectionPoolMetrics.html) * [LogRecord](../Structs/LogRecord.html) * [Notice](../Structs/Notice.html) * [Postgres](../Structs/Postgres.html) * [PostgresByteA](../Structs/PostgresByteA.html) * [PostgresDate](../Structs/PostgresDate.html) * [PostgresTime](../Structs/PostgresTime.html) * [PostgresTimeWithTimeZone](../Structs/PostgresTimeWithTimeZone.html) * [PostgresTimestamp](../Structs/PostgresTimestamp.html) * [PostgresTimestampWithTimeZone](../Structs/PostgresTimestampWithTimeZone.html) * [PostgresValue](../Structs/PostgresValue.html) * [Row](../Structs/Row.html) ``` -------------------------------- ### Connection Lifecycle Source: https://github.com/codewinsdotcom/postgresclientkit/blob/master/Docs/API/Classes/Connection.html Methods for initializing, managing, and closing database connections. ```APIDOC ## POST /connection/init ### Description Creates a new `Connection` instance with the provided configuration and an optional delegate. ### Method POST ### Endpoint /connection/init ### Parameters #### Request Body - **configuration** (ConnectionConfiguration) - Required - The configuration for the `Connection`. - **delegate** (ConnectionDelegate?) - Optional - An optional delegate for the `Connection`. ### Response #### Success Response (200) - **connectionId** (string) - The unique identifier for the newly created connection. #### Response Example ```json { "connectionId": "a1b2c3d4-e5f6-7890-1234-567890abcdef" } ``` ``` ```APIDOC ## GET /connection/{id} ### Description Retrieves information about a specific `Connection`. ### Method GET ### Endpoint /connection/{id} ### Parameters #### Path Parameters - **id** (string) - Required - The unique identifier of the `Connection`. ### Response #### Success Response (200) - **id** (string) - Uniquely identifies this `Connection`. - **isClosed** (boolean) - Indicates whether this `Connection` is closed. - **delegate** (ConnectionDelegate?) - An optional delegate for this `Connection`. #### Response Example ```json { "id": "a1b2c3d4-e5f6-7890-1234-567890abcdef", "isClosed": false, "delegate": null } ``` ``` ```APIDOC ## DELETE /connection/{id} ### Description Closes the specified `Connection` gracefully. Has no effect if the `Connection` is already closed. ### Method DELETE ### Endpoint /connection/{id} ### Parameters #### Path Parameters - **id** (string) - Required - The unique identifier of the `Connection` to close. ### Response #### Success Response (204) No Content. ### Response Example (No response body) ``` ```APIDOC ## DELETE /connection/{id}/abrupt ### Description Closes the specified `Connection` abruptly without notifying the Postgres server. This forces the network socket to close immediately. ### Method DELETE ### Endpoint /connection/{id}/abrupt ### Parameters #### Path Parameters - **id** (string) - Required - The unique identifier of the `Connection` to close abruptly. ### Response #### Success Response (204) No Content. ### Response Example (No response body) ``` -------------------------------- ### PostgresClientKit API Reference Source: https://github.com/codewinsdotcom/postgresclientkit/blob/master/Docs/API/Structs/PostgresTime.html An overview of the available classes, enumerations, extensions, protocols, and structures within the PostgresClientKit library. ```APIDOC ## PostgresClientKit API Reference ### Classes - **Connection**: Manages database connections. - **ConnectionPool**: Handles a pool of database connections. - **ConsoleLogHandler**: A log handler that outputs logs to the console. - **Cursor**: Represents a database cursor for fetching results. - **Logger**: Provides logging capabilities. - **Statement**: Represents a prepared SQL statement. ### Enumerations - **Credential**: Defines types of database credentials. - **LogLevel**: Specifies different levels of logging severity. - **PostgresError**: Enumerates possible PostgreSQL errors. ### Extensions - **Bool**: Extension for Boolean type. - **Date**: Extension for Date type. - **Decimal**: Extension for Decimal type. - **Double**: Extension for Double type. - **Int**: Extension for Integer type. - **Optional**: Extension for Optional types. - **String**: Extension for String type. ### Protocols - **ConnectionDelegate**: Protocol for connection event handling. - **LogHandler**: Protocol for custom log handlers. - **PostgresValueConvertible**: Protocol for types convertible to Postgres values. ### Structures - **ColumnMetadata**: Contains metadata about a database column. - **ConnectionConfiguration**: Configuration settings for establishing a database connection. - **ConnectionPoolConfiguration**: Configuration for a connection pool. - **ConnectionPoolMetrics**: Metrics related to connection pool performance. - **LogRecord**: Represents a single log entry. - **Notice**: Represents a notice message from the database. - **Postgres**: The main client for interacting with PostgreSQL. - **PostgresByteA**: Represents PostgreSQL BYTEA data type. - **PostgresDate**: Represents PostgreSQL DATE data type. - **PostgresTime**: Represents PostgreSQL TIME data type. - **PostgresTimeWithTimeZone**: Represents PostgreSQL TIME WITH TIME ZONE data type. - **PostgresTimestamp**: Represents PostgreSQL TIMESTAMP data type. - **PostgresTimestampWithTimeZone**: Represents PostgreSQL TIMESTAMP WITH TIME ZONE data type. - **PostgresValue**: Represents a value from the PostgreSQL database. - **Row**: Represents a single row of data fetched from the database. ``` -------------------------------- ### Connection Management and SQL Execution Source: https://github.com/codewinsdotcom/postgresclientkit/blob/master/Docs/API/Classes.html Methods for establishing connections, preparing SQL statements, and executing them to retrieve data via cursors. ```APIDOC ## Connection.prepareStatement(text:) ### Description Parses the provided SQL text and returns a Statement object for execution. ### Parameters #### Request Body - **text** (String) - Required - The SQL statement to be parsed. ### Response - **Statement** (Object) - A prepared statement object ready for execution. --- ## Statement.execute(parameterValues:retrieveColumnMetadata:) ### Description Executes a prepared statement and returns a Cursor to iterate over the result set. ### Parameters #### Request Body - **parameterValues** ([PostgresValueConvertible]?) - Optional - Values to bind to the statement parameters. - **retrieveColumnMetadata** (Bool) - Required - Whether to retrieve metadata for the result columns. ### Response - **Cursor** (Object) - A cursor used to iterate over the rows of the result set. ``` -------------------------------- ### ConnectionConfiguration Structure Source: https://github.com/codewinsdotcom/postgresclientkit/blob/master/Docs/API/Structs/ConnectionConfiguration.html The `ConnectionConfiguration` structure holds all the necessary information to establish a connection to a PostgreSQL server. ```APIDOC ## ConnectionConfiguration Structure Reference ### Description The configuration for a `Connection` to the Postgres server. ### Properties * **`init()`** Creates a `ConnectionConfiguration`. #### Declaration ```swift public init() ``` * **`host`** (String) - The hostname or IP address of the Postgres server. Defaults to `localhost`. #### Declaration ```swift public var host: String ``` * **`port`** (Int) - The port number of the Postgres server. Defaults to `5432`. #### Declaration ```swift public var port: Int ``` * **`ssl`** (Bool) - Whether to use SSL/TLS to connect to the Postgres server. Defaults to `true`. #### Declaration ```swift public var ssl: Bool ``` * **`sslServiceConfiguration`** (SSLService.Configuration) - The SSL/TLS configuration for connecting to the Postgres server. Ignored if `ssl` is `false`. Defaults to `SSLService.Configuration()`. Refer to the [BlueSSLService documentation](https://github.com/Kitura/BlueSSLService#creating-the-configuration) for additional information. #### Declaration ```swift public var sslServiceConfiguration: SSLService.Configuration ``` * **`socketTimeout`** (Int) - The timeout for socket operations, in seconds, or 0 for no timeout. Defaults to 0. #### Declaration ```swift public var socketTimeout: Int ``` * **`database`** (String) - The name of the database on the Postgres server. Defaults to `postgres`. #### Declaration ```swift public var database: String ``` * **`user`** (String) - The Postgres username. Defaults to an empty string. #### Declaration ```swift public var user: String ``` * **`credential`** (Credential) - The credential to use to authenticate to the Postgres server. Defaults to `Credential.trust`. #### Declaration ```swift public var credential: Credential ``` * **`applicationName`** (String) - The Postgres `application_name` parameter. Included in the `pg_stat_activity` view and displayed by pgAdmin. Defaults to `PostgresClientKit`. #### Declaration ```swift public var applicationName: String ``` ``` -------------------------------- ### Execute Prepared Statements Source: https://context7.com/codewinsdotcom/postgresclientkit/llms.txt Uses parameterized queries to execute SQL statements efficiently with varying inputs. ```swift import PostgresClientKit do { let connection = try Connection(configuration: configuration) defer { connection.close() } // Prepare a parameterized statement let text = """ INSERT INTO users (name, email, age, created_at) VALUES ($1, $2, $3, $4) RETURNING id """ let statement = try connection.prepareStatement(text: text) defer { statement.close() } // Execute with different parameter values let users = [ ("Alice", "alice@example.com", 30), ("Bob", "bob@example.com", 25), ("Carol", "carol@example.com", 35) ] for (name, email, age) in users { let timestamp = PostgresTimestampWithTimeZone(date: Date(), in: TimeZone.current) let cursor = try statement.execute(parameterValues: [name, email, age, timestamp]) if let row = try cursor.next()?.get() { let id = try row.columns[0].int() print("Inserted user \(name) with id: \(id)") } } // Statement can be reused until closed print("Statement closed: \(statement.isClosed)") // false } catch { print("Error: \(error)") } ``` -------------------------------- ### Create Foundation Date from PostgresDate Source: https://github.com/codewinsdotcom/postgresclientkit/blob/master/Docs/API/Structs/PostgresDate.html Creates a Foundation Date by interpreting the PostgresDate in a specified time zone. The hour, minute, second, and fractional second components are set to 0. ```swift public func date(in timeZone: TimeZone) -> Date ``` -------------------------------- ### Classes Source: https://github.com/codewinsdotcom/postgresclientkit/blob/master/Docs/API/Enums/PostgresError.html Available classes in the PostgresClientKit library. ```APIDOC ## Classes ### Description Provides access to various classes for database interaction and logging. ### Available Classes - **Connection**: Represents a connection to the PostgreSQL database. - **ConnectionPool**: Manages a pool of database connections. - **ConsoleLogHandler**: A log handler that outputs logs to the console. - **Cursor**: Represents a cursor for fetching results from a query. - **Logger**: A generic logger interface. - **Statement**: Represents a prepared SQL statement. ``` -------------------------------- ### Log a Record Source: https://github.com/codewinsdotcom/postgresclientkit/blob/master/Docs/API/Classes/ConsoleLogHandler.html Prints the provided LogRecord to standard output. ```Swift public func log(_ record: LogRecord) ``` -------------------------------- ### PostgresClientKit Protocols Source: https://github.com/codewinsdotcom/postgresclientkit/blob/master/Docs/API/Structs/PostgresDate.html Overview of the protocols available in the PostgresClientKit library. ```APIDOC ## PostgresClientKit Protocols ### Protocols * [ConnectionDelegate](../Protocols/ConnectionDelegate.html) * [LogHandler](../Protocols/LogHandler.html) * [PostgresValueConvertible](../Protocols/PostgresValueConvertible.html) ``` -------------------------------- ### Configure pg_hba.conf authentication Source: https://github.com/codewinsdotcom/postgresclientkit/blob/master/Docs/setting_up_a_postgres_database_for_testing.md Authentication records for test users, placed before other configuration records in pg_hba.conf. ```text # For PostgresClientKit testing host postgresclientkittest terry_postgresclientkittest 0.0.0.0/0 trust host postgresclientkittest terry_postgresclientkittest ::0/0 trust host postgresclientkittest charlie_postgresclientkittest 0.0.0.0/0 password host postgresclientkittest charlie_postgresclientkittest ::0/0 password host postgresclientkittest mary_postgresclientkittest 0.0.0.0/0 md5 host postgresclientkittest mary_postgresclientkittest ::0/0 md5 host postgresclientkittest sally_postgresclientkittest 0.0.0.0/0 scram-sha-256 host postgresclientkittest sally_postgresclientkittest ::0/0 scram-sha-256 ``` -------------------------------- ### Configure Postgres Server for Client Messages Source: https://github.com/codewinsdotcom/postgresclientkit/blob/master/Docs/troubleshooting.md Set the client_min_messages configuration parameter on the Postgres server to receive log messages from the server in your Swift application. This requires adjusting the Postgres server's configuration file. ```sql client_min_messages = debug5 ``` -------------------------------- ### Declare Postgres Namespace Source: https://github.com/codewinsdotcom/postgresclientkit/blob/master/Docs/API/Structs.html Namespace for properties and methods used throughout the library. ```Swift public struct Postgres ``` -------------------------------- ### Initialize ConsoleLogHandler Source: https://github.com/codewinsdotcom/postgresclientkit/blob/master/Docs/API/Classes/ConsoleLogHandler.html Creates a new instance of the ConsoleLogHandler class. ```Swift public init() ``` -------------------------------- ### PostgresClientKit Structures Source: https://github.com/codewinsdotcom/postgresclientkit/blob/master/Docs/API/Structs/ConnectionPoolConfiguration.html Documentation for the core structures used in PostgresClientKit for database interaction and data representation. ```APIDOC ## Structures ### Description Core data structures used for configuring connections, representing database data, and managing operations. ### Structure List - **ColumnMetadata**: Represents metadata for a database column. - **ConnectionConfiguration**: Configuration settings for establishing a database connection. - **ConnectionPoolConfiguration**: Configuration for managing a pool of database connections. - **ConnectionPoolMetrics**: Metrics related to the performance of the connection pool. - **LogRecord**: Represents a single log entry. - **Notice**: Represents a notice message from the PostgreSQL server. - **Postgres**: The main client class for interacting with PostgreSQL. - **PostgresByteA**: Represents PostgreSQL BYTEA data type. - **PostgresDate**: Represents PostgreSQL DATE data type. - **PostgresTime**: Represents PostgreSQL TIME data type. - **PostgresTimeWithTimeZone**: Represents PostgreSQL TIME WITH TIME ZONE data type. - **PostgresTimestamp**: Represents PostgreSQL TIMESTAMP data type. - **PostgresTimestampWithTimeZone**: Represents PostgreSQL TIMESTAMP WITH TIME ZONE data type. - **PostgresValue**: Represents a generic PostgreSQL value. - **Row**: Represents a single row of data retrieved from a query. ``` -------------------------------- ### Acquire Connection with Completion Handler Source: https://github.com/codewinsdotcom/postgresclientkit/blob/master/Docs/API/Classes/ConnectionPool.html Asynchronously acquires a database connection. The completion handler is executed on a specified dispatch queue and receives a Result type indicating success with a Connection or failure with an Error. ```swift public func acquireConnection( completionHandler: @escaping (Result) -> Void) ``` -------------------------------- ### Log Event with Details - PostgresClientKit Source: https://github.com/codewinsdotcom/postgresclientkit/blob/master/Docs/API/Classes/Logger.html A convenience method for logging an event with specified level, message, context, file, function, and line number. Useful for structured logging. ```swift public func log(level: LogLevel, message: CustomStringConvertible, context: CustomStringConvertible? = nil, file: String = #file, function: String = #function, line: Int = #line) ``` -------------------------------- ### PostgresClientKit Extensions Source: https://github.com/codewinsdotcom/postgresclientkit/blob/master/Docs/API/Structs/PostgresDate.html Overview of the extensions available in the PostgresClientKit library. ```APIDOC ## PostgresClientKit Extensions ### Extensions * [Bool](../Extensions/Bool.html) * [Date](../Extensions/Date.html) * [Decimal](../Extensions/Decimal.html) * [Double](../Extensions/Double.html) * [Int](../Extensions/Int.html) * [Optional](../Extensions/Optional.html) * [String](../Extensions/String.html) ``` -------------------------------- ### Connection.prepareStatement Source: https://github.com/codewinsdotcom/postgresclientkit/blob/master/Docs/API/Classes/Connection.html Parses SQL text and returns a Statement object for execution. ```APIDOC ## Connection.prepareStatement(text:) ### Description Parses the provided SQL text and returns a Statement object. This is the first step in executing SQL statements. ### Parameters #### Request Body - **text** (String) - Required - The SQL statement to be parsed. ### Response - **Statement** (Object) - A prepared statement object ready for execution. ``` -------------------------------- ### Perform Action with Connection Source: https://github.com/codewinsdotcom/postgresclientkit/blob/master/Docs/API/Classes/ConnectionPool.html Acquires a connection, performs an action, and automatically releases the connection. ```APIDOC ## Perform Action with Connection ### Description Acquires a `Connection` from the pool, executes the provided completion handler, and automatically releases the connection afterward. This is a convenience method for operations that require a connection for a limited scope. ### Method `withConnection(completionHandler:)` ### Endpoint None ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example None ### Response #### Success Response (200) - **Result** (Result<Connection, Error>) - A Result type containing either a successfully acquired `Connection` or an `Error`. #### Response Example None ```