MySQLKit

repository·main·Indexed 42 days ago

https://github.com/vapor/mysql-kit

An SQLKit driver for MySQL clients that enables building and serializing MySQL-dialect SQL queries. It uses MySQLNIO for asynchronous communication and provides connection management via AsyncKit. Supports Swift 5.8+ and is compatible with all MySQL versions and platforms supported by MySQLNIO.

Tokens
1.3K
Snippets
5
Records
7
Agent score
4%

What's inside MySQLKit

  1. Overview of MySQLKit

    main

    MySQLKit is a library that provides an SQLKit driver for MySQLNIO. It serves as the foundational layer for MySQL support in the Vapor ecosystem.

    Its primary responsibilities include:

    • Managing the MySQLNIO library.
    • Bridging MySQLNIO data and metadata formats with SQLKit generic formats.
    • Providing an interface for connection management and interaction via AsyncKit.

    Note: If you are looking for a Fluent driver for MySQL, you should use the FluentMySQLDriver package instead of MySQLKit directly.

  2. Set up a MySQL connection pool

    main

    To manage database connections efficiently, use MySQLConnectionSource and EventLoopGroupConnectionPool.

    1. Create a MySQLConnectionSource with your MySQLConfiguration.
    2. Initialize an EventLoopGroupConnectionPool using the source and an EventLoopGroup.
    3. Use withConnection to execute logic on a randomly chosen event loop, or use pool(for:) to get an EventLoopConnectionPool tied to a specific event loop.

    Note: Always ensure you shut down the connection pool before it deinitializes.

    let eventLoopGroup: EventLoopGroup = ...
    defer { try! eventLoopGroup.syncShutdown() }
    
    let pools = EventLoopGroupConnectionPool(
        source: MySQLConnectionSource(configuration: configuration), 
        on: eventLoopGroup
    )
    defer { pools.shutdown() }
    
    // Use a random event loop from the group
    pools.withConnection { conn 
        print(conn) // MySQLConnection on randomly chosen event loop
    }
    
    // Use a specific event loop
    let eventLoop: EventLoop = ...
    let pool = pools.pool(for: eventLoop)
    
    pool.withConnection { conn
        print(conn) // MySQLConnection on eventLoop
    }
  3. Install MySQLKit via Swift Package Manager

    main

    Add MySQLKit to your Package.swift file using the following SPM dependency declaration to include it in your project.

    .package(url: "https://github.com/vapor/mysql-kit.git", from: "4.0.0")
  4. Configure MySQL connection settings

    main

    You can configure database connections using the MySQLConfiguration struct. There are three ways to provide configuration:

    1. Explicit properties: Specify hostname, port, username, password, and database.
    2. URL string: Initialize from a MySQL connection URL.
    3. Unix Domain Sockets: Use unixDomainSocketPath instead of hostname and port to connect via a local socket file.
    import MySQLKit
    
    // Using explicit properties
    let configuration = MySQLConfiguration(
        hostname: "localhost",
        port: 3306,
        username: "vapor_username",
        password: "vapor_password",
        database: "vapor_database"
    )
    
    // Using a URL string
    guard let configuration = MySQLConfiguration(url: "mysql://...") else {
        ...
    }
    
    // Using Unix Domain Sockets
    let configuration = MySQLConfiguration(
        unixDomainSocketPath: "/path/to/socket",
        username: "vapor_username",
        password: "vapor_password",
        database: "vapor_database"
    )
  5. Use MySQLDatabase to execute raw queries

    main

    An EventLoopGroupConnectionPool or EventLoopConnectionPool can be converted into a MySQLDatabase instance. Use this instance to execute raw SQL queries via methods like simpleQuery.

    let mysql = pool.database(logger: ...)
    let rows = try mysql.simpleQuery("SELECT @@version;").wait()
  6. Use SQLDatabase for type-safe query building

    main

    To use the SQLKit query builder, call .sql() on a MySQLDatabase instance. This returns a SQLDatabase which allows you to build and serialize queries using a fluent API.

    let sql = mysql.sql() // Returns SQLDatabase
    let planets = try sql.select().column("*").from("planets").all().wait()