GithubHelp home page GithubHelp logo

mysql-swift's Introduction

mysql-swift

Swift 4.0 Platform Linux, macOS Build Status

MySQL client library for Swift. This is inspired by Node.js' mysql and Himotoki as decoding results.

  • Based on libmysqlclient
  • Raw SQL query
  • Simple query formatting and escaping (same as Node's)
  • Decoding and mapping queried results to Swift struct or class

Note: No asynchronous support currently. It depends libmysqlclient.

// Declare a model

struct User: QueryRowResultType, QueryParameterDictionaryType {
    let id: Int
    let userName: String
    let age: Int?
    let status: Status
    let createdAt: Date
    
    enum Status: String, SQLEnumType {
        case created = "created"
        case verified = "verified"
    }
    
    // Decode query results (selecting rows) to a model
    static func decodeRow(r: QueryRowResult) throws -> User {
        return try User(
            id: r <| 0, // as index
            userName: r <| "name", // as field name
            age: r <|? 3, // nullable field,
            status: r <| "status", // string enum type
            createdAt: r <| "created_at"
        )
    }
    
    // Use this model as a query paramter
    // See inserting example
    func queryParameter() throws -> QueryDictionary {
        return QueryDictionary([
            //"id": // auto increment
            "name": userName,
            "age": age,
            "status": status,
            "created_at": createdAt
        ])
    }
}
    
// Selecting
let nameParam: String = "some one"
let ids: [QueryParameter] = [1, 2, 3, 4, 5, 6]
let optional:Int? = nil
let params: (Int, Int?, String, QueryArray) = (
	50,
	optional,
	nameParam,
	QueryArray(ids)
)	
let rows: [User] = try conn.query("SELECT id,name,created_at,age FROM users WHERE (age > ? OR age is ?) OR name = ? OR id IN (?)", build(params) ])

// Inserting
let age: Int? = 26
let user = User(id: 0, userName: "novi", age: age, createdAt: Date())
let status = try conn.query("INSERT INTO users SET ?", [user]) as QueryStatus
let newId = status.insertedId
        
// Updating
let defaultAge = 30
try conn.query("UPDATE users SET age = ? WHERE age is NULL;", [defaultAge])
            
        

Requirements

  • Swift 4.0

(If you are using Swift 3.1, use 0.7.4 tagged version.)

Dependencies

  • MariaDB or MySQL Connector/C (libmysqlclient) 2.2.3

macOS

This library uses Vapor's cmysql . Follow the instruction.

Ubuntu Linux

$ sudo apt-get install libmariadbclient-dev

Installation

Swift Package Manager

  • Add mysql-swift to Package.swift of your project.
// swift-tools-version:4.0
import PackageDescription

let package = Package(
    ...,
    dependencies: [
        .package(url: "https://github.com/novi/mysql-swift.git", .upToNextMinor(from: "0.8.0"))
    ],
    targets: [
        .target(
            name: "YourAppOrLibrary",
            dependencies: [
                // add a dependency
                "MySQL", 
            ]
        )
    ]
)

Usage

Connection & Querying

  1. Create a pool with options (hostname, port, password,...).
  2. Use pool.execute(). It automatically get and release a connection.
let options = Options(host: "your.mysql.host"...)
let pool = ConnectionPool(options: options) // Create pool with options
let rows: [User] = try pool.execute { conn in
	// The connection is held in this block
	try conn.query("SELECT * FROM users;") // And it returns result to outside execute block
}

Transaction

let wholeStaus: QueryStatus = try pool.transaction { conn in
	let status = try conn.query("INSERT INTO users SET ?;", [user]) as QueryStatus // Create a user
	let userId = status.insertedId // the user's id
	try conn.query("UPDATE info SET val = ? WHERE key = 'latest_user_id' ", [userId]) // Store user's id that we have created the above
}
wholeStaus.affectedRows == 1 // true

License

MIT

mysql-swift's People

Contributors

floresrobles avatar florianreinhart avatar hansospina avatar novi avatar popaaaandrei avatar

Watchers

 avatar

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.