CLSQLでPostgreSQLを使う

1. PostgreSQLのユーザとDBの作成

# su - postgres
$ createuser -P testuser
$ createdb -O testuser testdb
$ psql -h localhost -U testuser testdb

※接続が正常にできることを確認

2. ライブラリのシンボリックリンク作成

CLSQLで実際にDBに接続するときにlibpq.soがロードできないとエラーが出たのでシンボリックリンクを作成しておく。

# cd /usr/lib
# ln -s libpq.so.5.2 libpq.so

※環境はCentOS6.7です。

3. CLSQLをインストールする

(ql:quickload :clsql)

4. DBに接続

(require :clsql)
(clsql:connect '("localhost" "testdb" "testuser" "password") :database-type :postgresql)

5. DBの接続状態の確認

(clsql:connected-databases)

6. データモデルを定義

(clsql:def-view-class test_tbl ()
  ((key
     :db-kind :key
     :db-constraints :not-null
     :type string
     :initarg :key)
   (data1
     :type string
     :initarg :data1)
   (data2
     :type string
     :initarg :data2)
   (data3
     :type string
     :initarg :data3))
  (:base-table test_tbl))

7. テーブルの作成と削除

テーブル作成

(clsql:create-view-from-class 'test_tbl)

テーブル削除

(clsql:drop-view-from-class 'test_tbl)

8. テーブルの参照

(clsql:query "select * from test_tbl" :field-names nil)

9. レコードの登録

(clsql:insert-records :into 'test_tbl
  :attributes '(key data1 data2 data3)
  :values '("001" "データ1" "データ2" "データ3"))

10. レコードの更新

(clsql:update-records [test_tbl]
  :av-pairs'((data1 "更新データ1"))
  :where [:= [key] "001"])

11. レコードの削除

(clsql:delete-records :from [test_tbl] :where [= [key] "001"])

12. トランザクション

ロールバック

(clsql:start-transaction)
(clsql:delete-records :from [test_tbl] :where [= [key] "001"])
(clsql:rollback)

コミット

(clsql:start-transaction)
(clsql:delete-records :from [test_tbl] :where [= [key] "001"])
(clsql:commit)

13. DB切断

(clsql:disconnect)