### Minimum Viable Example Source: https://github.com/vapor/mysql-kit/blob/main/_autodocs/README.md A basic setup for connecting to a MySQL database using MySQLKit, AsyncKit, and Logging. This example demonstrates creating a configuration, event loop group, connection pool, and executing a simple query. ```swift import MySQLKit import AsyncKit import Logging let config = MySQLConfiguration( hostname: "localhost", username: "user", password: "pass" ) let eventLoopGroup = MultiThreadedEventLoopGroup(numberOfThreads: 2) let pools = EventLoopGroupConnectionPool( source: MySQLConnectionSource(configuration: config), on: eventLoopGroup ) let db = pools.database(logger: Logger(label: "db")) print(try db.simpleQuery("SELECT 1").wait()) try pools.shutdown() try eventLoopGroup.syncShutdown() ``` -------------------------------- ### MySQLConfiguration Setup Source: https://github.com/vapor/mysql-kit/blob/main/_autodocs/api-reference/MySQLConnectionSource.md Example of how to create a MySQLConfiguration object with connection details. This configuration is then used to initialize MySQLConnectionSource. ```swift let configuration = MySQLConfiguration( hostname: "localhost", port: 3306, username: "app_user", password: "password", database: "myapp" ) ``` -------------------------------- ### Minimal MySQLKit Example Source: https://github.com/vapor/mysql-kit/blob/main/_autodocs/README.md A minimal example demonstrating how to configure a MySQL connection, create a connection pool, and execute queries using both raw MySQL commands and the SQLKit query builder. ```swift import MySQLKit import AsyncKit import Logging // 1. Configure let configuration = MySQLConfiguration( hostname: "localhost", username: "app_user", password: "password", database: "myapp_db" ) // 2. Create event loop group and connection pool let eventLoopGroup = MultiThreadedEventLoopGroup(numberOfThreads: System.coreCount) defer { try! eventLoopGroup.syncShutdown() } let pools = EventLoopGroupConnectionPool( source: MySQLConnectionSource(configuration: configuration), on: eventLoopGroup ) defer { pools.shutdown() } // 3. Create database and execute queries let database = pools.database(logger: Logger(label: "database")) // Option A: Raw MySQL queries via MySQLNIO let rows = try database.simpleQuery("SELECT * FROM users LIMIT 10;").wait() // Option B: SQLKit query builder let sqlDb = database.sql() let users = try sqlDb.select() .column("*") .from("users") .limit(10) .all() .wait() ``` -------------------------------- ### MySQLConnection Creation and Usage Example Source: https://github.com/vapor/mysql-kit/blob/main/_autodocs/api-reference/MySQLConnectionSource.md An example demonstrating how to use MySQLConnectionSource to create a new MySQL connection and then use it. It includes setting up an EventLoopGroup and handling the connection lifecycle. ```swift let eventLoopGroup = MultiThreadedEventLoopGroup(numberOfThreads: 4) defer { try! eventLoopGroup.syncShutdown() } let eventLoop = eventLoopGroup.next() let source = MySQLConnectionSource(configuration: configuration) let connectionFuture = source.makeConnection(logger: logger, on: eventLoop) connectionFuture.whenSuccess { connection in // Use connection try! connection.close().wait() } ``` -------------------------------- ### Usage Example: EventLoopGroupConnectionPool Source: https://github.com/vapor/mysql-kit/blob/main/_autodocs/api-reference/ConnectionPool+MySQL.md Demonstrates setting up a MySQLConfiguration, an EventLoopGroup, and an EventLoopGroupConnectionPool to obtain a MySQLDatabase instance for executing queries. ```swift import MySQLKit import AsyncKit import Logging let configuration = MySQLConfiguration( hostname: "localhost", username: "app_user", password: "password", database: "myapp" ) let eventLoopGroup = MultiThreadedEventLoopGroup(numberOfThreads: System.coreCount) defer { try! eventLoopGroup.syncShutdown() } let pools = EventLoopGroupConnectionPool( source: MySQLConnectionSource(configuration: configuration), on: eventLoopGroup ) defer { pools.shutdown() } var logger = Logger(label: "com.example.app") logger.logLevel = .info let database = pools.database(logger: logger) // Execute a query let version = try database.simpleQuery("SELECT @@version;").wait() ``` -------------------------------- ### SQL Builder - Select Source: https://github.com/vapor/mysql-kit/blob/main/_autodocs/QUICK_REFERENCE.md Start building a SELECT query using the SQLBuilder. ```swift sqlDb.select() -> SelectBuilder ``` -------------------------------- ### Typical Application Flow for MySQLKit Source: https://github.com/vapor/mysql-kit/blob/main/_autodocs/api-reference/ConnectionPool+MySQL.md Illustrates a common application flow for setting up and using MySQLKit, including configuration, event loop group creation, connection pool setup, and database instance retrieval. ```swift import MySQLKit import AsyncKit import Vapor // 1. Configure let configuration = MySQLConfiguration(url: "mysql://user:pass@localhost/dbname")! // 2. Create event loop group let eventLoopGroup = MultiThreadedEventLoopGroup(numberOfThreads: System.coreCount) // 3. Create connection pool let pools = EventLoopGroupConnectionPool( source: MySQLConnectionSource(configuration: configuration), on: eventLoopGroup ) // 4. Create database from pool var logger = Logger(label: "database") let database = pools.database(logger: logger) // 5. Use database or convert to SQLDatabase let sqlDb = database.sql() // 6. Cleanup defer { try! pools.shutdown() try! eventLoopGroup.syncShutdown() } ``` -------------------------------- ### Usage Example: SQLKit Query Builder Source: https://github.com/vapor/mysql-kit/blob/main/_autodocs/api-reference/MySQLDatabase+SQL.md Demonstrates how to obtain an SQLDatabase instance from a MySQLDatabase and use SQLKit's query builder for SELECT operations. ```swift import MySQLKit import SQLKit let pools = EventLoopGroupConnectionPool( source: MySQLConnectionSource(configuration: configuration), on: eventLoopGroup ) let database = pools.database(logger: logger) let sqlDb = database.sql() // Now use SQLKit query builder let results = try sqlDb.select().column("*").from("users").all().wait() ``` -------------------------------- ### SQL Builder - Insert Source: https://github.com/vapor/mysql-kit/blob/main/_autodocs/QUICK_REFERENCE.md Start building an INSERT query using the SQLBuilder. ```swift sqlDb.insert(into: String) -> InsertBuilder ``` -------------------------------- ### SQL Builder - Update Source: https://github.com/vapor/mysql-kit/blob/main/_autodocs/QUICK_REFERENCE.md Start building an UPDATE query using the SQLBuilder. ```swift sqlDb.update(String) -> UpdateBuilder ``` -------------------------------- ### SQL Builder - SELECT with WHERE, ORDER BY, and LIMIT Source: https://github.com/vapor/mysql-kit/blob/main/_autodocs/QUICK_REFERENCE.md Example of building a complex SELECT query with filtering, sorting, and limiting results. ```swift sqlDb.select() .column("id", "name", "email") .from("users") .where("age", .greaterThan, 18) .orderBy("created_at", .descending) .limit(10) ``` -------------------------------- ### Query Logging Example Source: https://github.com/vapor/mysql-kit/blob/main/_autodocs/api-reference/MySQLDatabase+SQL.md Shows how to enable and disable query logging for executed SQL statements and their bind parameters using the queryLogLevel parameter. ```swift let sqlDb = mysqlDatabase.sql(queryLogLevel: .info) // Logs: // [INFO] Executing query, sql="SELECT `id`, `name` FROM `users` WHERE `active` = ?", binds=["1"] let users = try sqlDb.select().column("id").column("name").from("users").all().wait() let sqlDb = mysqlDatabase.sql(queryLogLevel: nil) ``` -------------------------------- ### SQL Builder - Delete Source: https://github.com/vapor/mysql-kit/blob/main/_autodocs/QUICK_REFERENCE.md Start building a DELETE query using the SQLBuilder. ```swift sqlDb.delete(from: String) -> DeleteBuilder ``` -------------------------------- ### Example: Using SQLDatabase for CRUD Operations Source: https://github.com/vapor/mysql-kit/blob/main/_autodocs/api-reference/MySQLDatabase+SQL.md Illustrates common CRUD operations (SELECT, INSERT, UPDATE, DELETE) using the SQLDatabase interface obtained from MySQLDatabase. ```swift // Custom encoders/decoders for special handling let encoder = MySQLDataEncoder() let decoder = MySQLDataDecoder() let sqlDb = mysqlDatabase.sql( encoder: encoder, decoder: decoder, queryLogLevel: .info ) // SELECT with WHERE and ORDER let activeUsers = try sqlDb.select() .column("id") .column("name") .column("email") .from("users") .where("active", .equal, true) .orderBy("created_at", .descending) .all() .wait() // INSERT let insertId = try sqlDb.insert(into: "users") .columns("name", "email", "active") .values([ "Alice", "alice@example.com", true ]) .wait() // UPDATE try sqlDb.update("users") .set("active", to: false) .where("id", .equal, 42) .run() .wait() // DELETE try sqlDb.delete(from: "users") .where("id", .equal, 99) .run() .wait() ``` -------------------------------- ### Connection Pooling Example Source: https://github.com/vapor/mysql-kit/blob/main/_autodocs/README.md Illustrates the correct way to use connection pooling for efficient database interactions by reusing connections across multiple queries. Avoid creating new connection pools for each query. ```swift // Good: Pool is reused across queries let sqlDb = database.sql() for i in 0..<100 { try sqlDb.select().column("*").from("users").limit(1).all().wait() } // Avoid: Creating new connections each time for i in 0..<100 { let newPool = EventLoopGroupConnectionPool(source: source, on: group) try newPool.database(logger: logger).simpleQuery("SELECT 1").wait() } ``` -------------------------------- ### Example URLs with TLS Modes Source: https://github.com/vapor/mysql-kit/blob/main/_autodocs/configuration.md Demonstrates various ways to specify SSL/TLS modes in MySQL connection URLs. Values are case-insensitive and the last specified mode takes precedence. ```url mysql://user@localhost/db?ssl-mode=REQUIRED mysql://user@localhost/db?tls-mode=DISABLED mysql://user@localhost/db?ssl-mode=PREFERRED mysql+uds://user@localhost/socket?ssl-mode=DISABLED ``` -------------------------------- ### Usage Example: EventLoopConnectionPool Source: https://github.com/vapor/mysql-kit/blob/main/_autodocs/api-reference/ConnectionPool+MySQL.md Demonstrates obtaining a MySQLDatabase instance from a specific pool associated with an event loop, ensuring all queries execute on that event loop. ```swift let eventLoopGroup = MultiThreadedEventLoopGroup(numberOfThreads: 4) defer { try! eventLoopGroup.syncShutdown() } let pools = EventLoopGroupConnectionPool( source: MySQLConnectionSource(configuration: configuration), on: eventLoopGroup ) defer { pools.shutdown() } let eventLoop = eventLoopGroup.next() let pool = pools.pool(for: eventLoop) let database = pool.database(logger: logger) // All queries execute on eventLoop try database.simpleQuery("SELECT 1;").wait() ``` -------------------------------- ### SQL Builder - INSERT statement Source: https://github.com/vapor/mysql-kit/blob/main/_autodocs/QUICK_REFERENCE.md Example of constructing an INSERT statement to add new rows to a table. ```swift sqlDb.insert(into: "users") .columns("name", "email") .values(["Alice", "alice@example.com"]) ``` -------------------------------- ### MySQLConfiguration Database Property Source: https://github.com/vapor/mysql-kit/blob/main/_autodocs/api-reference/MySQLConfiguration.md Sets or gets the optional initial default database to select upon connection. Access is thread-safe. ```swift public var database: String? { get set } ``` -------------------------------- ### Basic SQLRow Usage Example Source: https://github.com/vapor/mysql-kit/blob/main/_autodocs/api-reference/MySQLRow+SQL.md Demonstrates how to use the `sql()` method to obtain an `SQLRow` and then decode column values into specific Swift types. This is useful for accessing individual fields from a database row. ```swift let sqlRow = mysqlRow.sql() let userId: Int = try sqlRow.decode(column: "id", as: Int.self) let userName: String = try sqlRow.decode(column: "name", as: String.self) let isActive: Bool = try sqlRow.decode(column: "active", as: Bool.self) ``` -------------------------------- ### MySQLConfiguration for Connection Failure Source: https://github.com/vapor/mysql-kit/blob/main/_autodocs/errors.md Example configuration designed to trigger a connection failure by specifying a port where no server is listening. The error handling demonstrates how to react to a failed connection attempt. ```swift let config = MySQLConfiguration( hostname: "localhost", port: 9999, // No server listening username: "user", password: "pass" ) let source = MySQLConnectionSource(configuration: config) let connectionFuture = source.makeConnection(logger: logger, on: eventLoop) connectionFuture.whenFailure { error in print("Connection failed: \(error)") // Error: connection refused / timeout } ``` -------------------------------- ### Enable Query Logging for SQLDatabase Source: https://github.com/vapor/mysql-kit/blob/main/_autodocs/configuration.md Provides examples for enabling and disabling query logging when creating an SQLDatabase from MySQLDatabase. Logging levels can be set to debug, info, or disabled. ```swift // Enable query logging at debug level let sqlDb = mysqlDatabase.sql(queryLogLevel: .debug) // Enable at info level let sqlDb = mysqlDatabase.sql(queryLogLevel: .info) // Disable logging let sqlDb = mysqlDatabase.sql(queryLogLevel: nil) // Default is .debug let sqlDb = mysqlDatabase.sql() ``` -------------------------------- ### MySQLConfiguration TLS Configuration Property Source: https://github.com/vapor/mysql-kit/blob/main/_autodocs/api-reference/MySQLConfiguration.md Sets or gets the optional TLS configuration for encrypted connections. `nil` indicates no TLS. Access is thread-safe. ```swift public var tlsConfiguration: TLSConfiguration? { get set } ``` -------------------------------- ### MySQLConfiguration for Address Resolution Failure Source: https://github.com/vapor/mysql-kit/blob/main/_autodocs/errors.md Example configuration that triggers an address resolution failure due to an invalid hostname. This error occurs during connection establishment. ```swift let config = MySQLConfiguration( hostname: "invalid..hostname", username: "user", password: "pass" ) // Error occurs when creating connection: let source = MySQLConnectionSource(configuration: config) source.makeConnection(logger: logger, on: eventLoop) // Fails with address resolution error ``` -------------------------------- ### SQLRow Error Handling Example Source: https://github.com/vapor/mysql-kit/blob/main/_autodocs/api-reference/MySQLRow+SQL.md Illustrates how to handle potential errors when decoding columns from an `SQLRow`. It specifically catches `MissingColumn` for non-existent columns and `DecodingError` for type conversion failures. ```swift do { let value: String = try sqlRow.decode(column: "nonexistent", as: String.self) } catch let error as MissingColumn { print("Column not found: \(error.column)") } catch let error as DecodingError { print("Decoding failed: \(error.debugDescription)") } ``` -------------------------------- ### Complete Row Processing with Decodable Struct Source: https://github.com/vapor/mysql-kit/blob/main/_autodocs/api-reference/MySQLRow+SQL.md Provides a comprehensive example of processing database rows by decoding them into a custom `Decodable` struct. It shows how to decode various types, including optionals, and map them to struct properties. ```swift struct UserRow: Decodable { let id: Int let name: String let email: String let age: Int? let created_at: String } let decoder = MySQLDataDecoder() try sqlDb.select().column("*").from("users").all { sqlRow in let id: Int = try sqlRow.decode(column: "id", as: Int.self) let name: String = try sqlRow.decode(column: "name", as: String.self) let email: String = try sqlRow.decode(column: "email", as: String.self) let age: Int? = try sqlRow.decode(column: "age", as: Int?.self) let createdAt: String = try sqlRow.decode(column: "created_at", as: String.self) let user = UserRow(id: id, name: name, email: email, age: age, created_at: createdAt) print(user) }.wait() ``` -------------------------------- ### Complete MySQLKit Flow Source: https://github.com/vapor/mysql-kit/blob/main/_autodocs/QUICK_REFERENCE.md Demonstrates the typical lifecycle: configuration, pool creation, database acquisition, query execution, and cleanup. ```swift // 1. Configure let config = MySQLConfiguration( hostname: "localhost", username: "user", password: "pass" ) // 2. Create pool let group = MultiThreadedEventLoopGroup(numberOfThreads: 4) let pools = EventLoopGroupConnectionPool( source: MySQLConnectionSource(configuration: config), on: group ) // 3. Get database let db = pools.database(logger: logger) // 4. Execute query let sqlDb = db.sql() let results = try sqlDb.select().column("*").from("users").all().wait() // 5. Cleanup try pools.shutdown() try group.syncShutdown() ``` -------------------------------- ### init?(url: URL) Source: https://github.com/vapor/mysql-kit/blob/main/_autodocs/api-reference/MySQLConfiguration.md Creates a MySQLConfiguration from a Foundation.URL object. This initializer is useful when you already have a URL object representing the connection details. ```APIDOC ## init?(url: URL) ### Description Creates a configuration from a `Foundation.URL` object. ### Method `init` ### Parameters #### Path Parameters - **url** (`URL`) - Required - A MySQL connection URL. ### Returns `MySQLConfiguration?` - A configuration if the URL is valid; `nil` otherwise. ### Usage Example: ```swift let urlString = "mysql+uds://user@localhost/var/run/mysqld/mysqld.sock#mydb" if let url = URL(string: urlString), let configuration = MySQLConfiguration(url: url) { // Use configuration } ``` ``` -------------------------------- ### Initialize MySQLConfiguration from Foundation.URL Source: https://github.com/vapor/mysql-kit/blob/main/_autodocs/api-reference/MySQLConfiguration.md Creates a MySQLConfiguration instance from a Foundation.URL object. This is useful when you already have a URL object representing your database connection. ```swift public init?(url: URL) ``` ```swift let urlString = "mysql+uds://user@localhost/var/run/mysqld/mysqld.sock#mydb" if let url = URL(string: urlString), let configuration = MySQLConfiguration(url: url) { // Use configuration } ``` -------------------------------- ### MySQLConfiguration Username Property Source: https://github.com/vapor/mysql-kit/blob/main/_autodocs/api-reference/MySQLConfiguration.md Sets or gets the username for MySQL authentication. Access is thread-safe. ```swift public var username: String { get set } ``` -------------------------------- ### init?(url: String) Source: https://github.com/vapor/mysql-kit/blob/main/_autodocs/api-reference/MySQLConfiguration.md Creates a MySQLConfiguration from a URL-formatted connection string. It supports various URL formats including TCP with TLS, TCP alias, and UNIX sockets, and validates the components based on the scheme. ```APIDOC ## init?(url: String) ### Description Creates a configuration from a URL-formatted connection string. ### Method `init` ### Parameters #### Path Parameters - **url** (`String`) - Required - A MySQL connection URL string. ### Returns `MySQLConfiguration?` - A configuration if the URL is valid and contains required components; `nil` if invalid. ### Accepted URL Formats: - TCP with TLS: `mysql://username:password@hostname:port/database?ssl-mode=REQUIRED` - TCP alias: `mysql+tcp://username:password@hostname:port/database?ssl-mode=REQUIRED` - UNIX socket: `mysql+uds://username:password@localhost/path?ssl-mode=DISABLED#database` ### URL Component Requirements: - **TCP schemes** (`mysql`, `mysql+tcp`): hostname is required; port, password, and database are optional. - **UDS scheme** (`mysql+uds`): path is required; authority must be empty or `localhost`; port is not allowed. ### SSL Mode Values: | Value | Behavior | |-------|----------| | `DISABLED` | Don't use TLS. | | `PREFERRED` | Use TLS if possible. Currently same as `REQUIRED` due to implementation limitations. | | `REQUIRED` | Enforce TLS with full certificate verification. | | `VERIFY_CA` | Alias for `REQUIRED`. | | `VERIFY_IDENTITY` | Alias for `REQUIRED`. | ### Usage Example: ```swift if let configuration = MySQLConfiguration(url: "mysql://user:pass@localhost:3306/mydb?ssl-mode=REQUIRED") { // Use configuration } ``` ``` -------------------------------- ### SQL Builder - DELETE statement Source: https://github.com/vapor/mysql-kit/blob/main/_autodocs/QUICK_REFERENCE.md Example of constructing a DELETE statement to remove rows based on a condition. ```swift sqlDb.delete(from: "users") .where("created_at", .lessThan, someDate) ``` -------------------------------- ### MySQLConnectionSource Instantiation Source: https://github.com/vapor/mysql-kit/blob/main/_autodocs/api-reference/MySQLConnectionSource.md Demonstrates creating an instance of MySQLConnectionSource using a previously defined MySQLConfiguration. ```swift let source = MySQLConnectionSource(configuration: configuration) ``` -------------------------------- ### SQL Builder - UPDATE statement Source: https://github.com/vapor/mysql-kit/blob/main/_autodocs/QUICK_REFERENCE.md Example of constructing an UPDATE statement to modify existing rows, with a WHERE clause. ```swift sqlDb.update("users") .set("active", to: true) .where("id", .equal, 42) ``` -------------------------------- ### MySQL Configuration from URL Source: https://github.com/vapor/mysql-kit/blob/main/README.md Create a MySQLConfiguration instance from a URL string. Ensure the URL is valid, otherwise handle the nil case. ```swift guard let configuration = MySQLConfiguration(url: "mysql://...") else { ... } ``` -------------------------------- ### MySQLConfiguration from URL string Source: https://github.com/vapor/mysql-kit/blob/main/_autodocs/QUICK_REFERENCE.md Create a MySQL configuration from a URL string. Returns an optional configuration. ```swift MySQLConfiguration?(url: String) ``` -------------------------------- ### MySQL Dialect Name Source: https://github.com/vapor/mysql-kit/blob/main/_autodocs/QUICK_REFERENCE.md Get the name of the SQL dialect. This is useful for identifying the specific database system being used. ```swift MySQLDialect().name // "mysql" ``` -------------------------------- ### init(unixDomainSocketPath:username:password:database:tlsConfiguration:) Source: https://github.com/vapor/mysql-kit/blob/main/_autodocs/api-reference/MySQLConfiguration.md Creates a configuration for a UNIX domain socket connection with optional TLS. Supports optional database selection. ```APIDOC ## init(unixDomainSocketPath:username:password:database:tlsConfiguration:) ### Description Creates a configuration for a UNIX domain socket connection with optional TLS. Supports optional database selection. ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters - **unixDomainSocketPath** (`String`) - Required - Path to the UNIX domain socket file. - **username** (`String`) - Required - Username for authentication. - **password** (`String`) - Required - Password for authentication. - **database** (`String?`) - Optional - Optional initial default database. - **tlsConfiguration** (`TLSConfiguration?`) - Optional - Optional TLS configuration. ### Usage Example ```swift let tlsConfig = TLSConfiguration.makeClientConfiguration() let configuration = MySQLConfiguration( unixDomainSocketPath: "/var/run/mysqld/mysqld.sock", username: "app_user", password: "secure_password", database: "myapp_db", tlsConfiguration: tlsConfig ) ``` ``` -------------------------------- ### Get Connection from Pool (Specific Event Loop) Source: https://github.com/vapor/mysql-kit/blob/main/README.md Retrieve a specific EventLoopConnectionPool for a given EventLoop, then acquire a MySQLConnection from it. ```swift let eventLoop: EventLoop = ... let pool = pools.pool(for: eventLoop) pool.withConnection { conn print(conn) // MySQLConnection on eventLoop } ``` -------------------------------- ### init(hostname:port:username:password:database:tlsConfiguration:) Source: https://github.com/vapor/mysql-kit/blob/main/_autodocs/api-reference/MySQLConfiguration.md Creates a configuration for a TCP connection to a MySQL server. Supports optional TLS encryption. ```APIDOC ## init(hostname:port:username:password:database:tlsConfiguration:) ### Description Creates a configuration for a TCP connection to a MySQL server. Supports optional TLS encryption. ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters - **hostname** (`String`) - Required - The hostname or IP address to connect to. - **port** (`Int`) - Optional - TCP port number. Defaults to the IANA MySQL port (3306). - **username** (`String`) - Required - Username for authentication. - **password** (`String`) - Required - Password for authentication. Use empty string for no password. - **database** (`String?`) - Optional - Optional initial default database to select on connection. - **tlsConfiguration** (`TLSConfiguration?`) - Optional - Optional TLS configuration for encrypted connections. Defaults to standard client configuration. ### Usage Example ```swift let configuration = MySQLConfiguration( hostname: "localhost", port: 3306, username: "app_user", password: "secure_password", database: "myapp_db" ) ``` ``` -------------------------------- ### MySQLConfiguration Password Property Source: https://github.com/vapor/mysql-kit/blob/main/_autodocs/api-reference/MySQLConfiguration.md Sets or gets the password for MySQL authentication. Can be an empty string if no password is required. Access is thread-safe. ```swift public var password: String { get set } ``` -------------------------------- ### Configure MySQL Database Source: https://github.com/vapor/mysql-kit/blob/main/_autodocs/INDEX.md Instantiate MySQLConfiguration with connection details. ```swift let config = MySQLConfiguration(hostname: "localhost", username: "user", password: "pass") ``` -------------------------------- ### Get Connection from Pool (Random Event Loop) Source: https://github.com/vapor/mysql-kit/blob/main/README.md Acquire a MySQLConnection from the EventLoopGroupConnectionPool. A random event loop will be chosen for the connection. ```swift pools.withConnection { conn print(conn) // MySQLConnection on randomly chosen event loop } ``` -------------------------------- ### Initialize MySQLConfiguration from URL String Source: https://github.com/vapor/mysql-kit/blob/main/_autodocs/api-reference/MySQLConfiguration.md Creates a MySQLConfiguration instance from a URL-formatted connection string. Supports TCP and UNIX domain socket connections with various SSL modes. ```swift public init?(url: String) ``` ```swift if let configuration = MySQLConfiguration(url: "mysql://user:pass@localhost:3306/mydb?ssl-mode=REQUIRED") { // Use configuration } ``` -------------------------------- ### Create UNIX Domain Socket MySQL Configuration (With TLS) Source: https://github.com/vapor/mysql-kit/blob/main/_autodocs/api-reference/MySQLConfiguration.md Use this initializer to create a MySQL configuration for a UNIX domain socket connection that includes optional TLS encryption. Provide the socket path, credentials, an optional database, and TLS configuration. ```swift public init( unixDomainSocketPath: String, username: String, password: String, database: String? = nil, tlsConfiguration: TLSConfiguration? ) ``` ```swift let tlsConfig = TLSConfiguration.makeClientConfiguration() let configuration = MySQLConfiguration( unixDomainSocketPath: "/var/run/mysqld/mysqld.sock", username: "app_user", password: "secure_password", database: "myapp_db", tlsConfiguration: tlsConfig ) ``` -------------------------------- ### MySQL Dialect Bind Placeholder Source: https://github.com/vapor/mysql-kit/blob/main/_autodocs/QUICK_REFERENCE.md Get the placeholder character used for bind parameters in MySQL queries. This is typically a question mark. ```swift MySQLDialect().bindPlaceholder(at: 0) // "?" ``` -------------------------------- ### init(unixDomainSocketPath:username:password:database:) Source: https://github.com/vapor/mysql-kit/blob/main/_autodocs/api-reference/MySQLConfiguration.md Creates a configuration for a UNIX domain socket connection without TLS. Supports optional database selection. ```APIDOC ## init(unixDomainSocketPath:username:password:database:) ### Description Creates a configuration for a UNIX domain socket connection without TLS. Supports optional database selection. ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters - **unixDomainSocketPath** (`String`) - Required - Path to the UNIX domain socket file. - **username** (`String`) - Required - Username for authentication. - **password** (`String`) - Required - Password for authentication. Use empty string for no password. - **database** (`String?`) - Optional - Optional initial default database. ### Usage Example ```swift let configuration = MySQLConfiguration( unixDomainSocketPath: "/var/run/mysqld/mysqld.sock", username: "app_user", password: "secure_password", database: "myapp_db" ) ``` ``` -------------------------------- ### Async/Await Support Source: https://github.com/vapor/mysql-kit/blob/main/_autodocs/api-reference/MySQLDatabase+SQL.md Demonstrates the async/await pattern for executing queries with the SQLDatabase, alongside the traditional callback-based approach. ```swift // Callback-based (EventLoopFuture) sqlDb.execute(sql: query) { row in // Handle each row }.whenComplete { result in // Query completed } // Async/await try await sqlDb.execute(sql: query) { row in // Handle each row } ``` -------------------------------- ### Create SQLDatabase with MySQLDialect Source: https://github.com/vapor/mysql-kit/blob/main/_autodocs/api-reference/MySQLDialect.md Demonstrates how to obtain an SQLDatabase instance that automatically uses MySQLDialect for its operations when initialized from a MySQLDatabase. ```swift let sqlDb = mysqlDatabase.sql() // Uses MySQLDialect internally ``` -------------------------------- ### Configure MySQLConnectionSource for Connection Pool Source: https://github.com/vapor/mysql-kit/blob/main/_autodocs/configuration.md Illustrates setting up a MySQLConnectionSource with specific MySQL configuration to be used with AsyncKit's connection pooling mechanisms. ```swift let source = MySQLConnectionSource(configuration: configuration) let pools = EventLoopGroupConnectionPool( source: source, on: eventLoopGroup ) ``` -------------------------------- ### Get MySQLDatabase from EventLoopGroupConnectionPool Source: https://github.com/vapor/mysql-kit/blob/main/_autodocs/api-reference/ConnectionPool+MySQL.md Returns a MySQLDatabase that rotates between available connection pools for each query. Suitable for applications without specific event loop affinity. ```swift public func database(logger: Logger) -> any MySQLDatabase ``` -------------------------------- ### MySQLConfiguration from hostname/port Source: https://github.com/vapor/mysql-kit/blob/main/_autodocs/QUICK_REFERENCE.md Create a MySQL configuration using hostname, port, username, password, database, and optional TLS configuration. ```swift MySQLConfiguration( hostname: String, port: Int = 3306, username: String, password: String, database: String? = nil, tlsConfiguration: TLSConfiguration? = .makeClientConfiguration() ) ``` -------------------------------- ### Create MySQLDatabase Instance Source: https://github.com/vapor/mysql-kit/blob/main/README.md Create a MySQLDatabase instance from a connection pool. A logger can be provided for debugging. ```swift let mysql = pool.database(logger: ...) let rows = try mysql.simpleQuery("SELECT @@version;").wait() ``` -------------------------------- ### init?(mysqlData: MySQLData) Source: https://github.com/vapor/mysql-kit/blob/main/_autodocs/api-reference/Optional+MySQLDataConvertible.md Initializes an Optional from MySQLData. Returns .none for NULL values and attempts to initialize the wrapped type for non-NULL values. ```APIDOC ## init?(mysqlData: MySQLData) ### Description Creates an optional value from `MySQLData`. If the data buffer is `nil` (NULL value), returns `.none`. If the buffer is present, attempts to initialize the wrapped type. Returns `nil` if the wrapped type's initializer returns `nil`. ### Method `init?(mysqlData: MySQLData)` ### Parameters - **mysqlData** (MySQLData) - The data to convert from. ### Request Example ```swift let decoder = MySQLDataDecoder() // NULL data let nullData = MySQLData(type: .null, format: .text, buffer: nil) let optionalInt: Int? = try decoder.decode(Int?.self, from: nullData) // nil // Non-NULL data let data = MySQLData(...) let optionalInt: Int? = try decoder.decode(Int?.self, from: data) // Some(42) ``` ### Response #### Success Response - `Optional?` - An optional value initialized from the `MySQLData`. ``` -------------------------------- ### MySQLConfiguration Address Property Source: https://github.com/vapor/mysql-kit/blob/main/_autodocs/api-reference/MySQLConfiguration.md Provides a closure to get the SocketAddress for the configured MySQL server. This is computed from hostname/port or UNIX socket path and may throw errors on resolution failure. ```swift public var address: @Sendable () throws -> SocketAddress { get set } ``` -------------------------------- ### MySQL Custom Data Type Mapping Source: https://github.com/vapor/mysql-kit/blob/main/_autodocs/api-reference/MySQLDialect.md Maps generic SQL data types to MySQL-specific types. For example, '.text' is mapped to 'VARCHAR(255)'. Other types use the default mapping. ```swift public func customDataType(for dataType: SQLDataType) -> (any SQLExpression)? ``` -------------------------------- ### Create UNIX Domain Socket MySQL Configuration (No TLS) Source: https://github.com/vapor/mysql-kit/blob/main/_autodocs/api-reference/MySQLConfiguration.md Use this initializer to create a MySQL configuration when connecting via a UNIX domain socket without TLS encryption. Specify the socket path, username, password, and an optional database. ```swift public init( unixDomainSocketPath: String, username: String, password: String, database: String? = nil ) ``` ```swift let configuration = MySQLConfiguration( unixDomainSocketPath: "/var/run/mysqld/mysqld.sock", username: "app_user", password: "secure_password", database: "myapp_db" ) ``` -------------------------------- ### MySQLConfiguration from URL object Source: https://github.com/vapor/mysql-kit/blob/main/_autodocs/QUICK_REFERENCE.md Create a MySQL configuration from a URL object. Returns an optional configuration. ```swift MySQLConfiguration?(url: URL) ``` -------------------------------- ### Configure MySQL Connection from URL Source: https://github.com/vapor/mysql-kit/blob/main/_autodocs/README.md Configure a MySQL database connection by parsing a connection URL. ```swift // From URL if let config = MySQLConfiguration(url: "mysql://app:secret@db.example.com/production") { // Use config } ``` -------------------------------- ### Add MySQLKit to Package.swift Source: https://github.com/vapor/mysql-kit/blob/main/_autodocs/README.md Add the MySQLKit package to your Swift project's Package.swift file. ```swift .package(url: "https://github.com/vapor/mysql-kit.git", from: "4.0.0") ``` -------------------------------- ### Handle MySQL Authentication Failures Source: https://github.com/vapor/mysql-kit/blob/main/_autodocs/errors.md Demonstrates how to catch authentication errors when establishing a MySQL connection. This is useful for validating credentials and user permissions. ```swift let config = MySQLConfiguration( hostname: "localhost", username: "wrong_user", password: "wrong_password", database: "mydb" ) let source = MySQLConnectionSource(configuration: config) let connectionFuture = source.makeConnection(logger: logger, on: eventLoop) connectionFuture.whenFailure { error in print("Auth error: \(error)") // Error: Access denied for user 'wrong_user'@'localhost' } ``` -------------------------------- ### MySQLConfiguration from UNIX socket Source: https://github.com/vapor/mysql-kit/blob/main/_autodocs/QUICK_REFERENCE.md Create a MySQL configuration using a UNIX domain socket path, username, password, database, and optional TLS configuration. ```swift MySQLConfiguration( unixDomainSocketPath: String, username: String, password: String, database: String? = nil, tlsConfiguration: TLSConfiguration? = nil ) ``` -------------------------------- ### MySQLConnectionSource Initializer Source: https://github.com/vapor/mysql-kit/blob/main/_autodocs/api-reference/MySQLConnectionSource.md Creates a connection source with the specified MySQL configuration. This is the primary way to instantiate MySQLConnectionSource. ```swift public init(configuration: MySQLConfiguration) ``` -------------------------------- ### Create TCP MySQL Configuration Source: https://github.com/vapor/mysql-kit/blob/main/_autodocs/api-reference/MySQLConfiguration.md Use this initializer to create a MySQL configuration for a standard TCP connection. It allows specifying hostname, port, username, password, an optional database, and TLS settings. ```swift public init( hostname: String, port: Int = Self.ianaPortNumber, username: String, password: String, database: String? = nil, tlsConfiguration: TLSConfiguration? = .makeClientConfiguration() ) ``` ```swift let configuration = MySQLConfiguration( hostname: "localhost", port: 3306, username: "app_user", password: "secure_password", database: "myapp_db" ) ``` -------------------------------- ### Execute Async Query Source: https://github.com/vapor/mysql-kit/blob/main/_autodocs/README.md Demonstrates how to execute a SELECT query asynchronously using async/await and process the results. Ensure proper error handling with a do-catch block. ```swift do { try await sqlDb.select().column("*").from("users").all { row in // Process row } } catch { print("Query failed: \(error)") } ``` -------------------------------- ### MySQLConfiguration Struct Source: https://github.com/vapor/mysql-kit/blob/main/_autodocs/types.md Defines parameters for establishing a MySQL database connection. Supports configuration via URL strings, URLs, or direct property initialization, including options for hostname, port, username, password, database, and TLS. ```swift public struct MySQLConfiguration: Sendable { public var address: @Sendable () throws -> SocketAddress public var username: String public var password: String public var database: String? public var tlsConfiguration: TLSConfiguration? public static var ianaPortNumber: Int { 3306 } public init?(url: String) public init?(url: URL) public init( unixDomainSocketPath: String, username: String, password: String, database: String? = nil ) public init( unixDomainSocketPath: String, username: String, password: String, database: String? = nil, tlsConfiguration: TLSConfiguration? ) public init( hostname: String, port: Int = Self.ianaPortNumber, username: String, password: String, database: String? = nil, tlsConfiguration: TLSConfiguration? = .makeClientConfiguration() ) } ``` -------------------------------- ### Using Multiple Decoder Instances Source: https://github.com/vapor/mysql-kit/blob/main/_autodocs/api-reference/MySQLRow+SQL.md Illustrates how to create and use different `MySQLDataDecoder` instances for different rows, allowing for varied decoding strategies within the same application context. ```swift let standardDecoder = MySQLDataDecoder() let isoDecoder = MySQLDataDecoder(json: { let dec = JSONDecoder() dec.dateDecodingStrategy = .iso8601 return dec }()) let row1 = resultRow1.sql(decoder: standardDecoder) let row2 = resultRow2.sql(decoder: isoDecoder) ``` -------------------------------- ### Configure TLS for MySQL Connection Source: https://github.com/vapor/mysql-kit/blob/main/_autodocs/configuration.md Shows how to integrate NIOSSL's `TLSConfiguration` for secure MySQL connections. This includes creating a default client configuration and optionally disabling TLS. ```swift import NIOSSL // Standard client config (default) let tlsConfig = TLSConfiguration.makeClientConfiguration() // Use with configuration let config = MySQLConfiguration( hostname: "localhost", username: "user", password: "pass", tlsConfiguration: tlsConfig ) // Or disable TLS let config = MySQLConfiguration( hostname: "localhost", username: "user", password: "pass", tlsConfiguration: nil ) ``` -------------------------------- ### Initialize Data Encoder and Decoder Source: https://github.com/vapor/mysql-kit/blob/main/_autodocs/INDEX.md Create instances of MySQLDataEncoder and MySQLDataDecoder for custom data conversion. ```swift let encoder = MySQLDataEncoder() let decoder = MySQLDataDecoder() let db = database.sql(encoder: encoder, decoder: decoder) ``` -------------------------------- ### MySQL Kit File Organization Source: https://github.com/vapor/mysql-kit/blob/main/_autodocs/MANIFEST.md This snippet shows the directory structure for the MySQL Kit documentation files. It helps in understanding where to locate specific reference documents. ```text output/ ├── README.md (Overview & quick start) ├── MANIFEST.md (This file) ├── types.md (Type definitions) ├── configuration.md (Configuration options) ├── errors.md (Error reference) └── api-reference/ ├── MySQLConfiguration.md ├── MySQLConnectionSource.md ├── MySQLDataDecoder.md ├── MySQLDataEncoder.md ├── MySQLDialect.md ├── MySQLDatabase+SQL.md ├── MySQLRow+SQL.md ├── ConnectionPool+MySQL.md └── Optional+MySQLDataConvertible.md ``` -------------------------------- ### Query Logging Configuration Source: https://github.com/vapor/mysql-kit/blob/main/_autodocs/README.md Demonstrates how to configure query logging levels. Set `queryLogLevel` to `nil` for production to disable logging and improve performance, or use `.debug` for development. ```swift // Production: No logging let sqlDb = database.sql(queryLogLevel: nil) // Development: Debug logging let sqlDb = database.sql(queryLogLevel: .debug) ``` -------------------------------- ### Initialize MySQLDialect Source: https://github.com/vapor/mysql-kit/blob/main/_autodocs/api-reference/MySQLDialect.md Creates a new MySQLDialect instance with default MySQL behavior. This is used to configure SQLKit for MySQL interactions. ```swift public init() ``` ```swift let dialect = MySQLDialect() let sqlDb = mysqlDatabase.sql() // Automatically uses MySQLDialect ``` -------------------------------- ### Create Connection Pool Source: https://github.com/vapor/mysql-kit/blob/main/_autodocs/INDEX.md Set up an EventLoopGroupConnectionPool for efficient connection management. ```swift let pools = EventLoopGroupConnectionPool(source: MySQLConnectionSource(configuration: config), on: group) ``` -------------------------------- ### Encoding and Decoding Customization Source: https://github.com/vapor/mysql-kit/blob/main/_autodocs/api-reference/MySQLDatabase+SQL.md Shows how to customize date encoding and decoding strategies to ISO8601 format when using the SQLDatabase wrapper. ```swift // Custom date strategy let encoder = MySQLDataEncoder(json: { let enc = JSONEncoder() enc.dateEncodingStrategy = .iso8601 return enc }()) let decoder = MySQLDataDecoder(json: { let dec = JSONDecoder() dec.dateDecodingStrategy = .iso8601 return dec }()) let sqlDb = mysqlDatabase.sql(encoder: encoder, decoder: decoder) // Dates are now encoded/decoded as ISO8601 strings ``` -------------------------------- ### Add MySQLKit Dependency Source: https://github.com/vapor/mysql-kit/blob/main/README.md Use this SPM string to include the MySQLKit dependency in your Package.swift file. ```swift .package(url: "https://github.com/vapor/mysql-kit.git", from: "4.0.0") ``` -------------------------------- ### Integrate MySQLDataDecoder with SQLDatabase Source: https://github.com/vapor/mysql-kit/blob/main/_autodocs/api-reference/MySQLDataDecoder.md Shows how to create an SQLDatabase instance from a MySQLDatabase using a MySQLDataDecoder for decoding query results. ```swift let decoder = MySQLDataDecoder() let sqlDb = mysqlDatabase.sql(decoder: decoder) let rows = try sqlDb.select().column("*").from("users").all().wait() ``` -------------------------------- ### SQL Builder - Raw Source: https://github.com/vapor/mysql-kit/blob/main/_autodocs/QUICK_REFERENCE.md Execute a raw SQL string as a query using the SQLBuilder. ```swift sqlDb.raw(String) -> RawBuilder ``` -------------------------------- ### MySQLConfiguration Source: https://github.com/vapor/mysql-kit/blob/main/_autodocs/types.md Represents the configuration parameters required to establish a connection to a MySQL database. It supports various initialization methods, including from a URL or specific connection details like hostname, port, and credentials. ```APIDOC ## MySQLConfiguration ### Description A struct containing all parameters needed to establish a MySQL database connection. ### Initializers - `init?(url: String)` - `init?(url: URL)` - `init(unixDomainSocketPath: String, username: String, password: String, database: String? = nil)` - `init(unixDomainSocketPath: String, username: String, password: String, database: String? = nil, tlsConfiguration: TLSConfiguration?) - `init(hostname: String, port: Int = 3306, username: String, password: String, database: String? = nil, tlsConfiguration: TLSConfiguration? = .makeClientConfiguration())` ### Properties - **address** (`@Sendable () throws -> SocketAddress`) - Closure resolving server address; throws if resolution fails. - **username** (`String`) - Username for authentication. - **password** (`String`) - Password for authentication (empty string = no password). - **database** (`String?`) - Optional initial database to select. - **tlsConfiguration** (`TLSConfiguration?`) - Optional TLS settings; `nil` disables encryption. ### Static Properties - **ianaPortNumber** (`Int`) - The standard IANA port number for MySQL (3306). ``` -------------------------------- ### Create Connection Pool Source: https://github.com/vapor/mysql-kit/blob/main/README.md Create an EventLoopGroupConnectionPool using a MySQLConfiguration and an EventLoopGroup. Remember to shut down the pool when done. ```swift let eventLoopGroup: EventLoopGroup = ... default { try! eventLoopGroup.syncShutdown() } let pools = EventLoopGroupConnectionPool( source: MySQLConnectionSource(configuration: configuration), on: eventLoopGroup ) default { pools.shutdown() } ``` -------------------------------- ### UNIX Domain Socket Configuration (With TLS) Source: https://github.com/vapor/mysql-kit/blob/main/_autodocs/configuration.md Configure a MySQL connection using a UNIX domain socket path, username, password, an optional database, and TLS configuration. ```swift let configuration = MySQLConfiguration( unixDomainSocketPath: String, username: String, password: String, database: String? = nil, tlsConfiguration: TLSConfiguration? ) ``` -------------------------------- ### MySQLConnectionSource Initializer Source: https://github.com/vapor/mysql-kit/blob/main/_autodocs/api-reference/MySQLConnectionSource.md Initializes a MySQLConnectionSource with a given MySQLConfiguration. This configuration is used to establish new database connections. ```APIDOC ## init(configuration:) ### Description Creates a connection source with the specified MySQL configuration. ### Method `init` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```swift let configuration = MySQLConfiguration( hostname: "localhost", port: 3306, username: "app_user", password: "password", database: "myapp" ) let source = MySQLConnectionSource(configuration: configuration) ``` ### Response None ### Error Handling None ``` -------------------------------- ### MySQLDialect Initializer Source: https://github.com/vapor/mysql-kit/blob/main/_autodocs/api-reference/MySQLDialect.md Creates a new MySQLDialect instance with default MySQL behavior. This is used to configure SQLKit for MySQL. ```APIDOC ## init() ### Description Creates a new `MySQLDialect` with default MySQL behavior. ### Method `init()` ### Parameters None ### Returns `MySQLDialect` - A new instance of the MySQLDialect. ``` -------------------------------- ### Create MySQL Connection Pool Source: https://github.com/vapor/mysql-kit/blob/main/_autodocs/README.md Create a connection pool for MySQL using an event loop group and a MySQL connection source. ```swift let eventLoopGroup = MultiThreadedEventLoopGroup(numberOfThreads: 4) defer { try! eventLoopGroup.syncShutdown() } let pools = EventLoopGroupConnectionPool( source: MySQLConnectionSource(configuration: config), on: eventLoopGroup ) defer { pools.shutdown() } let database = pools.database(logger: logger) ``` -------------------------------- ### Execute SQL Query Source: https://github.com/vapor/mysql-kit/blob/main/_autodocs/INDEX.md Perform a SQL SELECT query to retrieve all users from a table. ```swift let db = pools.database(logger: logger).sql() let users = try db.select().column("*").from("users").all().wait() ``` -------------------------------- ### Event Loop Lifecycle Management with EventLoopConnectionPool Source: https://github.com/vapor/mysql-kit/blob/main/_autodocs/api-reference/ConnectionPool+MySQL.md Demonstrates how to obtain specific event loop pools and their associated database instances using `pool(for:)`, which is crucial for Vapor applications where request handlers are bound to specific event loops. ```swift let eventLoopGroup = MultiThreadedEventLoopGroup(numberOfThreads: 2) let pools = EventLoopGroupConnectionPool(source: source, on: eventLoopGroup) let el1 = eventLoopGroup.next() let el2 = eventLoopGroup.next() let pool1 = pools.pool(for: el1) let pool2 = pools.pool(for: el2) let db1 = pool1.database(logger: logger) // Uses el1 let db2 = pool2.database(logger: logger) // Uses el2 ``` -------------------------------- ### MySQL Configuration Struct Source: https://github.com/vapor/mysql-kit/blob/main/README.md Configure MySQL connection details using the MySQLConfiguration struct. This includes hostname, port, username, password, and database. ```swift import MySQLKit let configuration = MySQLConfiguration( hostname: "localhost", port: 3306, username: "vapor_username", password: "vapor_password", database: "vapor_database" ) ``` -------------------------------- ### Properties Source: https://github.com/vapor/mysql-kit/blob/main/_autodocs/api-reference/MySQLConfiguration.md Details the configurable properties of a MySQLConfiguration instance, including address, username, password, database, and TLS configuration. ```APIDOC ## Properties ### address ```swift public var address: @Sendable () throws -> SocketAddress { get set } ``` A closure that returns the `SocketAddress` for the configured server. This is computed from either hostname/port or UNIX socket path. Throwing errors occur if address resolution fails. ### username ```swift public var username: String { get set } ``` The username used for authentication. Thread-safe access. ### password ```swift public var password: String { get set } ``` The password used for authentication. May be an empty string if no password is required. Thread-safe access. ### database ```swift public var database: String? { get set } ``` Optional initial default database to select on connection. Thread-safe access. ### tlsConfiguration ```swift public var tlsConfiguration: TLSConfiguration? { get set } ``` Optional TLS configuration for encrypted connections. `nil` indicates no TLS. Thread-safe access. ``` -------------------------------- ### Execute Raw SQL Queries Source: https://github.com/vapor/mysql-kit/blob/main/_autodocs/README.md Execute simple and parameterized SQL queries directly against the database. Use this for queries not supported by the query builder or for maximum flexibility. ```swift let database = pools.database(logger: logger) // Simple query with no parameters let results = try database.simpleQuery("SELECT @@version").wait() // Parameterized query let users = try database.query("SELECT * FROM users WHERE age > ?", [18]).wait() ``` -------------------------------- ### Create SQLDatabase Instance Source: https://github.com/vapor/mysql-kit/blob/main/README.md Convert a MySQLDatabase instance to an SQLDatabase instance for using SQLKit functionalities. This allows building and executing generic SQL queries. ```swift let sql = mysql.sql() // SQLDatabase let planets = try sql.select().column("*").from("planets").all().wait() ``` -------------------------------- ### MySQL Configuration via Unix Domain Socket Source: https://github.com/vapor/mysql-kit/blob/main/README.md Configure MySQL connection using a Unix domain socket path instead of hostname and port. Requires username, password, and database. ```swift let configuration = MySQLConfiguration( unixDomainSocketPath: "/path/to/socket", username: "vapor_username", password: "vapor_password", database: "vapor_database" ) ``` -------------------------------- ### Configure MySQL Database in Vapor Source: https://github.com/vapor/mysql-kit/blob/main/_autodocs/README.md Configure MySQLKit as a database service within a Vapor application using connection details from environment variables. This sets up the database for use in route handlers. ```swift import Vapor app.databases.use(.mysql( hostname: Environment.get("DATABASE_HOST") ?? "localhost", port: Int(Environment.get("DATABASE_PORT") ?? "3306") ?? 3306, username: Environment.get("DATABASE_USER") ?? "vapor", password: Environment.get("DATABASE_PASSWORD") ?? "password", database: Environment.get("DATABASE_NAME") ?? "vapor" ), as: .mysql) // In route handlers app.get("users") { req -> EventLoopFuture<[User]> in User.query(on: req.db).all() } ``` -------------------------------- ### MySQLDatabase from EventLoopConnectionPool Source: https://github.com/vapor/mysql-kit/blob/main/_autodocs/QUICK_REFERENCE.md Obtain a MySQLDatabase instance from an EventLoopConnectionPool, requiring a Logger. ```swift pool.database(logger: Logger) -> any MySQLDatabase ```