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