app: report errors in DataStore and fix a warning
[nit.git] / lib / linux / data_store.nit
1 # This file is part of NIT ( http://www.nitlanguage.org ).
2 #
3 # Copyright 2014 Alexis Laferrière <alexis.laf@xymus.net>
4 #
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
8 #
9 # http://www.apache.org/licenses/LICENSE-2.0
10 #
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.
16
17 # `app::data_store` implementation on GNU/Linux
18 module data_store
19
20 import app::data_store
21 private import xdg_basedir
22 import sqlite3
23 private import json
24
25 redef class DataStore
26
27 # File path of the Sqlite3 DB file
28 fun db_file: String do return "data_store.db"
29
30 # Sqlite3 table used
31 fun db_table: String do return "data_store"
32
33 private var db_cache: nullable Sqlite3DB = null
34
35 # Database to use to implement the `DataStore`
36 fun db: nullable Sqlite3DB
37 do
38 var db = db_cache
39 if db != null then return db
40
41 # Find DB path
42 var config_home = xdg_basedir.config_home.to_s
43 var config_dir = config_home.join_path(sys.program_name.basename)
44 if not config_dir.file_exists then config_dir.mkdir
45 var db_path = config_dir.join_path(db_file)
46
47 # Open DB connection
48 db = new Sqlite3DB.open(db_path)
49 if not db.is_open then
50 print_error "Data store unavaible, cannot load/save data. (at '{db_path}' with '{db.error or else "unknown"}')"
51 return null
52 end
53
54 # Create DB table
55 db.create_table "IF NOT EXISTS {db_table} (key TEXT PRIMARY KEY, value TEXT)"
56
57 db_cache = db
58 return db
59 end
60
61 redef fun [](key)
62 do
63 # Get DB
64 var db = self.db
65 if db == null then return null
66
67 # Prepare SELECT statement
68 var stmt = db.select("* FROM {db_table} WHERE key == {key.to_sql_string}")
69 if stmt == null then return null
70
71 # Execute statment
72 for row in stmt do
73 # Get from statement
74 var serialized = row[1].to_s
75 stmt.close
76
77 # Deserialize
78 var deserializer = new JsonDeserializer(serialized)
79 var deserialized = deserializer.deserialize
80
81 var errors = deserializer.errors
82 if errors.not_empty then
83 # An update may have broken the versioning compatibility
84 print_error "{class_name} error at deserialization: {errors.join(", ")}"
85 return null # Let's be safe
86 end
87
88 return deserialized
89 end
90
91 stmt.close
92 return null
93 end
94
95 redef fun []=(key, value)
96 do
97 # Get DB
98 var db = self.db
99 if db == null then return
100
101 # Serialize
102 var stream = new StringWriter
103 var serializer = new JsonSerializer(stream)
104 serializer.serialize value
105 var serialized = stream.to_s
106
107 # Save in DB
108 db.execute "BEGIN TRANSACTION"
109 db.insert "OR REPLACE INTO {db_table} VALUES({key.to_sql_string}, {serialized.to_sql_string})"
110 db.execute "COMMIT"
111 end
112 end