]> gitweb.factorcode.org Git - factor.git/blob - basis/db/sqlite/sqlite.factor
2aea3e1fb1281e28f9ec8a9e817f81ea5fd9e3f0
[factor.git] / basis / db / sqlite / sqlite.factor
1 ! Copyright (C) 2005, 2008 Chris Double, Doug Coleman.
2 ! See http://factorcode.org/license.txt for BSD license.
3 USING: accessors classes.tuple combinators db db.private db.queries
4 db.sqlite.errors db.sqlite.ffi db.sqlite.lib db.tuples
5 db.tuples.private db.types destructors interpolate kernel math
6 math.parser namespaces nmake random sequences sequences.deep ;
7 IN: db.sqlite
8
9 TUPLE: sqlite-db path ;
10
11 : <sqlite-db> ( path -- sqlite-db )
12     sqlite-db new
13         swap >>path ;
14
15 <PRIVATE
16
17 TUPLE: sqlite-db-connection < db-connection ;
18
19 : <sqlite-db-connection> ( handle -- db-connection )
20     sqlite-db-connection new-db-connection
21         swap >>handle ;
22
23 PRIVATE>
24
25 M: sqlite-db db-open
26     path>> sqlite-open <sqlite-db-connection> ;
27
28 M: sqlite-db-connection db-close sqlite-close ;
29
30 TUPLE: sqlite-statement < statement ;
31
32 TUPLE: sqlite-result-set < result-set has-more? ;
33
34 M: sqlite-db-connection <simple-statement>
35     <prepared-statement> ;
36
37 M: sqlite-db-connection <prepared-statement>
38     sqlite-statement new-statement ;
39
40 : sqlite-maybe-prepare ( statement -- statement )
41     dup handle>> [
42         db-connection get handle>> over sql>> sqlite-prepare
43         >>handle
44     ] unless ;
45
46 M: sqlite-statement dispose
47     handle>>
48     [ [ sqlite3_reset drop ] keep sqlite-finalize ] when* ;
49
50 M: sqlite-result-set dispose
51     f >>handle drop ;
52
53 : reset-bindings ( statement -- )
54     sqlite-maybe-prepare
55     handle>> [ sqlite3_reset drop ] [ sqlite3_clear_bindings drop ] bi ;
56
57 M: sqlite-statement low-level-bind
58     [ handle>> ] [ bind-params>> ] bi
59     [ [ key>> ] [ value>> ] [ type>> ] tri sqlite-bind-type ] with each ;
60
61 M: sqlite-statement bind-statement*
62     sqlite-maybe-prepare
63     dup bound?>> [ dup reset-bindings ] when
64     low-level-bind ;
65
66 GENERIC: sqlite-bind-conversion ( tuple obj -- array )
67
68 TUPLE: sqlite-low-level-binding < low-level-binding key type ;
69 : <sqlite-low-level-binding> ( key value type -- obj )
70     sqlite-low-level-binding new
71         swap >>type
72         swap >>value
73         swap >>key ;
74
75 M: sql-spec sqlite-bind-conversion
76     [ column-name>> ":" prepend ]
77     [ slot-name>> rot get-slot-named ]
78     [ type>> ] tri <sqlite-low-level-binding> ;
79
80 M: literal-bind sqlite-bind-conversion
81     nip [ key>> ] [ value>> ] [ type>> ] tri
82     <sqlite-low-level-binding> ;
83
84 M:: generator-bind sqlite-bind-conversion ( tuple generate-bind -- array )
85     generate-bind generator-singleton>> eval-generator :> obj
86     generate-bind slot-name>> :> name
87     obj name tuple set-slot-named
88     generate-bind key>> obj generate-bind type>> <sqlite-low-level-binding> ;
89
90 M: sqlite-statement bind-tuple
91     [
92         in-params>> [ sqlite-bind-conversion ] with map
93     ] keep bind-statement ;
94
95 ERROR: sqlite-last-id-fail ;
96
97 : last-insert-id ( -- id )
98     db-connection get handle>> sqlite3_last_insert_rowid
99     dup zero? [ sqlite-last-id-fail ] when ;
100
101 M: sqlite-db-connection insert-tuple-set-key
102     execute-statement last-insert-id swap set-primary-key ;
103
104 M: sqlite-result-set #columns
105     handle>> sqlite-#columns ;
106
107 M: sqlite-result-set row-column
108     [ handle>> ] [ sqlite-column ] bi* ;
109
110 M: sqlite-result-set row-column-typed
111     dup pick out-params>> nth type>>
112     [ handle>> ] 2dip sqlite-column-typed ;
113
114 M: sqlite-result-set advance-row
115     dup handle>> sqlite-next >>has-more? drop ;
116
117 M: sqlite-result-set more-rows?
118     has-more?>> ;
119
120 M: sqlite-statement query-results
121     sqlite-maybe-prepare
122     dup handle>> sqlite-result-set new-result-set
123     dup advance-row ;
124
125 M: sqlite-db-connection <insert-db-assigned-statement>
126     [
127         "insert into " 0% 0%
128         "(" 0%
129         remove-db-assigned-id
130         dup [ ", " 0% ] [ column-name>> 0% ] interleave
131         ") values(" 0%
132         [ ", " 0% ] [
133             dup type>> +random-id+ = [
134                 [ slot-name>> ]
135                 [
136                     column-name>> ":" prepend dup 0%
137                     random-id-generator
138                 ] [ type>> ] tri <generator-bind> 1,
139             ] [
140                 bind%
141             ] if
142         ] interleave
143         ");" 0%
144     ] query-make ;
145
146 M: sqlite-db-connection <insert-user-assigned-statement>
147     <insert-db-assigned-statement> ;
148
149 M: sqlite-db-connection bind#
150     [
151         [ column-name>> ":" next-sql-counter surround dup 0% ]
152         [ type>> ] bi
153     ] dip <literal-bind> 1, ;
154
155 M: sqlite-db-connection bind%
156     dup 1, column-name>> ":" prepend 0% ;
157
158 M: sqlite-db-connection persistent-table
159     H{
160         { +db-assigned-id+ { "integer" "integer" f } }
161         { +user-assigned-id+ { f f f } }
162         { +random-id+ { "integer" "integer" f } }
163         { +foreign-id+ { "integer" "integer" "references" } }
164         { +primary-key+ { f f "primary key" } }
165
166         { +on-update+ { f f "on update" } }
167         { +on-delete+ { f f "on delete" } }
168         { +restrict+ { f f "restrict" } }
169         { +cascade+ { f f "cascade" } }
170         { +set-null+ { f f "set null" } }
171         { +set-default+ { f f "set default" } }
172
173         { BOOLEAN { "boolean" "boolean" f } }
174         { INTEGER { "integer" "integer" f } }
175         { BIG-INTEGER { "bigint" "bigint" f } }
176         { SIGNED-BIG-INTEGER { "bigint" "bigint" f } }
177         { UNSIGNED-BIG-INTEGER { "bigint" "bigint" f } }
178         { TEXT { "text" "text" f } }
179         { VARCHAR { "text" "text" f } }
180         { DATE { "date" "date" f } }
181         { TIME { "time" "time" f } }
182         { DATETIME { "datetime" "datetime" f } }
183         { TIMESTAMP { "timestamp" "timestamp" f } }
184         { DOUBLE { "real" "real" f } }
185         { BLOB { "blob" "blob" f } }
186         { FACTOR-BLOB { "blob" "blob" f } }
187         { URL { "text" "text" f } }
188         { +autoincrement+ { f f "autoincrement" } }
189         { +unique+ { f f "unique" } }
190         { +default+ { f f "default" } }
191         { +null+ { f f "null" } }
192         { +not-null+ { f f "not null" } }
193         { system-random-generator { f f f } }
194         { secure-random-generator { f f f } }
195         { random-generator { f f f } }
196     } ;
197
198 : insert-trigger ( -- string )
199     "
200         CREATE TRIGGER fki_${table-name}_${table-id}_${foreign-table-name}_${foreign-table-id}_id
201         BEFORE INSERT ON ${table-name}
202         FOR EACH ROW BEGIN
203             SELECT RAISE(ROLLBACK, 'insert on table \"${table-name}\" violates foreign key constraint \"fki_${table-name}_${table-id}_${foreign-table-name}_${foreign-table-id}_id\"')
204             WHERE  (SELECT ${foreign-table-id} FROM ${foreign-table-name} WHERE ${foreign-table-id} = NEW.${table-id}) IS NULL;
205         END;
206     " interpolate>string ;
207
208 : insert-trigger-not-null ( -- string )
209     "
210         CREATE TRIGGER fki_${table-name}_${table-id}_${foreign-table-name}_${foreign-table-id}_id
211         BEFORE INSERT ON ${table-name}
212         FOR EACH ROW BEGIN
213             SELECT RAISE(ROLLBACK, 'insert on table \"${table-name}\" violates foreign key constraint \"fki_${table-name}_${table-id}_${foreign-table-name}_${foreign-table-id}_id\"')
214             WHERE NEW.${table-id} IS NOT NULL
215                 AND (SELECT ${foreign-table-id} FROM ${foreign-table-name} WHERE ${foreign-table-id} = NEW.${table-id}) IS NULL;
216         END;
217     " interpolate>string ;
218
219 : update-trigger ( -- string )
220     "
221         CREATE TRIGGER fku_${table-name}_${table-id}_${foreign-table-name}_${foreign-table-id}_id
222         BEFORE UPDATE ON ${table-name}
223         FOR EACH ROW BEGIN
224             SELECT RAISE(ROLLBACK, 'update on table \"${table-name}\" violates foreign key constraint \"fku_${table-name}_${table-id}_${foreign-table-name}_${foreign-table-id}_id\"')
225             WHERE (SELECT ${foreign-table-id} FROM ${foreign-table-name} WHERE ${foreign-table-id} = NEW.${table-id}) IS NULL;
226         END;
227     " interpolate>string ;
228
229 : update-trigger-not-null ( -- string )
230     "
231         CREATE TRIGGER fku_${table-name}_${table-id}_${foreign-table-name}_${foreign-table-id}_id
232         BEFORE UPDATE ON ${table-name}
233         FOR EACH ROW BEGIN
234             SELECT RAISE(ROLLBACK, 'update on table \"${table-name}\" violates foreign key constraint \"fku_${table-name}_${table-id}_${foreign-table-name}_${foreign-table-id}_id\"')
235             WHERE NEW.${table-id} IS NOT NULL
236                 AND (SELECT ${foreign-table-id} FROM ${foreign-table-name} WHERE ${foreign-table-id} = NEW.${table-id}) IS NULL;
237         END;
238     " interpolate>string ;
239
240 : delete-trigger-restrict ( -- string )
241     "
242         CREATE TRIGGER fkd_${table-name}_${table-id}_${foreign-table-name}_${foreign-table-id}_id
243         BEFORE DELETE ON ${foreign-table-name}
244         FOR EACH ROW BEGIN
245             SELECT RAISE(ROLLBACK, 'delete on table \"${foreign-table-name}\" violates foreign key constraint \"fkd_${table-name}_${table-id}_${foreign-table-name}_${foreign-table-id}_id\"')
246             WHERE (SELECT ${table-id} FROM ${table-name} WHERE ${table-id} = OLD.${foreign-table-id}) IS NOT NULL;
247         END;
248     " interpolate>string ;
249
250 : delete-trigger-cascade ( -- string )
251     "
252         CREATE TRIGGER fkd_${table-name}_${table-id}_${foreign-table-name}_${foreign-table-id}_id
253         BEFORE DELETE ON ${foreign-table-name}
254         FOR EACH ROW BEGIN
255             DELETE from ${table-name} WHERE ${table-id} = OLD.${foreign-table-id};
256         END;
257     " interpolate>string ;
258
259 : can-be-null? ( -- ? )
260     "sql-spec" get modifiers>> [ +not-null+ = ] none? ;
261
262 : delete-cascade? ( -- ? )
263     "sql-spec" get modifiers>> { +on-delete+ +cascade+ } subseq-index? ;
264
265 : sqlite-trigger, ( string -- )
266     { } { } <simple-statement> 3, ;
267
268 : create-sqlite-triggers ( -- )
269     can-be-null? [
270         insert-trigger sqlite-trigger,
271         update-trigger sqlite-trigger,
272     ] [
273         insert-trigger-not-null sqlite-trigger,
274         update-trigger-not-null sqlite-trigger,
275     ] if
276     delete-cascade? [
277         delete-trigger-cascade sqlite-trigger,
278     ] [
279         delete-trigger-restrict sqlite-trigger,
280     ] if ;
281
282 : create-db-triggers ( sql-specs -- )
283     [ modifiers>> [ +foreign-id+ = ] deep-any? ] filter
284     [
285         [ "sql-spec" set ]
286         [ column-name>> "table-id" set ]
287         [ ] tri
288         modifiers>> [ [ +foreign-id+ = ] deep-any? ] filter
289         [
290             [ second db-table-name "foreign-table-name" set ]
291             [ third "foreign-table-id" set ] bi
292             create-sqlite-triggers
293         ] each
294     ] each ;
295
296 : sqlite-create-table ( sql-specs class-name -- )
297     [
298         "create table " 0% 0%
299         "(" 0% [ ", " 0% ] [
300             dup "sql-spec" set
301             dup column-name>> [ "table-id" set ] [ 0% ] bi
302             " " 0%
303             dup type>> lookup-create-type 0%
304             modifiers 0%
305         ] interleave
306     ] [
307         drop
308         find-primary-key [
309             ", " 0%
310             "primary key(" 0%
311             [ "," 0% ] [ column-name>> 0% ] interleave
312             ")" 0%
313         ] unless-empty
314         ");" 0%
315     ] 2bi ;
316
317 M: sqlite-db-connection create-sql-statement
318     [
319         [ sqlite-create-table ]
320         [ drop create-db-triggers ] 2bi
321     ] query-make ;
322
323 M: sqlite-db-connection drop-sql-statement
324     [ nip "drop table " 0% 0% ";" 0% ] query-make ;
325
326 M: sqlite-db-connection compound
327     over {
328         { "default" [ first number>string " " glue ] }
329         { "references" [ >reference-string ] }
330         [ 2drop ]
331     } case ;
332
333 M: sqlite-db-connection parse-db-error
334     dup sqlite-error? [
335         dup n>> {
336             { 1 [ string>> parse-sqlite-sql-error ] }
337             [ drop ]
338         } case
339     ] when ;