Keep track of prepared statements instead of using sqlite3_next_stmt
[cl-sqlite.git] / sqlite.lisp
blob4b8952a330e0d50df65311bd1a5ada96f41dad10
1 (defpackage :sqlite
2 (:use :cl :iter)
3 (:export :sqlite-handle
4 :connect
5 :disconnect
6 :sqlite-statement
7 :prepare-statement
8 :finalize-statement
9 :step-statement
10 :reset-statement
11 :statement-column-value
12 :bind-parameter
13 :execute-non-query
14 :execute-to-list
15 :execute-single
16 :execute-one-row-m-v
17 :last-insert-rowid
18 :with-transaction
19 :with-open-database))
21 (in-package :sqlite)
23 ;(declaim (optimize (speed 3) (safety 0) (debug 0)))
25 (defclass sqlite-handle ()
26 ((handle :accessor handle)
27 (database-path :accessor database-path)
28 (cache :accessor cache)
29 (statements :initform nil :accessor sqlite-handle-statements))
30 (:documentation "Class that encapsulates the connection to the database. Use connect and disconnect."))
32 (defmethod initialize-instance :after ((object sqlite-handle) &key (database-path ":memory:") &allow-other-keys)
33 (cffi:with-foreign-object (ppdb 'sqlite-ffi:p-sqlite3)
34 (let ((error-code (sqlite-ffi:sqlite3-open database-path ppdb)))
35 (if (eq error-code :ok)
36 (setf (handle object) (cffi:mem-ref ppdb 'sqlite-ffi:p-sqlite3)
37 (database-path object) database-path)
38 (error "Received error code ~A when trying to open sqlite3 database ~A"
39 error-code database-path))))
40 (setf (cache object) (make-instance 'sqlite.cache:mru-cache :cache-size 16 :destructor #'really-finalize-statement)))
42 (defun connect (database-path)
43 "Connect to the sqlite database at the given DATABASE-PATH. Returns the SQLITE-HANDLE connected to the database. Use DISCONNECT to disconnect."
44 (make-instance 'sqlite-handle :database-path database-path))
46 (defun disconnect (handle)
47 "Disconnects the given HANDLE from the database. All further operations on the handle are invalid."
48 (sqlite.cache:purge-cache (cache handle))
49 (iter (with statements = (copy-list (sqlite-handle-statements handle)))
50 (declare (dynamic-extent statements))
51 (for statement in statements)
52 (really-finalize-statement statement))
53 (let ((error-code (sqlite-ffi:sqlite3-close (handle handle))))
54 (unless (eq error-code :ok)
55 (error "Received error code ~A when trying to close ~A (connected to ~A)" error-code handle (database-path handle)))))
57 (defclass sqlite-statement ()
58 ((db :reader db :initarg :db)
59 (handle :accessor handle)
60 (sql :reader sql :initarg :sql)
61 (columns-count :accessor resultset-columns-count)
62 (columns-names :accessor resultset-columns-names)
63 (parameters-count :accessor parameters-count)
64 (parameters-names :accessor parameters-names))
65 (:documentation "Class that represents the prepared statement."))
67 (defmethod initialize-instance :after ((object sqlite-statement) &key &allow-other-keys)
68 (cffi:with-foreign-object (p-statement 'sqlite-ffi:p-sqlite3-stmt)
69 (cffi:with-foreign-object (p-tail '(:pointer :char))
70 (cffi:with-foreign-string (sql (sql object))
71 (let ((error-code (sqlite-ffi:sqlite3-prepare (handle (db object)) sql -1 p-statement p-tail)))
72 (unless (eq error-code :ok)
73 (error "Error when trying to prepare sqlite statement '~A'. Code: ~A, message: ~A" (sql object) error-code (sqlite-ffi:sqlite3-errmsg (handle (db object)))))
74 (unless (zerop (cffi:mem-ref (cffi:mem-ref p-tail '(:pointer :char)) :uchar))
75 (error "SQL string '~A' contains more than one SQL statements" (sql object)))
76 (setf (handle object) (cffi:mem-ref p-statement 'sqlite-ffi:p-sqlite3-stmt)
77 (resultset-columns-count object) (sqlite-ffi:sqlite3-column-count (handle object))
78 (resultset-columns-names object) (loop
79 for i below (resultset-columns-count object)
80 collect (sqlite-ffi:sqlite3-column-name (handle object) i))
81 (parameters-count object) (sqlite-ffi:sqlite3-bind-parameter-count (handle object))
82 (parameters-names object) (loop
83 for i from 1 to (parameters-count object)
84 collect (sqlite-ffi:sqlite3-bind-parameter-name (handle object) i))))))))
86 (defun prepare-statement (db sql)
87 "Prepare the statement to the DB that will execute the commands that are in SQL.
89 Returns the SQLITE-STATEMENT.
91 SQL must contain exactly one statement.
92 SQL may have some positional (not named) parameters specified with question marks.
94 Example:
96 select name from users where id = ?"
97 (or (sqlite.cache:get-from-cache (cache db) sql)
98 (let ((statement (make-instance 'sqlite-statement :db db :sql sql)))
99 (push statement (sqlite-handle-statements db))
100 statement)))
102 (defun really-finalize-statement (statement)
103 (setf (sqlite-handle-statements (db statement))
104 (delete statement (sqlite-handle-statements (db statement))))
105 (sqlite-ffi:sqlite3-finalize (handle statement)))
107 (defun finalize-statement (statement)
108 "Finalizes the statement and signals that associated resources may be released.
109 Note: does not immediately release resources because statements are cached."
110 (progn
111 (let ((error-code (sqlite-ffi:sqlite3-reset (handle statement))))
112 (unless (eq error-code :ok)
113 (error "When resetting statement ~A (sql: ~A), error ~A (~A)" statement (sql statement) error-code (sqlite-ffi:sqlite3-errmsg (handle (db statement))))))
114 (sqlite.cache:put-to-cache (cache (db statement)) (sql statement) statement)))
116 (defun step-statement (statement)
117 "Steps to the next row of the resultset of STATEMENT.
118 Returns T is successfully advanced to the next row and NIL if there are no more rows."
119 (let ((error-code (sqlite-ffi:sqlite3-step (handle statement))))
120 (case error-code
121 (:done nil)
122 (:row t)
123 (t (error "When stepping statement ~A (sql: ~A), error ~A (~A)" statement (sql statement) error-code (sqlite-ffi:sqlite3-errmsg (handle (db statement))))))))
125 (defun reset-statement (statement)
126 "Resets the STATEMENT and prepare it to be called again."
127 (let ((error-code (sqlite-ffi:sqlite3-reset (handle statement))))
128 (unless (eq error-code :ok)
129 (error "When resetting statment ~A (sql: ~A), error ~A (~A)" statement (sql statement) error-code (sqlite-ffi:sqlite3-errmsg (handle (db statement)))))))
131 (defun statement-column-value (statement column-number)
132 "Returns the COLUMN-NUMBER-th column's value of the current row of the STATEMENT. Columns are numbered from zero.
133 Returns:
134 * NIL for NULL
135 * INTEGER for integers
136 * DOUBLE-FLOAT for floats
137 * STRING for text
138 * (SIMPLE-ARRAY (UNSIGNED-BYTE 8)) for BLOBs"
139 (let ((type (sqlite-ffi:sqlite3-column-type (handle statement) column-number)))
140 (ecase type
141 (:null nil)
142 (:text (sqlite-ffi:sqlite3-column-text (handle statement) column-number))
143 (:integer (sqlite-ffi:sqlite3-column-int64 (handle statement) column-number))
144 (:float (sqlite-ffi:sqlite3-column-double (handle statement) column-number))
145 (:blob (let* ((blob-length (sqlite-ffi:sqlite3-column-bytes (handle statement) column-number))
146 (result (make-array (the fixnum blob-length) :element-type '(unsigned-byte 8)))
147 (blob (sqlite-ffi:sqlite3-column-blob (handle statement) column-number)))
148 (loop
149 for i below blob-length
150 do (setf (aref result i) (cffi:mem-aref blob :unsigned-char i)))
151 result)))))
153 (defun execute-non-query (db sql &rest parameters)
154 "Executes the query SQL to the database DB with given PARAMETERS. Returns nothing.
156 Example:
158 (execute-non-query db \"insert into users (user_name, real_name) values (?, ?)\" \"joe\" \"Joe the User\")
160 See BIND-PARAMETER for the list of supported parameter types."
161 (declare (dynamic-extent parameters))
162 (let ((stmt (prepare-statement db sql)))
163 (iter (for i from 1)
164 (declare (type fixnum i))
165 (for value in parameters)
166 (bind-parameter stmt i value))
167 (step-statement stmt)
168 (finalize-statement stmt)
169 (values)))
171 (defun execute-to-list (db sql &rest parameters)
172 "Executes the query SQL to the database DB with given PARAMETERS. Returns the results as list of lists.
174 Example:
176 (execute-to-list db \"select id, user_name, real_name from users where user_name = ?\" \"joe\")
178 ((1 \"joe\" \"Joe the User\")
179 (2 \"joe\" \"Another Joe\"))
181 See BIND-PARAMETER for the list of supported parameter types."
182 (declare (dynamic-extent parameters))
183 (let ((stmt (prepare-statement db sql))
184 result)
185 (iter (for i from 1)
186 (declare (type fixnum i))
187 (for value in parameters)
188 (bind-parameter stmt i value))
189 (loop (if (step-statement stmt)
190 (push (iter (for i from 0 below (the fixnum (sqlite-ffi:sqlite3-column-count (handle stmt))))
191 (declare (type fixnum i))
192 (collect (statement-column-value stmt i)))
193 result)
194 (return)))
195 (finalize-statement stmt)
196 (nreverse result)))
198 (defun execute-one-row-m-v (db sql &rest parameters)
199 "Executes the query SQL to the database DB with given PARAMETERS. Returns the first row as multiple values.
201 Example:
202 (execute-one-row-m-v db \"select id, user_name, real_name from users where id = ?\" 1)
204 (values 1 \"joe\" \"Joe the User\")
206 See BIND-PARAMETER for the list of supported parameter types."
207 (let ((stmt (prepare-statement db sql)))
208 (unwind-protect
209 (progn
210 (iter (for i from 1)
211 (declare (type fixnum i))
212 (for value in parameters)
213 (bind-parameter stmt i value))
214 (if (step-statement stmt)
215 (return-from execute-one-row-m-v
216 (values-list (iter (for i from 0 below (the fixnum (sqlite-ffi:sqlite3-column-count (handle stmt))))
217 (declare (type fixnum i))
218 (collect (statement-column-value stmt i)))))
219 (return-from execute-one-row-m-v
220 (values-list (loop repeat (the fixnum (sqlite-ffi:sqlite3-column-count (handle stmt))) collect nil)))))
221 (finalize-statement stmt))))
223 (defun statement-parameter-index (statement parameter-name)
224 (sqlite-ffi:sqlite3-bind-parameter-index (handle statement) parameter-name))
226 (defun bind-parameter (statement parameter value)
227 "Sets the PARAMETER-th parameter in STATEMENT to the VALUE.
228 Parameters are numbered from one.
229 Supported types:
230 * NULL. Passed as NULL
231 * INTEGER. Passed as an 64-bit integer
232 * STRING. Passed as a string
233 * FLOAT. Passed as a double
234 * (VECTOR (UNSIGNED-BYTE 8)) and VECTOR that contains integers in range [0,256). Passed as a BLOB"
235 (let ((index (etypecase parameter
236 (integer parameter)
237 (string (statement-parameter-index statement parameter)))))
238 (declare (type fixnum index))
239 (let ((error-code (typecase value
240 (null (sqlite-ffi:sqlite3-bind-null (handle statement) index))
241 (integer (sqlite-ffi:sqlite3-bind-int64 (handle statement) index value))
242 (double-float (sqlite-ffi:sqlite3-bind-double (handle statement) index value))
243 (real (sqlite-ffi:sqlite3-bind-double (handle statement) index (coerce value 'double-float)))
244 (string (sqlite-ffi:sqlite3-bind-text (handle statement) index value -1 (sqlite-ffi:destructor-transient)))
245 ((vector (unsigned-byte 8)) (cffi:with-pointer-to-vector-data (ptr value)
246 (sqlite-ffi:sqlite3-bind-blob (handle statement) index ptr (length value) (sqlite-ffi:destructor-transient))))
247 (vector (cffi:with-foreign-object (array :unsigned-char (length value))
248 (loop
249 for i from 0 below (length value)
250 do (setf (cffi:mem-aref array :unsigned-char i) (aref value i)))
251 (sqlite-ffi:sqlite3-bind-blob (handle statement) index array (length value) (sqlite-ffi:destructor-transient))))
252 (t (error "Do not know how to pass value ~A of type ~A to sqlite" value (type-of value))))))
253 (unless (eq error-code :ok)
254 (error "When binding parameter ~A to value ~A for statment ~A (sql: ~A), error ~A (~A)" parameter value statement (sql statement) error-code (sqlite-ffi:sqlite3-errmsg (handle (db statement))))))))
256 (defun execute-single (db sql &rest parameters)
257 "Executes the query SQL to the database DB with given PARAMETERS. Returns the first column of the first row as single value.
259 Example:
260 (execute-single db \"select user_name from users where id = ?\" 1)
262 \"joe\"
264 See BIND-PARAMETER for the list of supported parameter types."
265 (declare (dynamic-extent parameters))
266 (let ((stmt (prepare-statement db sql)))
267 (unwind-protect
268 (progn
269 (iter (for i from 1)
270 (declare (type fixnum i))
271 (for value in parameters)
272 (bind-parameter stmt i value))
273 (if (step-statement stmt)
274 (statement-column-value stmt 0)
275 nil))
276 (finalize-statement stmt))))
278 (defun last-insert-rowid (db)
279 "Returns the auto-generated ID of the last inserted row on the database connection DB."
280 (sqlite-ffi:sqlite3-last-insert-rowid (handle db)))
282 (defmacro with-transaction (db &body body)
283 "Wraps the BODY inside the transaction."
284 (let ((ok (gensym "TRANSACTION-COMMIT-"))
285 (db-var (gensym "DB-"))
286 (result (gensym "RESULT-")))
287 `(let (,ok
288 (,db-var ,db))
289 (execute-non-query ,db-var "begin transaction")
290 (unwind-protect
291 (progn
292 (let ((,result (progn
293 ,@body)))
294 (setf ,ok t)
295 ,result))
296 (if ,ok
297 (execute-non-query ,db-var "commit transaction")
298 (execute-non-query ,db-var "rollback transaction"))))))
300 (defmacro with-open-database ((db path) &body body)
301 `(let ((,db (connect ,path)))
302 (unwind-protect
303 (progn ,@body)
304 (disconnect ,db))))
306 (defmacro-driver (FOR vars IN-SQLITE-QUERY query-expression ON-DATABASE db &optional WITH-PARAMETERS parameters)
307 (let ((statement (gensym "STATEMENT-"))
308 (kwd (if generate 'generate 'for)))
309 `(progn (with ,statement = (prepare-statement ,db ,query-expression))
310 (finally-protected (when ,statement (finalize-statement ,statement)))
311 ,@(when parameters
312 (list `(initially ,@(iter (for i from 1)
313 (for value in parameters)
314 (collect `(sqlite:bind-parameter ,statement ,i ,value))))))
315 (,kwd ,(if (symbolp vars)
316 `(values ,vars)
317 `(values ,@vars))
318 next (progn (if (step-statement ,statement)
319 (values ,@(iter (for i from 0 below (if (symbolp vars) 1 (length vars)))
320 (collect `(statement-column-value ,statement ,i))))
321 (terminate)))))))
323 (defmacro-driver (FOR vars ON-SQLITE-STATEMENT statement)
324 (let ((statement-var (gensym "STATEMENT-"))
325 (kwd (if generate 'generate 'for)))
326 `(progn (with ,statement-var = ,statement)
327 (,kwd ,(if (symbolp vars)
328 `(values ,vars)
329 `(values ,@vars))
330 next (progn (if (step-statement ,statement-var)
331 (values ,@(iter (for i from 0 below (if (symbolp vars) 1 (length vars)))
332 (collect `(statement-column-value ,statement-var ,i))))
333 (terminate)))))))