-
Notifications
You must be signed in to change notification settings - Fork 1
/
TJDatabaseManager.swift
executable file
·128 lines (114 loc) · 3.69 KB
/
TJDatabaseManager.swift
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
// TJDatabaseManager.swift
// Database Demo
//
// Created by Tejas Ardeshna on 09/08/17.
// Copyright © 2017 Tejas Ardeshna. All rights reserved.
//
import UIKit
import FMDB
let kDataBaseName = "YOUR_DATABASENAME" //don't include file extention
class TJDatabaseManager {
let applyDatabaseVersoning = false //if you want to create database copy for each new version release
// static properties get lazy evaluation and dispatch_once_t for free
struct Static {
static let instance = TJDatabaseManager()
}
// this is the Swift way to do singletons
class var databaseManager: TJDatabaseManager
{
return Static.instance
}
//
//Copy database to diractory
//
func copyDatabaseIfNeeded() {
//Using NSFileManager we can perform many file system operations.
let bundlePath = Bundle.main.path(forResource: kDataBaseName, ofType: ".sqlite")
let fileManager = FileManager.default
let fullDestPath = URL(string : self.getDBPath())
if fileManager.fileExists(atPath: (fullDestPath?.path)!){
print("Database file is exist")
print(fullDestPath!.path)
}else{
do{
try fileManager.copyItem(atPath: bundlePath!, toPath: (fullDestPath?.path)!)
print("DB Path:\(fullDestPath!.path)")
}catch{
}
}
}
//
// Find database path
//
func getDBPath() -> String {
let paths: [Any] = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)
let documentsDir: String = paths[0] as? String ?? ""
let strDatabaseName: String = applyDatabaseVersoning ? self.getDatabaseNameWithVersionNumber() : kDataBaseName
return URL(fileURLWithPath: documentsDir).appendingPathComponent(strDatabaseName).absoluteString + ".sqlite"
}
//
// Execute update
//
func executeUpdate(_ query: String) -> Bool {
var status: Bool
let db = FMDatabase(path: self.getDBPath())
db.open()
do {
try db.executeUpdate(query, values: nil)
status = true
} catch {
print(error)
status = false
}
db.close()
return status
}
//
// Execute custom query
//
func execute(_ query: String) -> [AnyObject]{
var array = [AnyObject]()
let db = FMDatabase(path: self.getDBPath())
db.open()
var rs: FMResultSet?
do {
rs = try db.executeQuery(query, values: nil)
}
catch{
}
if rs != nil{
while rs!.next() {
array.append(rs?.resultDictionary as AnyObject)
}
rs?.close()
}
defer {
}
db.close()
return array
}
//
// For database versoning
//
func getDatabaseNameWithVersionNumber() -> String {
let buildVersion = Bundle.main.infoDictionary?[kCFBundleVersionKey as String] as? String
let strVersionNumber: String = buildVersion!.replacingOccurrences(of: ".", with: "_")
let strDatabaseName: String = "\(strVersionNumber)\(kDataBaseName)"
return strDatabaseName
}
//
// Perform batch operations
//
func executeBatchOperations(_ arrQueries: [String]) {
let queue = FMDatabaseQueue(path: self.getDBPath())
queue.inTransaction({ (db, rollback) in
for query: String in arrQueries {
do {
try db.executeUpdate(query, values: nil)
} catch {
print(error)
}
}
})
}
}