Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save Osein/d7220ae89a1485a5681bce65133e2bfb to your computer and use it in GitHub Desktop.
Save Osein/d7220ae89a1485a5681bce65133e2bfb to your computer and use it in GitHub Desktop.
//
// AppDelegate.swift
// SqliteTestApp
//
// Created by HASAN HUSEYIN GUCUYENER on 11.05.2022.
//
import UIKit
import SQLite3
import CoreData
@main
class AppDelegate: UIResponder, UIApplicationDelegate {
let sqliteFilePath = "some path"
let managedObjectModelPath = "some path"
func openSqliteDb(withPath: String) -> OpaquePointer? {
var sqliteConn: OpaquePointer?
let dbOpenResult = sqlite3_open(withPath, &sqliteConn)
if dbOpenResult == SQLITE_OK {
NSLog("[DUPLICATE REMOVER] Connected to database successfully")
return sqliteConn
} else {
NSLog("[DUPLICATE REMOVER] Cannot open sqlite database. Error code: %d", dbOpenResult)
return nil
}
}
func removeDuplicateRows(fromDb: OpaquePointer) {
var removalStatement: OpaquePointer?
let removalStatementString = """
DELETE FROM messages
WHERE primary_key IN (
SELECT msg.primary_key FROM messages AS msg
INNER JOIN (
SELECT MAX(primary_key) AS biggest_primary_key, message_id
FROM messages
GROUP BY message_id
HAVING COUNT(message_id) > 1
) AS dup
WHERE msg.message_id = dup.message_id AND msg.primary_key < dup.biggest_primary_key
)
"""
let prepareResult = sqlite3_prepare_v2(fromDb, removalStatementString, -1, &removalStatement, nil)
if prepareResult == SQLITE_OK {
let stmtResult = sqlite3_step(removalStatement)
if stmtResult == SQLITE_DONE {
NSLog("[DUPLICATE REMOVER] Removed duplicates successfully.")
} else {
NSLog("[DUPLICATE REMOVER] Error on duplicate remove operation. Error: %d", stmtResult)
}
} else {
NSLog("[DUPLICATE REMOVER] Cannot prepare remove statement. Error: %d", prepareResult)
}
sqlite3_finalize(removalStatement)
}
func sqlitePendingUpdates() -> Bool {
// 2
let managedObjectModel = NSManagedObjectModel(contentsOf: URL(fileURLWithPath: managedObjectModelPath))
// 3
let storeCoordinator = NSPersistentStoreCoordinator(managedObjectModel: managedObjectModel!)
// 4
let currentSqliteMetadata = try! NSPersistentStoreCoordinator.metadataForPersistentStore(ofType: NSSQLiteStoreType, at: URL(string: sqliteFilePath)!)
// 5
return storeCoordinator.managedObjectModel.isConfiguration(withName: nil, compatibleWithStoreMetadata: currentSqliteMetadata)
}
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
// 1
if FileManager.default.fileExists(atPath: sqliteFilePath), sqlitePendingUpdates() {
if let sqliteDbConnection = openSqliteDb(withPath: sqliteFilePath) {
removeDuplicateRows(fromDb: sqliteDbConnection)
}
}
// Init app
return true
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment