diff --git a/sqlite/src/main/scala/lightdb/sqlite/SQLiteSupport.scala b/sqlite/src/main/scala/lightdb/sqlite/SQLiteSupport.scala index 3bcacfae..5af93a2b 100644 --- a/sqlite/src/main/scala/lightdb/sqlite/SQLiteSupport.scala +++ b/sqlite/src/main/scala/lightdb/sqlite/SQLiteSupport.scala @@ -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})") } @@ -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))