• Stars
    star
    163
  • Rank 231,141 (Top 5 %)
  • Language
    Swift
  • License
    MIT License
  • Created almost 9 years ago
  • Updated 11 months ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

A type safe MySQL client for Swift

mysql-swift

This library is obsolete and not maintained. Use MySQLNIO instead.

Platform Linux, macOS CircleCI

MySQL client library for Swift. This is inspired by Node.js' mysql.

  • Based on libmysqlclient
  • Raw SQL query
  • Simple query formatting and escaping (same as Node's)
  • Mapping queried results to Codable structs or classes

Note: No asynchronous I/O support currently. It depends libmysqlclient.

// Declare a model

struct User: Codable, QueryParameter {
    let id: Int
    let userName: String
    let age: Int?
    let status: Status
    let createdAt: Date
    
    enum Status: String, Codable {
        case created = "created"
        case verified = "verified"
    }
    
    private enum CodingKeys: String, CodingKey {
        case id
        case userName = "user_name"
        case age
        case status = "status"
        case createdAt = "created_at"
    }
}
    
// Selecting
let nameParam = "some one"
let ids: [QueryParameter] = [1, 2, 3, 4, 5, 6]
let optionalInt: Int? = nil
let rows: [User] = try conn.query("SELECT id,user_name,status,status,created_at FROM `user` WHERE (age > ? OR age is ?) OR name = ? OR id IN (?)", [50, optionalInt, nameParam, QueryArray(ids)] ])

// Inserting
let age: Int? = 26
let user = User(id: 0, userName: "novi", age: age, status: .created, createdAt: Date())
let status = try conn.query("INSERT INTO `user` SET ?", [user]) as QueryStatus
let newId = status.insertedId

// Updating
let tableName = "user"
let defaultAge = 30
try conn.query("UPDATE ?? SET age = ? WHERE age is NULL;", [tableName, defaultAge])

Requirements

  • Swift 5.0 or later
  • MariaDB or MySQL Connector/C (libmysqlclient) 2.2.3 or later

macOS

Install pkg-config .pc file in cmysql or cmysql-mariadb.

# cmysql
$ brew tap novi/tap
$ brew install novi/tap/cmysql

# cmysql-mariadb
$ brew tap novi/tap
$ brew install novi/tap/cmysqlmariadb

Ubuntu

$ sudo apt-get install libmariadbclient-dev

Installation

Swift Package Manager

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

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

Usage

Connection & Querying

  1. Create a pool with options (hostname, port, password,...).
  2. Use ConnectionPool.execute(). It automatically get and release a connection.
let option = Option(host: "your.mysql.host"...) // Define and create your option type
let pool = ConnectionPool(option: option) // Create a pool with the option
let rows: [User] = try pool.execute { conn in
	// The connection `conn` 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 some_value = ? WHERE some_key = 'latest_user_id' ", [userId]) // Store user's id that we have created the above
}
wholeStaus.affectedRows == 1 // true

License

MIT

More Repositories

1

LTCoreText

Lightweight paging text view using CoreText suitable for Book App
Objective-C
147
star
2

mecab-swift

MeCab(Japanese Morphological Analyzer) wrapper for Swift
Swift
73
star
3

LTAPIRequest

RESTful な API を持つ Web サービス用クライアント型iOSアプリのひな形
Objective-C
40
star
4

Kunugi

Minimal web framework and middleware for Swift
Swift
34
star
5

SwiftMagickWand

MagickWand(ImageMagick) wrapper for Swift
Swift
25
star
6

FakeClockUp

FakeClockUp iOS MobileSubstrate PlugIn
Logos
20
star
7

i2c-swift-example

Use I2C bus device with Swift
Swift
19
star
8

LTIOUSB

IOKit (USB) wrapper for Cocoa / CocoaでUSBドライバを作成するためのIOKitラッパー(ヘルパー)です。
Objective-C
15
star
9

i2c-swift

I2C Bus Library for Swift
Swift
10
star
10

HALAudio

CoreAudio Hardware wrapper for Swift
Swift
9
star
11

nextasic

Verilog HDL implementation of ASIC for NeXT Sound Box hardware.
Verilog
8
star
12

next-kbd-emu

NeXT NonADB Keyboard emulator based on ESP8266
C++
6
star
13

CoreTextJapanese

CoreTextで日本語を扱うと行間が不自然に空く仕様を直す
Objective-C
6
star
14

SoundBlaster16PCI

Sound Blaster 16 PCI Driver with an es1371 chip (VMware Fusion) for NEXTSTEP/OPENSTEP
C
6
star
15

scsiemu-pcb

Level Converters for SCSI-bus Emulators
5
star
16

nkf-swift

nkf(Network Kanji Filter) for Swift
C
5
star
17

stm32f4-hub-test

Example code of USB Host, USB Hub for STM32F401 with PlatformIO, STM Cube framework
C
4
star
18

mongodiary

Node.js+Mongoose+MongoDB で作るWebアプリ
JavaScript
4
star
19

tsssm-crawler

Demonstrates how to implement simple RSS crawler in Server-Side Swift with Cocoa based Management tools
Swift
4
star
20

ipad-oneseg

LOG-J200 Oneseg Tuner Driver for iPad
Objective-C
4
star
21

i2c_tiny_usb

ATTiny85 optimized version of i2c-tiny-usb (see attiny85 branch)
C
4
star
22

ScrollViewOverlayWithZooming

UIScrollViewのZoomingでオーバーレイしたViewをズームさせないやつのサンプル (Avoid zoom UIView on specified zooming view)
Objective-C
3
star
23

proconapp

高専プログラミングコンテスト公式 App
Swift
3
star
24

tsssm-enum

値付きEnumをHackする
Swift
2
star
25

next2usb

NeXT NonADB Keyboard to USB converter
C
2
star
26

CMeCab

MeCab module for Swift on Linux
Swift
2
star
27

LTUtils

Objective-C
2
star
28

CapOneSegMac

Example Implementation of LTIOUSB, One-seg tuner driver for LOG-J200
Objective-C
2
star
29

4004MainBoard

Intel 4004 Single Board Computer (KiCad project)
2
star
30

docker-swift-dev

Dockerfile
2
star
31

gnstg

Cによるオブジェクト指向で作ったシューティングゲーム (課題レポート)
2
star
32

nextstep_experiment

C
2
star
33

LTGridView

Lightweight grid view based on UIScrollView for multiple use
Objective-C
2
star
34

casl-emulator

Cocoa版 CASLエミュレータ
Objective-C
1
star
35

lthttp

Objective-CベースのWebサーバーが作れるかどうか試している
Objective-C
1
star
36

swift-date

Simple date and time structure for Swift
Swift
1
star
37

proconapp-lp

proconappのランディングページ
CSS
1
star
38

todoapi-example

Example of API Server communicates with MySQL written in Swift
Swift
1
star
39

beagleledtest

JavaScript
1
star
40

word2vec-swift

C
1
star
41

i2s_to_lj16

Converting from I2S audio to Left Justified 16bit format with 2xWCK, suitable for early SONY' DAC such as CX20017.
Verilog
1
star
42

shuriken-video

Gamecube digital AV output to HDMI converter with SPDIF output
VHDL
1
star