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