Sub Process_Globals
End Sub
Sub Globals
Private sql As SQL
End Sub
Sub Activity_Create(FirstTime As Boolean)
sql.Initialize(File.DirInternal,"db",True)
InsertJson("{key1: val1}",False) 'Table will contain column 'key1'
InsertJson("{key3: val3}",False) 'Table will contain columns 'key1' and 'key3'
InsertJson("{key3: val3, key4: val4, key5: val5}",True) 'Table will contain columns 'key3', 'key4' and 'key5' (Column 'key1' will be dropped)
Log("--------Columns--------")
Dim Res As ResultSet = sql.ExecQuery("PRAGMA table_info(json)")
Do While Res.NextRow
Log(Res.GetString("name"))
Loop
Log("-------------------------")
Res.Close
End Sub
Sub Activity_Resume
End Sub
Sub Activity_Pause (UserClosed As Boolean)
End Sub
'When reset is set to true all columns that doesn't exists in json will be dropped.
Sub InsertJson (Json As String, Reset As Boolean)
sql.ExecNonQuery("CREATE TABLE IF NOT EXISTS json (rowid INTEGER PRIMARY KEY)")
Dim Res As ResultSet = sql.ExecQuery("PRAGMA table_info(json)")
Dim par As JSONParser : par.Initialize(Json)
Dim k As Map = par.NextObject
Do While Res.NextRow
For Each key As String In k.Keys
If Res.GetString("name") = key Then
k.Remove(key)
Exit
End If
Next
Loop
For Each key As String In k.Keys
sql.ExecNonQuery($"ALTER TABLE json ADD COLUMN ${key} NONE"$)
Next
Res.Close
par.Initialize(Json)
k = par.NextObject
If Reset Then
Dim c As String
For Each key As String In k.Keys
c = c & key & ","
Next
c = c.SubString2(0,c.LastIndexOf(","))
sql.ExecNonQuery($"CREATE TABLE json_backup(rowid INTEGER PRIMARY KEY,${c})"$)
sql.ExecNonQuery($"INSERT INTO json_backup Select rowid,${c} FROM json"$)
sql.ExecNonQuery($"DROP TABLE json"$)
sql.ExecNonQuery($"CREATE TABLE json(rowid INTEGER PRIMARY key,${c})"$)
sql.ExecNonQuery($"INSERT INTO json Select rowid,${c} FROM json_backup"$)
sql.ExecNonQuery($"DROP TABLE json_backup"$)
End If
Dim part1 = "INSERT INTO json (", part2 = ") VALUES (" As String
For Each key As String In k.Keys
part1 = part1 & key & ","
part2 = part2 & $"'${k.Get(key)}',"$
Next
part1 = part1.SubString2(0,part1.LastIndexOf(","))
part2 = part2.SubString2(0,part2.LastIndexOf(","))
sql.ExecQuery(part1 & part2 & ")")
k.Clear
End Sub