NetNewsWire/Frameworks/RSDatabase/DatabaseTable.swift

80 lines
2.0 KiB
Swift
Raw Normal View History

//
// DatabaseTable.swift
// RSDatabase
//
// Created by Brent Simmons on 7/16/17.
// Copyright © 2017 Ranchero Software, LLC. All rights reserved.
//
import Foundation
2017-07-17 05:51:08 +02:00
public protocol DatabaseTable {
2017-07-29 21:13:38 +02:00
var name: String {get}
var queue: RSDatabaseQueue {get}
2017-07-17 05:51:08 +02:00
2017-07-29 21:13:38 +02:00
init(name: String, queue: RSDatabaseQueue)
2017-07-17 05:51:08 +02:00
}
public extension DatabaseTable {
// MARK: Fetching
public func selectRowsWhere(key: String, equals value: Any, in database: FMDatabase) -> FMResultSet? {
2017-07-17 05:51:08 +02:00
return database.rs_selectRowsWhereKey(key, equalsValue: value, tableName: name)
2017-07-17 05:51:08 +02:00
}
public func selectRowsWhere(key: String, inValues values: [Any], in database: FMDatabase) -> FMResultSet? {
return database.rs_selectRowsWhereKey(key, inValues: values, tableName: name)
}
// MARK: Deleting
2017-07-17 05:51:08 +02:00
public func deleteRowsWhere(key: String, equalsAnyValue values: [Any], in database: FMDatabase) {
if values.isEmpty {
return
}
database.rs_deleteRowsWhereKey(key, inValues: values, tableName: name)
}
// MARK: Updating
public func updateRowsWithValue(_ value: Any, valueKey: String, whereKey: String, matches: [Any]) {
queue.update { (database: FMDatabase!) in
let _ = database.rs_updateRows(withValue: value, valueKey: valueKey, whereKey: whereKey, inValues: matches, tableName: self.name)
}
}
// MARK: Saving
2017-08-05 20:12:45 +02:00
public func insertRows(_ dictionaries: [NSDictionary], insertType: RSDatabaseInsertType, in database: FMDatabase) {
2017-08-05 20:12:45 +02:00
dictionaries.forEach { (oneDictionary) in
let _ = database.rs_insertRow(with: oneDictionary as [NSObject: AnyObject], insertType: insertType, tableName: self.name)
}
}
// MARK: Counting
func numberWithCountResultSet(_ resultSet: FMResultSet?) -> Int {
if let resultSet = resultSet, resultSet.next() {
return Int(resultSet.int(forColumnIndex: 0))
}
return 0
}
func numberWithSQLAndParameters(_ sql: String, _ parameters: [Any], in database: FMDatabase) -> Int {
let resultSet = database.executeQuery(sql, withArgumentsIn: parameters)
return numberWithCountResultSet(resultSet)
}
}