1 # This file is part of NIT ( http://www.nitlanguage.org ).
3 # Copyright 2014 Alexis Laferrière <alexis.laf@xymus.net>
5 # Licensed under the Apache License, Version 2.0 (the "License");
6 # you may not use this file except in compliance with the License.
7 # You may obtain a copy of the License at
9 # http://www.apache.org/licenses/LICENSE-2.0
11 # Unless required by applicable law or agreed to in writing, software
12 # distributed under the License is distributed on an "AS IS" BASIS,
13 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 # See the License for the specific language governing permissions and
15 # limitations under the License.
17 # `app::data_store` implementation on GNU/Linux
20 import app
::data_store
21 private import xdg_basedir
22 private import sqlite3
23 private import json
::serialization
26 redef var data_store
= new LinuxStore
29 private class LinuxStore
32 # File path of the Sqlite3 DB file
33 fun db_file
: String do return "data_store.db"
36 fun db_table
: String do return "data_store"
38 var db_cache
: nullable Sqlite3DB = null
40 # Database to use to implement the `DataStore`
41 fun db
: nullable Sqlite3DB
44 if db
!= null then return db
47 var config_home
= xdg_basedir
.config_home
.to_s
48 var config_dir
= config_home
.join_path
(sys
.program_name
.basename
(""))
49 if not config_dir
.file_exists
then config_dir
.mkdir
50 var db_path
= config_dir
.join_path
(db_file
)
53 db
= new Sqlite3DB.open
(db_path
)
54 if not db
.is_open
then
55 print_error
"Data store unavaible, cannot load/save data. (at '{db_path}' with '{db.error or else "unknown"}')"
60 db
.create_table
"IF NOT EXISTS {db_table} (key TEXT PRIMARY KEY, value TEXT)"
70 if db
== null then return null
72 # Prepare SELECT statement
73 var stmt
= db
.select
("* FROM {db_table} WHERE key == {key.to_sql_string}")
78 var serialized
= row
[1].to_s
82 var deserializer
= new JsonDeserializer(serialized
)
83 var deserialized
= deserializer
.deserialize
92 redef fun []=(key
, value
)
96 if db
== null then return
99 var stream
= new StringWriter
100 var serializer
= new JsonSerializer(stream
)
101 serializer
.serialize value
102 var serialized
= stream
.to_s
105 db
.execute
"BEGIN TRANSACTION"
106 db
.insert
"OR REPLACE INTO {db_table} VALUES({key.to_sql_string}, {serialized.to_sql_string})"