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 module linux_data_store
19 import app
::data_store
20 private import xdg_basedir
21 private import sqlite3
22 private import json_serialization
25 redef var data_store
= new LinuxStore
28 private class LinuxStore
31 # File path of the Sqlite3 DB file
32 fun db_file
: String do return "data_store.db"
35 fun db_table
: String do return "data_store"
37 var db_cache
: nullable Sqlite3DB = null
39 # Database to use to implement the `DataStore`
40 fun db
: nullable Sqlite3DB
43 if db
!= null then return db
46 var config_home
= xdg_basedir
.config_home
.to_s
47 var config_dir
= config_home
.join_path
(sys
.program_name
.basename
(""))
48 if not config_dir
.file_exists
then config_dir
.mkdir
49 var db_path
= config_dir
.join_path
(db_file
)
52 db
= new Sqlite3DB.open
(db_path
)
53 if not db
.is_open
then
54 app
.log_error
"Data store unavaible, cannot load/save data. (at '{db_path}' with '{db.error or else "unknown"}')"
59 db
.create_table
"IF NOT EXISTS {db_table} (key TEXT PRIMARY KEY, value TEXT)"
69 if db
== null then return null
71 # Prepare SELECT statement
72 var stmt
= db
.select
("* FROM {db_table} WHERE key == {key.to_sql_string}")
77 var serialized
= row
[1].to_s
81 var deserializer
= new JsonDeserializer(serialized
)
82 var deserialized
= deserializer
.deserialize
91 redef fun []=(key
, value
)
95 if db
== null then return
98 var stream
= new StringOStream
99 var serializer
= new JsonSerializer(stream
)
100 serializer
.serialize value
101 var serialized
= stream
.to_s
104 db
.execute
"BEGIN TRANSACTION"
105 db
.insert
"OR REPLACE INTO {db_table} VALUES({key.to_sql_string}, {serialized.to_sql_string})"