Files
NetNewsWire/Modules/RSDatabase/Sources/RSDatabase/FMDatabase+Extras.swift
T

124 lines
3.9 KiB
Swift
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
//
// FMDatabase+Extras.swift
//
//
// Created by Brent Simmons on 3/10/24.
//
import Foundation
import RSDatabaseObjC
import os
public extension FMDatabase {
static func openAndSetUpDatabase(path: String) -> FMDatabase {
let database = FMDatabase(path: path)!
database.open()
database.executeStatements("PRAGMA synchronous = 1;")
database.setShouldCacheStatements(true)
return database
}
func executeUpdateInTransaction(_ sql: String, withArgumentsIn parameters: [Any]? = nil) {
beginTransaction()
guard executeUpdate(sql, withArgumentsIn: parameters) else {
rollback()
return
}
commit()
}
/// Vacuum the database if it’s been more than `daysBetweenVacuums` since the last vacuum.
/// Call this as part of an init method.
func vacuumIfNeeded(daysBetweenVacuums: Int, filepath: String) {
let defaultsKey = "FMDatabase-LastVacuumDate-\(filepath)"
let now = Date()
guard let lastVacuumDate = UserDefaults.standard.object(forKey: defaultsKey) as? Date else {
// Never vacuumed — probably a new database.
// Set the LastVacuumDate pref to now and skip vacuuming.
UserDefaults.standard.set(now, forKey: defaultsKey)
return
}
let minimumVacuumInterval = TimeInterval(daysBetweenVacuums * (60 * 60 * 24)) // Doesn’t have to be precise
let cutoffDate = now - minimumVacuumInterval
if lastVacuumDate < cutoffDate {
vacuum()
UserDefaults.standard.set(now, forKey: defaultsKey)
}
}
private static let logger = Logger(subsystem: Bundle.main.bundleIdentifier!, category: "FMDatabase")
func vacuum() {
let shortName: String
if let path = databasePath() {
let components = (path as NSString).pathComponents
let count = components.count
if count >= 2 {
shortName = components[count - 2] + "/" + components[count - 1]
} else {
shortName = components.last ?? path
}
} else {
shortName = "unknown"
}
let start = CFAbsoluteTimeGetCurrent()
executeStatements("vacuum;")
let duration = CFAbsoluteTimeGetCurrent() - start
Self.logger.debug("VACUUM \(shortName) took \(duration, format: .fixed(precision: 4)) seconds")
}
func runCreateStatements(_ statements: String) {
statements.enumerateLines { (line, stop) in
if line.lowercased().hasPrefix("create") {
self.executeStatements(line)
}
stop = false
}
}
func insertRows(_ dictionaries: [DatabaseDictionary], insertType: RSDatabaseInsertType, tableName: String) {
for dictionary in dictionaries {
insertRow(dictionary, insertType: insertType, tableName: tableName)
}
}
func insertRow(_ dictionary: DatabaseDictionary, insertType: RSDatabaseInsertType, tableName: String) {
rs_insertRow(with: dictionary, insertType: insertType, tableName: tableName)
}
func updateRowsWithValue(_ value: Any, valueKey: String, whereKey: String, equalsAnyValue values: [Any], tableName: String) {
rs_updateRows(withValue: value, valueKey: valueKey, whereKey: whereKey, inValues: values, tableName: tableName)
}
func updateRowsWithValue(_ value: Any, valueKey: String, whereKey: String, equals match: Any, tableName: String) {
updateRowsWithValue(value, valueKey: valueKey, whereKey: whereKey, equalsAnyValue: [match], tableName: tableName)
}
func updateRowsWithDictionary(_ dictionary: [String: Any], whereKey: String, equals value: Any, tableName: String) {
rs_updateRows(with: dictionary, whereKey: whereKey, equalsValue: value, tableName: tableName)
}
func deleteRowsWhere(key: String, equalsAnyValue values: [Any], tableName: String) {
rs_deleteRowsWhereKey(key, inValues: values, tableName: tableName)
}
func selectRowsWhere(key: String, equalsAnyValue values: [Any], tableName: String) -> FMResultSet? {
rs_selectRowsWhereKey(key, inValues: values, tableName: tableName)
}
func count(sql: String, parameters: [Any]?, tableName: String) -> Int? {
guard let resultSet = executeQuery(sql, withArgumentsIn: parameters) else {
return nil
}
let count = resultSet.intWithCountResult()
return count
}
}