Skip to content

Commit

Permalink
Fixed altered database columns in SQLite
Browse files Browse the repository at this point in the history
  • Loading branch information
darkfrog26 committed May 12, 2024
1 parent 9231394 commit ca47aea
Showing 1 changed file with 17 additions and 0 deletions.
17 changes: 17 additions & 0 deletions sqlite/src/main/scala/lightdb/sqlite/SQLiteSupport.scala
Original file line number Diff line number Diff line change
Expand Up @@ -30,8 +30,12 @@ trait SQLiteSupport[D <: Document[D]] extends IndexSupport[D] {
val s = c.createStatement()
try {
s.executeUpdate(s"CREATE TABLE IF NOT EXISTS ${collection.collectionName}(${index.fields.map(_.fieldName).mkString(", ")}, PRIMARY KEY (_id))")
val existingColumns = columns(c)
index.fields.foreach { f =>
if (f.fieldName != "_id") {
if (!existingColumns.contains(f.fieldName)) {
s.executeUpdate(s"ALTER TABLE ${collection.collectionName} ADD ${f.fieldName}")
}
val indexName = s"${f.fieldName}_idx"
s.executeUpdate(s"CREATE INDEX IF NOT EXISTS $indexName ON ${collection.collectionName}(${f.fieldName})")
}
Expand All @@ -43,6 +47,19 @@ trait SQLiteSupport[D <: Document[D]] extends IndexSupport[D] {
c
}

def columns(connection: Connection = connection): Set[String] = {
val ps = connection.prepareStatement(s"SELECT * FROM ${collection.collectionName} LIMIT 1")
try {
val rs = ps.executeQuery()
val meta = rs.getMetaData
(1 to meta.getColumnCount).map { index =>
meta.getColumnName(index)
}.toSet
} finally {
ps.close()
}
}

override lazy val index: SQLiteIndexer[D] = SQLiteIndexer(this, () => collection)

val _id: SQLIndexedField[Id[D], D] = index("_id", doc => Some(doc._id))
Expand Down

0 comments on commit ca47aea

Please sign in to comment.