Skip to content

Commit

Permalink
Merge pull request #37 from moneymanagerex/create_sample
Browse files Browse the repository at this point in the history
create sample database
  • Loading branch information
guanlisheng authored Sep 25, 2024
2 parents 49ead67 + 11df3ed commit 050a7b1
Show file tree
Hide file tree
Showing 6 changed files with 779 additions and 13 deletions.
12 changes: 12 additions & 0 deletions MMEX.xcodeproj/project.pbxproj
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
objects = {

/* Begin PBXBuildFile section */
920823F42CA3D16400388AB2 /* tables.sql in Resources */ = {isa = PBXBuildFile; fileRef = 920823F32CA3D16400388AB2 /* tables.sql */; };
929EF65F2C9FF2DE0051A3E6 /* AssetData.swift in Sources */ = {isa = PBXBuildFile; fileRef = 929EF65E2C9FF2DE0051A3E6 /* AssetData.swift */; };
929EF6612C9FF2FD0051A3E6 /* StockData.swift in Sources */ = {isa = PBXBuildFile; fileRef = 929EF6602C9FF2FD0051A3E6 /* StockData.swift */; };
929EF6632C9FF3ED0051A3E6 /* AssetRepository.swift in Sources */ = {isa = PBXBuildFile; fileRef = 929EF6622C9FF3ED0051A3E6 /* AssetRepository.swift */; };
Expand Down Expand Up @@ -80,6 +81,7 @@
/* End PBXBuildFile section */

/* Begin PBXFileReference section */
920823F32CA3D16400388AB2 /* tables.sql */ = {isa = PBXFileReference; lastKnownFileType = text; path = tables.sql; sourceTree = "<group>"; };
929EF65E2C9FF2DE0051A3E6 /* AssetData.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AssetData.swift; sourceTree = "<group>"; };
929EF6602C9FF2FD0051A3E6 /* StockData.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = StockData.swift; sourceTree = "<group>"; };
929EF6622C9FF3ED0051A3E6 /* AssetRepository.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AssetRepository.swift; sourceTree = "<group>"; };
Expand Down Expand Up @@ -175,6 +177,14 @@
);
path = Assets;
sourceTree = "<group>";
};
920823F22CA3D11F00388AB2 /* Resources */ = {
isa = PBXGroup;
children = (
920823F32CA3D16400388AB2 /* tables.sql */,
);
path = Resources;
sourceTree = "<group>";
};
A3462F672C948C8400F79145 /* Protocols */ = {
isa = PBXGroup;
Expand Down Expand Up @@ -321,6 +331,7 @@
A3C1425E2C8DE70300D3CEC0 /* DatabaseManager.swift */,
929EF6702CA3676B0051A3E6 /* MMEXDocument.swift */,
A3C1422E2C89751600D3CEC0 /* Assets.xcassets */,
920823F22CA3D11F00388AB2 /* Resources */,
A3C142302C89751600D3CEC0 /* Preview Content */,
);
path = MMEX;
Expand Down Expand Up @@ -437,6 +448,7 @@
files = (
A3C142322C89751600D3CEC0 /* Preview Assets.xcassets in Resources */,
A3C1422F2C89751600D3CEC0 /* Assets.xcassets in Resources */,
920823F42CA3D16400388AB2 /* tables.sql in Resources */,
);
runOnlyForDeploymentPostprocessing = 0;
};
Expand Down
27 changes: 25 additions & 2 deletions MMEX/ContentView.swift
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ import SwiftUI
struct ContentView: View {
@State private var isDocumentPickerPresented = false
@State private var isNewDocumentPickerPresented = false
@State private var isSampleDocumnt = false
@State private var selectedTab = 0
@State private var selectedFileURL: URL?
@State private var isPresentingTransactionAddView = false
Expand Down Expand Up @@ -98,6 +99,11 @@ struct ContentView: View {
}
Button("New Database") {
isNewDocumentPickerPresented = true
isSampleDocumnt = false
}
Button("Sample Database") {
isNewDocumentPickerPresented = true
isSampleDocumnt = true
}
}
}
Expand Down Expand Up @@ -129,12 +135,29 @@ struct ContentView: View {
isPresented: $isNewDocumentPickerPresented,
document: MMEXDocument(),
contentType: .mmb,
defaultFilename: "Untitled.mmb"
defaultFilename: isSampleDocumnt ? "Sample.mmb" : "Untitled.mmb"
) { result in
switch result {
case .success(let url):
print("Successfully created new document: \(url)")
MMEXDocument.create(at: url)
if url.startAccessingSecurityScopedResource() {
selectedFileURL = url
UserDefaults.standard.set(url.path, forKey: "SelectedFilePath")
url.stopAccessingSecurityScopedResource()
} else {
print("Unable to access file at URL: \(url)")
}
let dataManager = DataManager(databaseURL: url)
let repository = dataManager.getRepository()
guard let tables = Bundle.main.url(forResource: "tables.sql", withExtension: "") else {
print("Cannot find tables.sql in bundle")
return
}
repository.execute(url: tables)
if isSampleDocumnt { repository.insertSampleData() }
DispatchQueue.main.asyncAfter(deadline: .now() + 0.1) {
selectedTab = 0
}
case .failure(let error):
print("Failed to create a new document: \(error.localizedDescription)")
}
Expand Down
4 changes: 4 additions & 0 deletions MMEX/DatabaseManager.swift
Original file line number Diff line number Diff line change
Expand Up @@ -53,6 +53,10 @@ class DataManager {
}
}

func getRepository() -> Repository {
return Repository(db: db)
}

func getInfotableRepository() -> InfotableRepository {
return InfotableRepository(db: db)
}
Expand Down
20 changes: 11 additions & 9 deletions MMEX/MMEXDocument.swift
Original file line number Diff line number Diff line change
Expand Up @@ -25,17 +25,19 @@ struct MMEXDocument: FileDocument {
}
}

/*
extension MMEXDocument {
static func create(at url: URL) {
let dataManager = DataManager(databaseURL: url)
dataManager.getInfotableRepository().create()
dataManager.getCurrencyRepository().create()
dataManager.getAccountRepository().create()
dataManager.getAssetRepository().create()
dataManager.getStockRepository().create()
dataManager.getCategoryRepository().create()
dataManager.getPayeeRepository().create()
dataManager.getTransactionRepository().create()
dataManager.getScheduledRepository().create()
dataManager.getInfotableRepository().create()
dataManager.getCurrencyRepository().create()
dataManager.getAccountRepository().create()
dataManager.getAssetRepository().create()
dataManager.getStockRepository().create()
dataManager.getCategoryRepository().create()
dataManager.getPayeeRepository().create()
dataManager.getTransactionRepository().create()
dataManager.getScheduledRepository().create()
}
}
*/
179 changes: 177 additions & 2 deletions MMEX/Repositories/Repository.swift
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,51 @@
import Foundation
import SQLite

class Repository {
let db: Connection?
init(db: Connection?) {
self.db = db
}
}

extension Repository {
func execute(sql: String) {
guard let db else { return }
print("Executing sql: \(sql)")
do {
try db.execute(sql)
} catch {
print("Failed to execute sql: \(error)")
}
}

func execute(url: URL) {
if db == nil { return }
guard let contents = try? String(contentsOf: url) else {
print("Failed to read \(url)")
return
}

// split contents into paragraphs and execute each paragraph
var paragraph = ""
for line in contents.components(separatedBy: "\n") {
if line.starts(with: "--") { continue }
if line.trimmingCharacters(in: .whitespaces).isEmpty {
if !paragraph.isEmpty {
execute(sql: paragraph)
paragraph = ""
}
} else {
if !paragraph.isEmpty { paragraph.append("\n") }
paragraph.append(line)
}
}
if !paragraph.isEmpty {
execute(sql: paragraph)
}
}
}

protocol RepositoryProtocol {
associatedtype RepositoryData: DataProtocol

Expand Down Expand Up @@ -56,8 +101,7 @@ extension RepositoryProtocol {
let data = Self.selectData(row)
print("Successfull pluck for \(key) in \(Self.repositoryName): \(data.shortDesc())")
return data
}
else {
} else {
print("Unsuccefull pluck for \(key) in \(Self.repositoryName)")
return nil
}
Expand Down Expand Up @@ -128,4 +172,135 @@ extension RepositoryProtocol {
return false
}
}

func deleteAll() -> Bool {
guard let db else { return false }
do {
let query = Self.table.delete()
try db.run(query)
print("Successfull delete all in \(RepositoryData.dataName)")
return true
} catch {
print("Failed delete all in \(RepositoryData.dataName): \(error)")
return false
}
}
}

extension Repository {
func insertSampleData() {

var infotableMap: [Int64: Int64] = [:]
do {
let repo = InfotableRepository(db: db)
_ = repo.deleteAll()
for var data in InfotableData.sampleData {
let id = data.id
_ = repo.insert(&data)
infotableMap[id] = data.id
}
}

var currencyMap: [Int64: Int64] = [:]
do {
let repo = CurrencyRepository(db: db)
_ = repo.deleteAll()
for var data in CurrencyData.sampleData {
let id = data.id
_ = repo.insert(&data)
currencyMap[id] = data.id
}
}

var accountMap: [Int64: Int64] = [:]
do {
let repo = AccountRepository(db: db)
_ = repo.deleteAll()
for var data in AccountData.sampleData {
let id = data.id
data.currencyId = currencyMap[data.currencyId] ?? data.currencyId
_ = repo.insert(&data)
accountMap[id] = data.id
}
}

var assetMap: [Int64: Int64] = [:]
do {
let repo = AssetRepository(db: db)
_ = repo.deleteAll()
for var data in AssetData.sampleData {
let id = data.id
data.currencyId = currencyMap[data.currencyId] ?? data.currencyId
_ = repo.insert(&data)
assetMap[id] = data.id
}
}

var stockMap: [Int64: Int64] = [:]
do {
let repo = StockRepository(db: db)
_ = repo.deleteAll()
for var data in StockData.sampleData {
let id = data.id
data.accountId = accountMap[data.accountId] ?? data.accountId
_ = repo.insert(&data)
stockMap[id] = data.id
}
}

var categoryMap: [Int64: Int64] = [:]
do {
let repo = CategoryRepository(db: db)
_ = repo.deleteAll()
for var data in CategoryData.sampleData {
let id = data.id
data.parentId = categoryMap[data.parentId] ?? data.parentId
_ = repo.insert(&data)
categoryMap[id] = data.id
}
}

var payeeMap: [Int64: Int64] = [:]
do {
let repo = PayeeRepository(db: db)
_ = repo.deleteAll()
for var data in PayeeData.sampleData {
let id = data.id
data.categoryId = categoryMap[data.categoryId] ?? data.categoryId
_ = repo.insert(&data)
payeeMap[id] = data.id
}
}

var transactionMap: [Int64: Int64] = [:]
do {
let repo = TransactionRepository(db: db)
_ = repo.deleteAll()
for var data in TransactionData.sampleData {
let id = data.id
data.accountId = accountMap[data.accountId] ?? data.accountId
data.toAccountId = accountMap[data.toAccountId] ?? data.toAccountId
data.payeeId = payeeMap[data.payeeId] ?? data.payeeId
data.categId = categoryMap[data.categId] ?? data.categId
_ = repo.insert(&data)
transactionMap[id] = data.id
}
}

var scheduledMap: [Int64: Int64] = [:]
do {
let repo = ScheduledRepository(db: db)
_ = repo.deleteAll()
for var data in ScheduledData.sampleData {
let id = data.id
data.accountId = accountMap[data.accountId] ?? data.accountId
data.toAccountId = accountMap[data.toAccountId] ?? data.toAccountId
data.payeeId = payeeMap[data.payeeId] ?? data.payeeId
data.categId = categoryMap[data.categId] ?? data.categId
_ = repo.insert(&data)
scheduledMap[id] = data.id
}
}

}
}
Loading

0 comments on commit 050a7b1

Please sign in to comment.