pax_global_header00006660000000000000000000000064115622044720014515gustar00rootroot0000000000000052 comment=c738e66d4266ef63a1debc4ef4a1b871a068c112 cl-sqlite-20130615-git/000077500000000000000000000000001156220447200144365ustar00rootroot00000000000000cl-sqlite-20130615-git/cache.lisp000066400000000000000000000051031156220447200163710ustar00rootroot00000000000000(defpackage :sqlite.cache (:use :cl :iter) (:export :mru-cache :get-from-cache :put-to-cache :purge-cache)) (in-package :sqlite.cache) ;(declaim (optimize (speed 3) (safety 0) (debug 0))) (defclass mru-cache () ((objects-table :accessor objects-table :initform (make-hash-table :test 'equal)) (last-access-time-table :accessor last-access-time-table :initform (make-hash-table :test 'equal)) (total-cached :type fixnum :accessor total-cached :initform 0) (cache-size :type fixnum :accessor cache-size :initarg :cache-size :initform 100) (destructor :accessor destructor :initarg :destructor :initform #'identity))) (defun get-from-cache (cache id) (let ((available-objects-stack (gethash id (objects-table cache)))) (when (and available-objects-stack (> (length (the vector available-objects-stack)) 0)) (decf (the fixnum (total-cached cache))) (setf (gethash id (last-access-time-table cache)) (get-internal-run-time)) (vector-pop (the vector available-objects-stack))))) (defun remove-empty-objects-stacks (cache) (let ((table (objects-table cache))) (maphash (lambda (key value) (declare (type vector value)) (when (zerop (length value)) (remhash key table) (remhash key (last-access-time-table cache)))) table))) (defun pop-from-cache (cache) (let ((id (iter (for (id time) in-hashtable (last-access-time-table cache)) (when (not (zerop (length (the vector (gethash id (objects-table cache)))))) (finding id minimizing (the fixnum time)))))) (let ((object (vector-pop (gethash id (objects-table cache))))) (funcall (destructor cache) object))) (remove-empty-objects-stacks cache) (decf (the fixnum (total-cached cache)))) (defun put-to-cache (cache id object) (when (>= (the fixnum (total-cached cache)) (the fixnum (cache-size cache))) (pop-from-cache cache)) (let ((available-objects-stack (or (gethash id (objects-table cache)) (setf (gethash id (objects-table cache)) (make-array 0 :adjustable t :fill-pointer t))))) (vector-push-extend object available-objects-stack) (setf (gethash id (last-access-time-table cache)) (get-internal-run-time)) (incf (the fixnum (total-cached cache))) object)) (defun purge-cache (cache) (iter (for (id items) in-hashtable (objects-table cache)) (declare (ignorable id)) (when items (iter (for item in-vector (the vector items)) (funcall (destructor cache) item)))))cl-sqlite-20130615-git/index.html000066400000000000000000001135011156220447200164340ustar00rootroot00000000000000 SQLITE - Sqlite package

CL-SQLITE


 

Abstract

CL-SQLITE package is an interface to the SQLite embedded relational database engine.

The code is in public domain so you can basically do with it whatever you want.

This documentation describes only the CL-SQLITE package, not the SQLite database itself. SQLite documentation is available at http://sqlite.org/docs.html

CL-SQLITE together with this documentation can be downloaded from http://common-lisp.net/project/cl-sqlite/releases/cl-sqlite-0.2.tar.gz.

CL-SQLITE source code is available in Git repository at git://repo.or.cz/cl-sqlite.git (gitweb) and at git://github.com/dmitryvk/cl-sqlite.git (gitweb).


 

Contents

  1. Installation
  2. Example
  3. Usage
  4. The SQLITE dictionary
    1. bind-parameter
    2. clear-statement-bindings
    3. connect
    4. disconnect
    5. execute-non-query
    6. execute-non-query/named
    7. execute-one-row-m-v
    8. execute-one-row-m-v/named
    9. execute-single
    10. execute-single/named
    11. execute-to-list
    12. execute-to-list/named
    13. finalize-statement
    14. last-insert-rowid
    15. prepare-statement
    16. reset-statement
    17. sqlite-error
    18. sqlite-constraint-error
    19. sqlite-error-code
    20. sqlite-error-db-handle
    21. sqlite-error-message
    22. sqlite-error-sql
    23. sqlite-handle
    24. sqlite-statement
    25. statement-bind-parameter-names
    26. statement-column-names
    27. statement-column-value
    28. step-statement
    29. with-transaction
    30. with-open-database
  5. Support
  6. Changelog
  7. Acknowledgements

 

Installation

The package can be downloaded from http://common-lisp.net/project/cl-sqlite/releases/cl-sqlite-0.2.tar.gz. CL-SQLITE package has the following dependencies:

SQLITE has a system definition for ASDF. Compile and load it in the usual way.

This package does not include SQLite library. It should be installed and loadable with regular FFI mechanisms. On Linux and Mac OS X SQLite is probably already installed (if it's not installed, use native package manager to install it). On Windows PATH environment variable should contain path to sqlite3.dll.


 

Example

(use-package :sqlite)
(use-package :iter)

(defvar *db* (connect ":memory:")) ;;Connect to the sqlite database. :memory: is the temporary in-memory database

(execute-non-query *db* "create table users (id integer primary key, user_name text not null, age integer null)") ;;Create the table

(execute-non-query *db* "insert into users (user_name, age) values (?, ?)" "joe" 18)
(execute-non-query/named *db* "insert into users (user_name, age) values (:user_name, :user_age)" 
                         ":user_name" "dvk" ":user_age" 22)
(execute-non-query *db* "insert into users (user_name, age) values (?, ?)" "qwe" 30)
(execute-non-query *db* "insert into users (user_name, age) values (?, ?)" nil nil) ;; ERROR: constraint failed

(execute-single *db* "select id from users where user_name = ?" "dvk")
;; => 2
(execute-one-row-m-v *db* "select id, user_name, age from users where user_name = ?" "joe")
;; => (values 1 "joe" 18)

(execute-to-list *db* "select id, user_name, age from users")
;; => ((1 "joe" 18) (2 "dvk" 22) (3 "qwe" 30))

;; Use iterate
(iter (for (id user-name age) in-sqlite-query "select id, user_name, age from users where age < ?" on-database *db* with-parameters (25))
      (collect (list id user-name age)))
;; => ((1 "joe" 18) (2 "dvk" 22))

;; Use iterate with named parameters
(iter (for (id user-name age) in-sqlite-query/named "select id, user_name, age from users where age < :age"
      on-database *db* with-parameters (":age" 25))
      (collect (list id user-name age)))
;; => ((1 "joe" 18) (2 "dvk" 22))

;; Use prepared statements directly
(loop
   with statement = (prepare-statement *db* "select id, user_name, age from users where age < ?")
   initially (bind-parameter statement 1 25)
   while (step-statement statement)
   collect (list (statement-column-value statement 0) (statement-column-value statement 1) (statement-column-value statement 2))
   finally (finalize-statement statement))
;; => ((1 "joe" 18) (2 "dvk" 22))

;; Use prepared statements with named parameters
(loop
   with statement = (prepare-statement *db* "select id, user_name, age from users where age < :age")
   initially (bind-parameter statement ":age" 25)
   while (step-statement statement)
   collect (list (statement-column-value statement 0) (statement-column-value statement 1) (statement-column-value statement 2))
   finally (finalize-statement statement))
;; => ((1 "joe" 18) (2 "dvk" 22))

(disconnect *db*) ;;Disconnect

 

Usage

Two functions and a macro are used to manage connections to the database:

To make queries to the database the following functions are provided:

Macro with-transaction is used to execute code within transaction.

Support for ITERATE is provided. Use the following clause:

(for (vars) in-sqlite-query sql on-database db &optional with-parameters (&rest parameters))
This clause will bind vars (a list of variables) to the values of the columns of query.

Additionally, it is possible to use the prepared statements API of sqlite. Create the prepared statement with prepare-statement, bind its parameters with bind-parameter, step through it with step-statement, retrieve the results with statement-column-value, and finally reset it to be used again with reset-statement or dispose of it with finalize-statement.

Positional and named parameters in queries are supported. Positional parameters are denoted by question mark in SQL code, and named parameters are denoted by prefixing color (:), at sign (@) or dollar sign ($) before parameter name.

Following types are supported:


 

The SQLITE dictionary


[Function]
bind-parameter statement parameter value


Sets the parameter in statement to the value.
parameter is an index (parameters are numbered from one) or the name of a parameter.
Supported types:


[Function]
clear-statement-bindings statement


Binds all parameters of the statement to NULL.


[Function]
connect database-path &key busy-timeout => sqlite-handle


Connect to the sqlite database at the given database-path (database-path is a string or a pathname). If database-path equal to ":memory:" is given, a new in-memory database is created. Returns the sqlite-handle connected to the database. Use disconnect to disconnect.
Operations will wait for locked databases for up to busy-timeout milliseconds; if busy-timeout is NIL, then operations on locked databases will fail immediately.


[Function]
disconnect handle


Disconnects the given handle from the database. All further operations on the handle and on prepared statements (including freeing handle or statements) are invalid and will lead to memory corruption.


[Function]
execute-non-query db sql &rest parameters


Executes the query sql to the database db with given parameters. Returns nothing.
Example:
(execute-non-query db "insert into users (user_name, real_name) values (?, ?)" "joe" "Joe the User")
See bind-parameter for the list of supported parameter types.


[Function]
execute-non-query/named db sql &rest parameters


Executes the query sql to the database db with given parameters. Returns nothing. Parameters are alternating names and values.
Example:
(execute-non-query/named db "insert into users (user_name, real_name) values (:user_name, :real_name)"
                         ":user_name" "joe" ":real_name" "Joe the User")
See bind-parameter for the list of supported parameter types.


[Function]
execute-one-row-m-v db sql &rest parameters => (values result*)


Executes the query sql to the database db with given parameters. Returns the first row as multiple values.
Example:
(execute-one-row-m-v db "select id, user_name, real_name from users where id = ?" 1)
=>
(values 1 "joe" "Joe the User")
See bind-parameter for the list of supported parameter types.


[Function]
execute-one-row-m-v/named db sql &rest parameters => (values result*)


Executes the query sql to the database db with given parameters. Returns the first row as multiple values. Parameters are alternating names and values.
Example:
(execute-one-row-m-v/named db "select id, user_name, real_name from users where id = :id" ":id" 1)
=>
(values 1 "joe" "Joe the User")
See bind-parameter for the list of supported parameter types.


[Function]
execute-single db sql &rest parameters => result


Executes the query sql to the database db with given parameters. Returns the first column of the first row as single value.
Example:
(execute-single db "select user_name from users where id = ?" 1)
=>
"joe"
See bind-parameter for the list of supported parameter types.


[Function]
execute-single/named db sql &rest parameters => result


Executes the query sql to the database db with given parameters. Returns the first column of the first row as single value. Parameters are alternating names and values.
Example:
(execute-single/named db "select user_name from users where id = :id" ":id" 1)
=>
"joe"
See bind-parameter for the list of supported parameter types.


[Function]
execute-to-list db sql &rest parameters => results


Executes the query sql to the database db with given parameters. Returns the results as list of lists.
Example:
(execute-to-list db "select id, user_name, real_name from users where user_name = ?" "joe")
=>
((1 "joe" "Joe the User")
 (2 "joe" "Another Joe")) 
See bind-parameter for the list of supported parameter types.


[Function]
execute-to-list/named db sql &rest parameters => results


Executes the query sql to the database db with given parameters. Returns the results as list of lists. Parameters are alternating names and values.
Example:
(execute-to-list db "select id, user_name, real_name from users where user_name = :name" ":name" "joe")
=>
((1 "joe" "Joe the User")
 (2 "joe" "Another Joe")) 
See bind-parameter for the list of supported parameter types.


[Function]
finalize-statement statement


Finalizes the statement and signals that associated resources may be released.
Note: does not immediately release resources because statements are cached.


[Function]
last-insert-rowid db => result


Returns the auto-generated ID of the last inserted row on the database connection db.


[Function]
prepare-statement db sql => sqlite-statement


Prepare the statement to the DB that will execute the commands that are in sql.
Returns the sqlite-statement.
sql must contain exactly one statement.
sql may have some positional (not named) parameters specified with question marks.
Example:
(prepare-statement db "select name from users where id = ?")


[Function]
reset-statement statement


Resets the statement and prepares it to be called again. Note that bind parameter values are not cleared; use clear-statement-bindings for that.


[Condition]
sqlite-error


Error condition used by the library.


[Condition]
sqlite-constraint-error


A subclass of sqlite-error used to distinguish constraint violation errors.


[Accessor]
sqlite-error-code sqlite-error => keyword or null


Returns the SQLite error code represeting the error.


[Accessor]
sqlite-error-db-handle sqlite-error => sqlite-handle or null


Returns the SQLite database connection that caused the error.


[Accessor]
sqlite-error-message sqlite-error => string or null


Returns the SQLite error message corresponding to the error code.


[Accessor]
sqlite-error-sql sqlite-error => string or null


Returns the SQL statement source string that caused the error.


[Standard class]
sqlite-handle


Class that encapsulates the connection to the database.


[Standard class]
sqlite-statement


Class that represents the prepared statement.


[Accessor]
statement-bind-parameter-names statement => list of strings


Returns the names of the bind parameters of the prepared statement. If a parameter does not have a name, the corresponding list item is NIL.


[Accessor]
statement-column-names statement => list of strings


Returns the names of columns in the result set of the prepared statement.


[Function]
statement-column-value statement column-number => result


Returns the column-number-th column's value of the current row of the statement. Columns are numbered from zero.
Returns:


[Function]
step-statement statement => boolean


Steps to the next row of the resultset of statement.
Returns T is successfully advanced to the next row and NIL if there are no more rows.


[Macro]
with-transaction db &body body


Wraps the body inside the transaction. If body evaluates without error, transaction is commited. If evaluation of body is interrupted, transaction is rolled back.


[Macro]
with-open-database (db path &key busy-timeout) &body body


Executes the body with db being bound to the database handle for database located at path. Database is open before the body is run and it is ensured that database is closed after the evaluation of body finished or interrupted.
See CONNECT for meaning of busy-timeout parameter.

 

Support

This package is written by Kalyanov Dmitry.
This project has a cl-sqlite-devel mailing list.

 

Changelog


 

Acknowledgements

This documentation was prepared with DOCUMENTATION-TEMPLATE.

$Header: /usr/local/cvsrep/documentation-template/output.lisp,v 1.14 2008/05/29 08:23:37 edi Exp $ cl-sqlite-20130615-git/sqlite-ffi.lisp000066400000000000000000000106771156220447200174050ustar00rootroot00000000000000(defpackage :sqlite-ffi (:use :cl :cffi) (:export :error-code :p-sqlite3 :sqlite3-open :sqlite3-close :sqlite3-errmsg :sqlite3-busy-timeout :p-sqlite3-stmt :sqlite3-prepare :sqlite3-finalize :sqlite3-step :sqlite3-reset :sqlite3-clear-bindings :sqlite3-column-count :sqlite3-column-type :sqlite3-column-text :sqlite3-column-int64 :sqlite3-column-double :sqlite3-column-bytes :sqlite3-column-blob :sqlite3-column-name :sqlite3-bind-parameter-count :sqlite3-bind-parameter-name :sqlite3-bind-parameter-index :sqlite3-bind-double :sqlite3-bind-int64 :sqlite3-bind-null :sqlite3-bind-text :sqlite3-bind-blob :destructor-transient :destructor-static :sqlite3-last-insert-rowid)) (in-package :sqlite-ffi) (define-foreign-library sqlite3-lib (:darwin (:default "libsqlite3")) (:unix (:or "libsqlite3.so.0" "libsqlite3.so")) (t (:or (:default "libsqlite3") (:default "sqlite3")))) (use-foreign-library sqlite3-lib) (defcenum error-code (:OK 0) (:ERROR 1) (:INTERNAL 2) (:PERM 3) (:ABORT 4) (:BUSY 5) (:LOCKED 6) (:NOMEM 7) (:READONLY 8) (:INTERRUPT 9) (:IOERR 10) (:CORRUPT 11) (:NOTFOUND 12) (:FULL 13) (:CANTOPEN 14) (:PROTOCOL 15) (:EMPTY 16) (:SCHEMA 17) (:TOOBIG 18) (:CONSTRAINT 19) (:MISMATCH 20) (:MISUSE 21) (:NOLFS 22) (:AUTH 23) (:FORMAT 24) (:RANGE 25) (:NOTADB 26) (:ROW 100) (:DONE 101)) (defcstruct sqlite3) (defctype p-sqlite3 (:pointer sqlite3)) (defcfun sqlite3-open error-code (filename :string) (db (:pointer p-sqlite3))) (defcfun sqlite3-close error-code (db p-sqlite3)) (defcfun sqlite3-errmsg :string (db p-sqlite3)) (defcfun sqlite3-busy-timeout :int (db p-sqlite3) (ms :int)) (defcstruct sqlite3-stmt) (defctype p-sqlite3-stmt (:pointer sqlite3-stmt)) (defcfun (sqlite3-prepare "sqlite3_prepare_v2") error-code (db p-sqlite3) (sql :string) (sql-length-bytes :int) (stmt (:pointer p-sqlite3-stmt)) (tail (:pointer (:pointer :char)))) (defcfun sqlite3-finalize error-code (statement p-sqlite3-stmt)) (defcfun sqlite3-step error-code (statement p-sqlite3-stmt)) (defcfun sqlite3-reset error-code (statement p-sqlite3-stmt)) (defcfun sqlite3-clear-bindings error-code (statement p-sqlite3-stmt)) (defcfun sqlite3-column-count :int (statement p-sqlite3-stmt)) (defcenum type-code (:integer 1) (:float 2) (:text 3) (:blob 4) (:null 5)) (defcfun sqlite3-column-type type-code (statement p-sqlite3-stmt) (column-number :int)) (defcfun sqlite3-column-text :string (statement p-sqlite3-stmt) (column-number :int)) (defcfun sqlite3-column-int64 :int64 (statement p-sqlite3-stmt) (column-number :int)) (defcfun sqlite3-column-double :double (statement p-sqlite3-stmt) (column-number :int)) (defcfun sqlite3-column-bytes :int (statement p-sqlite3-stmt) (column-number :int)) (defcfun sqlite3-column-blob :pointer (statement p-sqlite3-stmt) (column-number :int)) (defcfun sqlite3-column-name :string (statement p-sqlite3-stmt) (column-number :int)) (defcfun sqlite3-bind-parameter-count :int (statement p-sqlite3-stmt)) (defcfun sqlite3-bind-parameter-name :string (statement p-sqlite3-stmt) (column-number :int)) (defcfun sqlite3-bind-parameter-index :int (statement p-sqlite3-stmt) (name :string)) (defcfun sqlite3-bind-double error-code (statement p-sqlite3-stmt) (parameter-index :int) (value :double)) (defcfun sqlite3-bind-int64 error-code (statement p-sqlite3-stmt) (parameter-index :int) (value :int64)) (defcfun sqlite3-bind-null error-code (statement p-sqlite3-stmt) (parameter-index :int)) (defcfun sqlite3-bind-text error-code (statement p-sqlite3-stmt) (parameter-index :int) (value :string) (octets-count :int) (destructor :pointer)) (defcfun sqlite3-bind-blob error-code (statement p-sqlite3-stmt) (parameter-index :int) (value :pointer) (bytes-count :int) (destructor :pointer)) (defconstant destructor-transient-address (mod -1 (expt 2 (* 8 (cffi:foreign-type-size :pointer))))) (defun destructor-transient () (cffi:make-pointer destructor-transient-address)) (defun destructor-static () (cffi:make-pointer 0)) (defcfun sqlite3-last-insert-rowid :int64 (db p-sqlite3)) cl-sqlite-20130615-git/sqlite-tests.asd000066400000000000000000000003571156220447200175750ustar00rootroot00000000000000(defsystem :sqlite-tests :name "sqlite-tests" :author "Kalyanov Dmitry " :version "0.1.4" :license "Public Domain" :components ((:file "sqlite-tests")) :depends-on (:fiveam :sqlite :bordeaux-threads))cl-sqlite-20130615-git/sqlite-tests.lisp000066400000000000000000000137101156220447200177720ustar00rootroot00000000000000(defpackage :sqlite-tests (:use :cl :sqlite :5am :iter :bordeaux-threads) (:export :run-all-tests)) (in-package :sqlite-tests) (def-suite sqlite-suite) (defun run-all-tests () (run! 'sqlite-suite)) (in-suite sqlite-suite) (test test-connect (with-open-database (db ":memory:"))) (test test-disconnect-with-statements (finishes (with-open-database (db ":memory:") (prepare-statement db "create table users (id integer primary key, user_name text not null, age integer null)")))) (defmacro with-inserted-data ((db) &body body) `(with-open-database (,db ":memory:") (execute-non-query ,db "create table users (id integer primary key, user_name text not null, age integer null)") (execute-non-query ,db "insert into users (user_name, age) values (?, ?)" "joe" 18) (execute-non-query ,db "insert into users (user_name, age) values (?, ?)" "dvk" 22) (execute-non-query ,db "insert into users (user_name, age) values (?, ?)" "qwe" 30) ,@body)) (test create-table-insert-and-error (with-inserted-data (db) (signals sqlite-constraint-error (execute-non-query db "insert into users (user_name, age) values (?, ?)" nil nil)))) (test create-table-insert-and-error/named (with-inserted-data (db) (signals sqlite-constraint-error (execute-non-query/named db "insert into users (user_name, age) values (:name, :age)" ":name" nil ":age" nil)))) (test test-select-single (with-inserted-data (db) (is (= (execute-single db "select id from users where user_name = ?" "dvk") 2)))) (test test-select-single/named (with-inserted-data (db) (is (= (execute-single/named db "select id from users where user_name = :name" ":name" "dvk") 2)))) (test test-select-m-v (with-inserted-data (db) (is (equalp (multiple-value-list (execute-one-row-m-v db "select id, user_name, age from users where user_name = ?" "joe")) (list 1 "joe" 18))))) (test test-select-m-v/named (with-inserted-data (db) (is (equalp (multiple-value-list (execute-one-row-m-v/named db "select id, user_name, age from users where user_name = :name" ":name" "joe")) (list 1 "joe" 18))))) (test test-select-list (with-inserted-data (db) (is (equalp (execute-to-list db "select id, user_name, age from users") '((1 "joe" 18) (2 "dvk" 22) (3 "qwe" 30)))))) (test test-iterate (with-inserted-data (db) (is (equalp (iter (for (id user-name age) in-sqlite-query "select id, user_name, age from users where age < ?" on-database db with-parameters (25)) (collect (list id user-name age))) '((1 "joe" 18) (2 "dvk" 22)))))) (test test-iterate/named (with-inserted-data (db) (is (equalp (iter (for (id user-name age) in-sqlite-query/named "select id, user_name, age from users where age < :age" on-database db with-parameters (":age" 25)) (collect (list id user-name age))) '((1 "joe" 18) (2 "dvk" 22)))))) (test test-loop-with-prepared-statement (with-inserted-data (db) (is (equalp (loop with statement = (prepare-statement db "select id, user_name, age from users where age < ?") initially (bind-parameter statement 1 25) while (step-statement statement) collect (list (statement-column-value statement 0) (statement-column-value statement 1) (statement-column-value statement 2)) finally (finalize-statement statement)) '((1 "joe" 18) (2 "dvk" 22)))))) (test test-loop-with-prepared-statement/named (with-inserted-data (db) (let ((statement (prepare-statement db "select id, user_name, age from users where age < $x"))) (unwind-protect (progn (is (equalp (statement-column-names statement) '("id" "user_name" "age"))) (is (equalp (statement-bind-parameter-names statement) '("$x"))) (bind-parameter statement "$x" 25) (flet ((fetch-all () (loop while (step-statement statement) collect (list (statement-column-value statement 0) (statement-column-value statement 1) (statement-column-value statement 2)) finally (reset-statement statement)))) (is (equalp (fetch-all) '((1 "joe" 18) (2 "dvk" 22)))) (is (equalp (fetch-all) '((1 "joe" 18) (2 "dvk" 22)))) (clear-statement-bindings statement) (is (equalp (fetch-all) '())))) (finalize-statement statement))))) #+thread-support (defparameter *db-file* "/tmp/test.sqlite") #+thread-support (defun ensure-table () (with-open-database (db *db-file*) (execute-non-query db "CREATE TABLE IF NOT EXISTS FOO (v NUMERIC)"))) #+thread-support (test test-concurrent-inserts (when (probe-file *db-file*) (delete-file *db-file*)) (ensure-table) (unwind-protect (do-zillions 10 10000) (when (probe-file *db-file*) (delete-file *db-file*)))) #+thread-support (defun do-insert (n timeout) "Insert a nonsense value into foo" (ignore-errors (with-open-database (db *db-file* :busy-timeout timeout) (iter (repeat 10000) (execute-non-query db "INSERT INTO FOO (v) VALUES (?)" n))) t)) #+thread-support (defun do-zillions (max-n timeout) (iterate (for n from 1 to max-n) (collect (bt:make-thread (let ((n n)) (lambda () (do-insert n timeout)))) into threads) (finally (iter (for thread in threads) (for all-ok = t) (for thread-result = (bt:join-thread thread)) (unless thread-result (setf all-ok nil)) (finally (is-true all-ok "One of inserter threads encountered a SQLITE_BUSY error")))))) cl-sqlite-20130615-git/sqlite.asd000066400000000000000000000007361156220447200164360ustar00rootroot00000000000000(defsystem :sqlite :name "sqlite" :author "Kalyanov Dmitry " :version "0.1.6" :license "Public Domain" :components ((:file "sqlite-ffi") (:file "cache") (:file "sqlite" :depends-on ("sqlite-ffi" "cache"))) :depends-on (:iterate :cffi) :in-order-to ((test-op (load-op sqlite-tests)))) (defmethod perform ((o asdf:test-op) (c (eql (find-system :sqlite)))) (funcall (intern "RUN-ALL-TESTS" :sqlite-tests))) cl-sqlite-20130615-git/sqlite.lisp000066400000000000000000000563341156220447200166430ustar00rootroot00000000000000(defpackage :sqlite (:use :cl :iter) (:export :sqlite-error :sqlite-constraint-error :sqlite-error-db-handle :sqlite-error-code :sqlite-error-message :sqlite-error-sql :sqlite-handle :connect :set-busy-timeout :disconnect :sqlite-statement :prepare-statement :finalize-statement :step-statement :reset-statement :clear-statement-bindings :statement-column-value :statement-column-names :statement-bind-parameter-names :bind-parameter :execute-non-query :execute-to-list :execute-single :execute-single/named :execute-one-row-m-v/named :execute-to-list/named :execute-non-query/named :execute-one-row-m-v :last-insert-rowid :with-transaction :with-open-database)) (in-package :sqlite) (define-condition sqlite-error (simple-error) ((handle :initform nil :initarg :db-handle :reader sqlite-error-db-handle) (error-code :initform nil :initarg :error-code :reader sqlite-error-code) (error-msg :initform nil :initarg :error-msg :reader sqlite-error-message) (statement :initform nil :initarg :statement :reader sqlite-error-statement) (sql :initform nil :initarg :sql :reader sqlite-error-sql))) (define-condition sqlite-constraint-error (sqlite-error) ()) (defun sqlite-error (error-code message &key statement (db-handle (if statement (db statement))) (sql-text (if statement (sql statement)))) (error (if (eq error-code :constraint) 'sqlite-constraint-error 'sqlite-error) :format-control (if (listp message) (first message) message) :format-arguments (if (listp message) (rest message)) :db-handle db-handle :error-code error-code :error-msg (if (and db-handle error-code) (sqlite-ffi:sqlite3-errmsg (handle db-handle))) :statement statement :sql sql-text)) (defmethod print-object :after ((obj sqlite-error) stream) (unless *print-escape* (when (or (and (sqlite-error-code obj) (not (eq (sqlite-error-code obj) :ok))) (sqlite-error-message obj)) (format stream "~&Code ~A: ~A." (or (sqlite-error-code obj) :OK) (or (sqlite-error-message obj) "no message"))) (when (sqlite-error-db-handle obj) (format stream "~&Database: ~A" (database-path (sqlite-error-db-handle obj)))) (when (sqlite-error-sql obj) (format stream "~&SQL: ~A" (sqlite-error-sql obj))))) ;(declaim (optimize (speed 3) (safety 0) (debug 0))) (defclass sqlite-handle () ((handle :accessor handle) (database-path :accessor database-path) (cache :accessor cache) (statements :initform nil :accessor sqlite-handle-statements)) (:documentation "Class that encapsulates the connection to the database. Use connect and disconnect.")) (defmethod initialize-instance :after ((object sqlite-handle) &key (database-path ":memory:") &allow-other-keys) (cffi:with-foreign-object (ppdb 'sqlite-ffi:p-sqlite3) (let ((error-code (sqlite-ffi:sqlite3-open database-path ppdb))) (if (eq error-code :ok) (setf (handle object) (cffi:mem-ref ppdb 'sqlite-ffi:p-sqlite3) (database-path object) database-path) (sqlite-error error-code (list "Could not open sqlite3 database ~A" database-path))))) (setf (cache object) (make-instance 'sqlite.cache:mru-cache :cache-size 16 :destructor #'really-finalize-statement))) (defun connect (database-path &key busy-timeout) "Connect to the sqlite database at the given DATABASE-PATH. Returns the SQLITE-HANDLE connected to the database. Use DISCONNECT to disconnect. Operations will wait for locked databases for up to BUSY-TIMEOUT milliseconds; if BUSY-TIMEOUT is NIL, then operations on locked databases will fail immediately." (let ((db (make-instance 'sqlite-handle :database-path (etypecase database-path (string database-path) (pathname (namestring database-path)))))) (when busy-timeout (set-busy-timeout db busy-timeout)) db)) (defun set-busy-timeout (db milliseconds) "Sets the maximum amount of time to wait for a locked database." (sqlite-ffi:sqlite3-busy-timeout (handle db) milliseconds)) (defun disconnect (handle) "Disconnects the given HANDLE from the database. All further operations on the handle are invalid." (sqlite.cache:purge-cache (cache handle)) (iter (with statements = (copy-list (sqlite-handle-statements handle))) (declare (dynamic-extent statements)) (for statement in statements) (really-finalize-statement statement)) (let ((error-code (sqlite-ffi:sqlite3-close (handle handle)))) (unless (eq error-code :ok) (sqlite-error error-code "Could not close sqlite3 database." :db-handle handle)) (slot-makunbound handle 'handle))) (defclass sqlite-statement () ((db :reader db :initarg :db) (handle :accessor handle) (sql :reader sql :initarg :sql) (columns-count :accessor resultset-columns-count) (columns-names :accessor resultset-columns-names :reader statement-column-names) (parameters-count :accessor parameters-count) (parameters-names :accessor parameters-names :reader statement-bind-parameter-names)) (:documentation "Class that represents the prepared statement.")) (defmethod initialize-instance :after ((object sqlite-statement) &key &allow-other-keys) (cffi:with-foreign-object (p-statement 'sqlite-ffi:p-sqlite3-stmt) (cffi:with-foreign-object (p-tail '(:pointer :char)) (cffi:with-foreign-string (sql (sql object)) (let ((error-code (sqlite-ffi:sqlite3-prepare (handle (db object)) sql -1 p-statement p-tail))) (unless (eq error-code :ok) (sqlite-error error-code "Could not prepare an sqlite statement." :db-handle (db object) :sql-text (sql object))) (unless (zerop (cffi:mem-ref (cffi:mem-ref p-tail '(:pointer :char)) :uchar)) (sqlite-error nil "SQL string contains more than one SQL statement." :sql-text (sql object))) (setf (handle object) (cffi:mem-ref p-statement 'sqlite-ffi:p-sqlite3-stmt) (resultset-columns-count object) (sqlite-ffi:sqlite3-column-count (handle object)) (resultset-columns-names object) (loop for i below (resultset-columns-count object) collect (sqlite-ffi:sqlite3-column-name (handle object) i)) (parameters-count object) (sqlite-ffi:sqlite3-bind-parameter-count (handle object)) (parameters-names object) (loop for i from 1 to (parameters-count object) collect (sqlite-ffi:sqlite3-bind-parameter-name (handle object) i)))))))) (defun prepare-statement (db sql) "Prepare the statement to the DB that will execute the commands that are in SQL. Returns the SQLITE-STATEMENT. SQL must contain exactly one statement. SQL may have some positional (not named) parameters specified with question marks. Example: select name from users where id = ?" (or (let ((statement (sqlite.cache:get-from-cache (cache db) sql))) (when statement (clear-statement-bindings statement)) statement) (let ((statement (make-instance 'sqlite-statement :db db :sql sql))) (push statement (sqlite-handle-statements db)) statement))) (defun really-finalize-statement (statement) (setf (sqlite-handle-statements (db statement)) (delete statement (sqlite-handle-statements (db statement)))) (sqlite-ffi:sqlite3-finalize (handle statement)) (slot-makunbound statement 'handle)) (defun finalize-statement (statement) "Finalizes the statement and signals that associated resources may be released. Note: does not immediately release resources because statements are cached." (reset-statement statement) (sqlite.cache:put-to-cache (cache (db statement)) (sql statement) statement)) (defun step-statement (statement) "Steps to the next row of the resultset of STATEMENT. Returns T is successfully advanced to the next row and NIL if there are no more rows." (let ((error-code (sqlite-ffi:sqlite3-step (handle statement)))) (case error-code (:done nil) (:row t) (t (sqlite-error error-code "Error while stepping an sqlite statement." :statement statement))))) (defun reset-statement (statement) "Resets the STATEMENT and prepare it to be called again." (let ((error-code (sqlite-ffi:sqlite3-reset (handle statement)))) (unless (eq error-code :ok) (sqlite-error error-code "Error while resetting an sqlite statement." :statement statement)))) (defun clear-statement-bindings (statement) "Sets all binding values to NULL." (let ((error-code (sqlite-ffi:sqlite3-clear-bindings (handle statement)))) (unless (eq error-code :ok) (sqlite-error error-code "Error while clearing bindings of an sqlite statement." :statement statement)))) (defun statement-column-value (statement column-number) "Returns the COLUMN-NUMBER-th column's value of the current row of the STATEMENT. Columns are numbered from zero. Returns: * NIL for NULL * INTEGER for integers * DOUBLE-FLOAT for floats * STRING for text * (SIMPLE-ARRAY (UNSIGNED-BYTE 8)) for BLOBs" (let ((type (sqlite-ffi:sqlite3-column-type (handle statement) column-number))) (ecase type (:null nil) (:text (sqlite-ffi:sqlite3-column-text (handle statement) column-number)) (:integer (sqlite-ffi:sqlite3-column-int64 (handle statement) column-number)) (:float (sqlite-ffi:sqlite3-column-double (handle statement) column-number)) (:blob (let* ((blob-length (sqlite-ffi:sqlite3-column-bytes (handle statement) column-number)) (result (make-array (the fixnum blob-length) :element-type '(unsigned-byte 8))) (blob (sqlite-ffi:sqlite3-column-blob (handle statement) column-number))) (loop for i below blob-length do (setf (aref result i) (cffi:mem-aref blob :unsigned-char i))) result))))) (defmacro with-prepared-statement (statement-var (db sql parameters-var) &body body) (let ((i-var (gensym "I")) (value-var (gensym "VALUE"))) `(let ((,statement-var (prepare-statement ,db ,sql))) (unwind-protect (progn (iter (for ,i-var from 1) (declare (type fixnum ,i-var)) (for ,value-var in ,parameters-var) (bind-parameter ,statement-var ,i-var ,value-var)) ,@body) (finalize-statement ,statement-var))))) (defmacro with-prepared-statement/named (statement-var (db sql parameters-var) &body body) (let ((name-var (gensym "NAME")) (value-var (gensym "VALUE"))) `(let ((,statement-var (prepare-statement ,db ,sql))) (unwind-protect (progn (iter (for (,name-var ,value-var) on ,parameters-var by #'cddr) (bind-parameter ,statement-var (string ,name-var) ,value-var)) ,@body) (finalize-statement ,statement-var))))) (defun execute-non-query (db sql &rest parameters) "Executes the query SQL to the database DB with given PARAMETERS. Returns nothing. Example: \(execute-non-query db \"insert into users (user_name, real_name) values (?, ?)\" \"joe\" \"Joe the User\") See BIND-PARAMETER for the list of supported parameter types." (declare (dynamic-extent parameters)) (with-prepared-statement statement (db sql parameters) (step-statement statement))) (defun execute-non-query/named (db sql &rest parameters) "Executes the query SQL to the database DB with given PARAMETERS. Returns nothing. PARAMETERS is a list of alternating parameter names and values. Example: \(execute-non-query db \"insert into users (user_name, real_name) values (:name, :real_name)\" \":name\" \"joe\" \":real_name\" \"Joe the User\") See BIND-PARAMETER for the list of supported parameter types." (declare (dynamic-extent parameters)) (with-prepared-statement/named statement (db sql parameters) (step-statement statement))) (defun execute-to-list (db sql &rest parameters) "Executes the query SQL to the database DB with given PARAMETERS. Returns the results as list of lists. Example: \(execute-to-list db \"select id, user_name, real_name from users where user_name = ?\" \"joe\") => \((1 \"joe\" \"Joe the User\") (2 \"joe\" \"Another Joe\")) See BIND-PARAMETER for the list of supported parameter types." (declare (dynamic-extent parameters)) (with-prepared-statement stmt (db sql parameters) (let (result) (loop (if (step-statement stmt) (push (iter (for i from 0 below (the fixnum (sqlite-ffi:sqlite3-column-count (handle stmt)))) (declare (type fixnum i)) (collect (statement-column-value stmt i))) result) (return))) (nreverse result)))) (defun execute-to-list/named (db sql &rest parameters) "Executes the query SQL to the database DB with given PARAMETERS. Returns the results as list of lists. PARAMETERS is a list of alternating parameters names and values. Example: \(execute-to-list db \"select id, user_name, real_name from users where user_name = :user_name\" \":user_name\" \"joe\") => \((1 \"joe\" \"Joe the User\") (2 \"joe\" \"Another Joe\")) See BIND-PARAMETER for the list of supported parameter types." (declare (dynamic-extent parameters)) (with-prepared-statement/named stmt (db sql parameters) (let (result) (loop (if (step-statement stmt) (push (iter (for i from 0 below (the fixnum (sqlite-ffi:sqlite3-column-count (handle stmt)))) (declare (type fixnum i)) (collect (statement-column-value stmt i))) result) (return))) (nreverse result)))) (defun execute-one-row-m-v (db sql &rest parameters) "Executes the query SQL to the database DB with given PARAMETERS. Returns the first row as multiple values. Example: \(execute-one-row-m-v db \"select id, user_name, real_name from users where id = ?\" 1) => \(values 1 \"joe\" \"Joe the User\") See BIND-PARAMETER for the list of supported parameter types." (with-prepared-statement stmt (db sql parameters) (if (step-statement stmt) (return-from execute-one-row-m-v (values-list (iter (for i from 0 below (the fixnum (sqlite-ffi:sqlite3-column-count (handle stmt)))) (declare (type fixnum i)) (collect (statement-column-value stmt i))))) (return-from execute-one-row-m-v (values-list (loop repeat (the fixnum (sqlite-ffi:sqlite3-column-count (handle stmt))) collect nil)))))) (defun execute-one-row-m-v/named (db sql &rest parameters) "Executes the query SQL to the database DB with given PARAMETERS. Returns the first row as multiple values. PARAMETERS is a list of alternating parameters names and values. Example: \(execute-one-row-m-v db \"select id, user_name, real_name from users where id = :id\" \":id\" 1) => \(values 1 \"joe\" \"Joe the User\") See BIND-PARAMETER for the list of supported parameter types." (with-prepared-statement/named stmt (db sql parameters) (if (step-statement stmt) (return-from execute-one-row-m-v/named (values-list (iter (for i from 0 below (the fixnum (sqlite-ffi:sqlite3-column-count (handle stmt)))) (declare (type fixnum i)) (collect (statement-column-value stmt i))))) (return-from execute-one-row-m-v/named (values-list (loop repeat (the fixnum (sqlite-ffi:sqlite3-column-count (handle stmt))) collect nil)))))) (defun statement-parameter-index (statement parameter-name) (sqlite-ffi:sqlite3-bind-parameter-index (handle statement) parameter-name)) (defun bind-parameter (statement parameter value) "Sets the PARAMETER-th parameter in STATEMENT to the VALUE. PARAMETER may be parameter index (starting from 1) or parameters name. Supported types: * NULL. Passed as NULL * INTEGER. Passed as an 64-bit integer * STRING. Passed as a string * FLOAT. Passed as a double * (VECTOR (UNSIGNED-BYTE 8)) and VECTOR that contains integers in range [0,256). Passed as a BLOB" (let ((index (etypecase parameter (integer parameter) (string (statement-parameter-index statement parameter))))) (declare (type fixnum index)) (let ((error-code (typecase value (null (sqlite-ffi:sqlite3-bind-null (handle statement) index)) (integer (sqlite-ffi:sqlite3-bind-int64 (handle statement) index value)) (double-float (sqlite-ffi:sqlite3-bind-double (handle statement) index value)) (real (sqlite-ffi:sqlite3-bind-double (handle statement) index (coerce value 'double-float))) (string (sqlite-ffi:sqlite3-bind-text (handle statement) index value -1 (sqlite-ffi:destructor-transient))) ((vector (unsigned-byte 8)) (cffi:with-pointer-to-vector-data (ptr value) (sqlite-ffi:sqlite3-bind-blob (handle statement) index ptr (length value) (sqlite-ffi:destructor-transient)))) (vector (cffi:with-foreign-object (array :unsigned-char (length value)) (loop for i from 0 below (length value) do (setf (cffi:mem-aref array :unsigned-char i) (aref value i))) (sqlite-ffi:sqlite3-bind-blob (handle statement) index array (length value) (sqlite-ffi:destructor-transient)))) (t (sqlite-error nil (list "Do not know how to pass value ~A of type ~A to sqlite." value (type-of value)) :statement statement))))) (unless (eq error-code :ok) (sqlite-error error-code (list "Error when binding parameter ~A to value ~A." parameter value) :statement statement))))) (defun execute-single (db sql &rest parameters) "Executes the query SQL to the database DB with given PARAMETERS. Returns the first column of the first row as single value. Example: \(execute-single db \"select user_name from users where id = ?\" 1) => \"joe\" See BIND-PARAMETER for the list of supported parameter types." (declare (dynamic-extent parameters)) (with-prepared-statement stmt (db sql parameters) (if (step-statement stmt) (statement-column-value stmt 0) nil))) (defun execute-single/named (db sql &rest parameters) "Executes the query SQL to the database DB with given PARAMETERS. Returns the first column of the first row as single value. PARAMETERS is a list of alternating parameters names and values. Example: \(execute-single db \"select user_name from users where id = :id\" \":id\" 1) => \"joe\" See BIND-PARAMETER for the list of supported parameter types." (declare (dynamic-extent parameters)) (with-prepared-statement/named stmt (db sql parameters) (if (step-statement stmt) (statement-column-value stmt 0) nil))) (defun last-insert-rowid (db) "Returns the auto-generated ID of the last inserted row on the database connection DB." (sqlite-ffi:sqlite3-last-insert-rowid (handle db))) (defmacro with-transaction (db &body body) "Wraps the BODY inside the transaction." (let ((ok (gensym "TRANSACTION-COMMIT-")) (db-var (gensym "DB-"))) `(let (,ok (,db-var ,db)) (execute-non-query ,db-var "begin transaction") (unwind-protect (multiple-value-prog1 (progn ,@body) (setf ,ok t)) (if ,ok (execute-non-query ,db-var "commit transaction") (execute-non-query ,db-var "rollback transaction")))))) (defmacro with-open-database ((db path &key busy-timeout) &body body) `(let ((,db (connect ,path :busy-timeout ,busy-timeout))) (unwind-protect (progn ,@body) (disconnect ,db)))) (defmacro-driver (FOR vars IN-SQLITE-QUERY query-expression ON-DATABASE db &optional WITH-PARAMETERS parameters) (let ((statement (gensym "STATEMENT-")) (kwd (if generate 'generate 'for))) `(progn (with ,statement = (prepare-statement ,db ,query-expression)) (finally-protected (when ,statement (finalize-statement ,statement))) ,@(when parameters (list `(initially ,@(iter (for i from 1) (for value in parameters) (collect `(sqlite:bind-parameter ,statement ,i ,value)))))) (,kwd ,(if (symbolp vars) `(values ,vars) `(values ,@vars)) next (progn (if (step-statement ,statement) (values ,@(iter (for i from 0 below (if (symbolp vars) 1 (length vars))) (collect `(statement-column-value ,statement ,i)))) (terminate))))))) (defmacro-driver (FOR vars IN-SQLITE-QUERY/NAMED query-expression ON-DATABASE db &optional WITH-PARAMETERS parameters) (let ((statement (gensym "STATEMENT-")) (kwd (if generate 'generate 'for))) `(progn (with ,statement = (prepare-statement ,db ,query-expression)) (finally-protected (when ,statement (finalize-statement ,statement))) ,@(when parameters (list `(initially ,@(iter (for (name value) on parameters by #'cddr) (collect `(sqlite:bind-parameter ,statement ,name ,value)))))) (,kwd ,(if (symbolp vars) `(values ,vars) `(values ,@vars)) next (progn (if (step-statement ,statement) (values ,@(iter (for i from 0 below (if (symbolp vars) 1 (length vars))) (collect `(statement-column-value ,statement ,i)))) (terminate))))))) (defmacro-driver (FOR vars ON-SQLITE-STATEMENT statement) (let ((statement-var (gensym "STATEMENT-")) (kwd (if generate 'generate 'for))) `(progn (with ,statement-var = ,statement) (,kwd ,(if (symbolp vars) `(values ,vars) `(values ,@vars)) next (progn (if (step-statement ,statement-var) (values ,@(iter (for i from 0 below (if (symbolp vars) 1 (length vars))) (collect `(statement-column-value ,statement-var ,i)))) (terminate)))))))cl-sqlite-20130615-git/style.css000066400000000000000000000016551156220447200163170ustar00rootroot00000000000000 .header { font-size: medium; background-color:#336699; color:#ffffff; border-style:solid; border-width: 5px; border-color:#002244; padding: 1mm 1mm 1mm 5mm; } .footer { font-size: small; font-style: italic; text-align: right; background-color:#336699; color:#ffffff; border-style:solid; border-width: 2px; border-color:#002244; padding: 1mm 1mm 1mm 1mm; } .footer a:link { font-weight:bold; color:#ffffff; text-decoration:underline; } .footer a:visited { font-weight:bold; color:#ffffff; text-decoration:underline; } .footer a:hover { font-weight:bold; color:#002244; text-decoration:underline; } .check {font-size: x-small; text-align:right;} .check a:link { font-weight:bold; color:#a0a0ff; text-decoration:underline; } .check a:visited { font-weight:bold; color:#a0a0ff; text-decoration:underline; } .check a:hover { font-weight:bold; color:#000000; text-decoration:underline; }