Remove CVS $Id$ keyword
[clsql.git] / db-db2 / db2-sql.lisp
1 ;;;; -*- Mode: LISP; Syntax: ANSI-Common-Lisp; Base: 10 -*-
2 ;;;; *************************************************************************
3 ;;;; FILE IDENTIFICATION
4 ;;;;
5 ;;;; Name:          db2-sql.lisp
6 ;;;;
7 ;;;; This file is part of CLSQL.
8 ;;;;
9 ;;;; CLSQL users are granted the rights to distribute and use this software
10 ;;;; as governed by the terms of the Lisp Lesser GNU Public License
11 ;;;; (http://opensource.franz.com/preamble.html), also known as the LLGPL.
12 ;;;; *************************************************************************
13
14 (in-package #:clsql-db2)
15
16 (defmethod database-initialize-database-type ((database-type (eql :db2)))
17   t)
18
19 (defclass db2-database (database)
20   ((henv :initform nil :allocation :class :initarg :henv :accessor henv)
21    (hdbc :initform nil :initarg :hdbc :accessor hdbc)))
22
23
24 (defmethod database-name-from-spec (connection-spec
25                                     (database-type (eql :db2)))
26   (check-connection-spec connection-spec database-type (dsn user password))
27   (destructuring-bind (dsn user password) connection-spec
28     (declare (ignore password))
29     (concatenate 'string dsn "/" user)))
30
31 (defmethod database-connect (connection-spec (database-type (eql :db2)))
32   (check-connection-spec connection-spec database-type (dsn user password))
33   (destructuring-bind (server user password) connection-spec
34     (handler-case
35         (let ((db (make-instance 'db2-database
36                     :name (database-name-from-spec connection-spec :db2)
37                     :database-type :db2)))
38           (db2-connect db server user password)
39           db)
40       (error ()         ;; Init or Connect failed
41         (error 'sql-connection-error
42                :database-type database-type
43                :connection-spec connection-spec
44                :message "Connection failed")))))
45
46
47 ;; API Functions
48
49 (uffi:def-type handle-type cli-handle)
50 (uffi:def-type handle-ptr-type (* cli-handle))
51
52 (defmacro deref-vp (foreign-object)
53   `(the handle-type (uffi:deref-pointer (the handle-ptr-type ,foreign-object) cli-handle)))
54
55 (defun db2-connect (db server user password)
56   (let ((henv (uffi:allocate-foreign-object 'cli-handle))
57         (hdbc (uffi:allocate-foreign-object 'cli-handle)))
58     (sql-alloc-handle SQL_HANDLE_ENV SQL_NULL_HANDLE henv)
59     (setf (slot-value db 'henv) henv)
60     (setf (slot-value db 'hdbc) hdbc)
61
62     (sql-alloc-handle SQL_HANDLE_DBC (deref-vp henv) hdbc)
63     (uffi:with-cstrings ((native-server server)
64                          (native-user user)
65                          (native-password password))
66       (sql-connect (deref-vp hdbc)
67                    native-server SQL_NTS
68                    native-user SQL_NTS
69                    native-password SQL_NTS)))
70     db)