I’m trying to create a common method to delete all rows from all DB files in my project.
I don’t want to store and pass all tables names, so it should work only with a DB file path.
I tried to get all tables from the DB file via this code:
<code> guard
let path = getDBPath(for: .contacts),
let dbQueue = FMDatabaseQueue(path: path)
else { return }
dbQueue.inDatabase { fmdb in
do {
let resultSet = try fmdb.executeQuery(
"SELECT name FROM sqlite_master WHERE type='table'",
values: nil
)
// what is next?
} catch {
// log error
}
}
</code>
<code> guard
let path = getDBPath(for: .contacts),
let dbQueue = FMDatabaseQueue(path: path)
else { return }
dbQueue.inDatabase { fmdb in
do {
let resultSet = try fmdb.executeQuery(
"SELECT name FROM sqlite_master WHERE type='table'",
values: nil
)
// what is next?
} catch {
// log error
}
}
</code>
guard
let path = getDBPath(for: .contacts),
let dbQueue = FMDatabaseQueue(path: path)
else { return }
dbQueue.inDatabase { fmdb in
do {
let resultSet = try fmdb.executeQuery(
"SELECT name FROM sqlite_master WHERE type='table'",
values: nil
)
// what is next?
} catch {
// log error
}
}
But I can’t figure out what I have to do after fmdb.executeQuery
.
Where do I need to call "DELETE FROM (tableName)"
?
Well, I managed it finally:
<code> let resultSet = try fmdb.executeQuery(
"SELECT name FROM sqlite_master WHERE type='table' AND name LIKE '%object%'", // I use `AND name LIKE '%object%'` to not clear any internal (system) tables, all my own entities have `object` word in their names
values: []
)
while resultSet.next() {
if let table = resultSet.string(forColumn: "name") {
try fmdb.executeUpdate(
"DELETE FROM (table)",
values: []
)
}
}
</code>
<code> let resultSet = try fmdb.executeQuery(
"SELECT name FROM sqlite_master WHERE type='table' AND name LIKE '%object%'", // I use `AND name LIKE '%object%'` to not clear any internal (system) tables, all my own entities have `object` word in their names
values: []
)
while resultSet.next() {
if let table = resultSet.string(forColumn: "name") {
try fmdb.executeUpdate(
"DELETE FROM (table)",
values: []
)
}
}
</code>
let resultSet = try fmdb.executeQuery(
"SELECT name FROM sqlite_master WHERE type='table' AND name LIKE '%object%'", // I use `AND name LIKE '%object%'` to not clear any internal (system) tables, all my own entities have `object` word in their names
values: []
)
while resultSet.next() {
if let table = resultSet.string(forColumn: "name") {
try fmdb.executeUpdate(
"DELETE FROM (table)",
values: []
)
}
}
1