Name

DEF-VIEW-CLASS — Defines CLOS classes with mapping to SQL database.Macro

Syntax

      def-view-class name superclasses slots &rest class-options => class

Arguments and Values

name

The class name.

superclasses

The superclasses for the defined class.

slots

The class slot definitions.

class options

The class options.

class

The defined class.

Slot Options

  • :db-kind - specifies the kind of database mapping which is performed for this slot and defaults to :base which indicates that the slot maps to an ordinary column of the database table. A :db-kind value of :key indicates that this slot is a special kind of :base slot which maps onto a column which is one of the unique keys for the database table, the value :join indicates this slot represents a join onto another View Class which contains View Class objects, and the value :virtual indicates a standard CLOS slot which does not map onto columns of the database table.

  • :db-info - if a slot is specified with :db-kind :join, the slot option :db-info contains a property list which specifies the nature of the join. The valid members of the list are:

    • :join-class class-name - the name of the class to join on.

    • :home-key slot-name - the name of the slot of this class for joining

    • :foreign-key slot-name - the name of the slot of the :join-class for joining

    • :target-slot target-slot - this is an optional parameter. If specified, then the join slot of the defining class will contain instances of this target slot rather than of the join class. This can be useful when the :join-class is an intermediate class in a many-to-many relationship and the application is actually interested in the :target-slot.

    • :retrieval time - The default value is :deferred, which defers filling this slot until the value is accessed. The other valid value is :immediate which performs the SQL query when the instance of the class is created. In this case, the :set is automatically set to NIL

    • :set set - This controls what is stored in the join slot. The default value is T. When set is T and target-slot is undefined, the join slot will contain a list of instances of the join class. Whereas, if target-slot is defined, then the join slot will contain a list of pairs of (target-value join-instance). When set is NIL, the join slot will contain a single instances.

  • :type - for slots of :db-kind :base or :key, the :type slot option has a special interpretation such that Lisp types, such as string, integer and float are automatically converted into appropriate SQL types for the column onto which the slot maps. This behaviour may be overridden using the :db-type slot option. The valid values are:

    string - a variable length character field up to *default-string-length* characters.
    (string n) - a fixed length character field n characters long.
    varchar - a variable length character field up to *default-string-length* characters.
    (varchar n) - a variable length character field up to n characters in length.
    char - a single character field
    integer - signed integer at least 32-bits wide
    (integer n)
    float
    (float n)
    long-float
    number
    (number n)
    (number n p)
    tinyint - An integer column 8-bits wide. [not supported by all database backends]
    smallint - An integer column 16-bits wide. [not supported by all database backends]
    bigint - An integer column 64-bits wide. [not supported by all database backends]
    universal-time - an integer field sufficiently wide to store a universal-time. On most databases, a slot of this type assigned a SQL type of BIGINT
    wall-time - a slot which stores a date and time in a SQL timestamp column. CLSQL provides a number of time manipulation functions to support objects of type wall-time.
    date - a slot which stores the date (without any time of day resolution) in a column. CLSQL provides a number of time manipulation functions that operate on date values.
    duration - stores a duration structure. CLSQL provides routines for wall-time and duration processing.
    boolean - stores a T or NIL value.
    generalized-boolean - similar to a boolean in that either a T or NIL value is stored in the SQL database. However, any Lisp object can be stored in the Lisp object. A Lisp value of NIL is stored as FALSE in the database, any other Lisp value is stored as TRUE.
    keyword - stores a keyword
    symbol - stores a symbol
    list - stores a list by writing it to a string. The items in the list must be able to be readable written.
    vector - stores a vector similarly to list
    array - stores a array similarly to list

  • :column - specifies the name of the SQL column which the slot maps onto, if :db-kind is not :virtual, and defaults to the slot name. If the slot name is used for the SQL column name, any hypens in the slot name are converted to underscore characters.

  • :void-value - specifies the value to store in the Lisp instance if the SQL value is NULL and defaults to NIL.

  • :db-constraints - is a keyword symbol representing an SQL column constraint expression or a list of such symbols. The following column constraints are supported: :not-null, :primary-key, :unique, :unsigned (MySQL specific), :zerofill (MySQL specific) and :auto-increment (MySQL specific).

  • :db-type - a string to specify the SQL column type. If specified, this string overrides the SQL column type as computed from the :type slot value.

  • :db-reader - If a string, then when reading values from the database, the string will be used for a format string, with the only value being the value from the database. The resulting string will be used as the slot value. If a function then it will take one argument, the value from the database, and return the value that should be put into the slot. If a symbol, then the symbol-function of the symbol will be used.

  • :db-writer - If a string, then when reading values from the slot for the database, the string will be used for a format string, with the only value being the value of the slot. The resulting string will be used as the column value in the database. If a function then it will take one argument, the value of the slot, and return the value that should be put into the database. If a symbol, then the symbol-function of the symbol will be used.

Class Options

  • :base-table - specifies the name of the SQL database table. The default value is the class name. Like slot names, hypens in the class name are converted to underscore characters.

  • :normalizedp - specifies whether this class uses normalized inheritance from parent classes. Defaults to nil, i.e. non-normalized schemas. When true, SQL database tables that map to this class and parent classes are joined on their primary keys to get the full set of database columns for this class. This means that the primary key of the base class will be copied to all subclasses as we insert so that all parent classes of an instance will have the same value in their primary key slots (see tests/ds-nodes.lisp and oodml.lisp)

Description

Creates a View Class called name whose slots slots can map onto the attributes of a table in a database. If superclasses is NIL then the superclass of class will be standard-db-object, otherwise superclasses is a list of superclasses for class which must include standard-db-object or a descendent of this class.

Normalized inheritance schemas

Specifying that :normalizedp is T tells CLSQL to normalize the database schema for inheritance. What this means is shown in the examples below.

With :normalizedp equal to NIL (the default) the class inheritance would result in the following:

(def-view-class node ()
  ((title :accessor title :initarg :title :type (varchar 240))))

SQL table NODE:
+-------+--------------+------+-----+---------+-------+
| Field | Type         | Null | Key | Default | Extra |
+-------+--------------+------+-----+---------+-------+
| TITLE | varchar(240) | YES  |     | NULL    |       |
+-------+--------------+------+-----+---------+-------+

(def-view-class user (node)
  ((user-id :accessor user-id :initarg :user-id
            :type integer :db-kind :key :db-constraints (:not-null))
   (nick :accessor nick :initarg :nick :type (varchar 64))))

SQL table USER:
+---------+--------------+------+-----+---------+-------+
| Field   | Type         | Null | Key | Default | Extra |
+---------+--------------+------+-----+---------+-------+
| USER_ID | int(11)      | NO   | PRI |         |       |
| NICK    | varchar(64)  | YES  |     | NULL    |       |
| TITLE   | varchar(240) | YES  |     | NULL    |       |
+---------+--------------+------+-----+---------+-------+
      

Using :normalizedp T, both view-classes need a primary key to join them on:

(def-view-class node ()
  ((node-id :accessor node-id :initarg :node-id
            :type integer :db-kind :key
            :db-constraints (:not-null))
   (title :accessor title :initarg :title :type (varchar 240))))

SQL table NODE:
+---------+--------------+------+-----+---------+-------+
| Field   | Type         | Null | Key | Default | Extra |
+---------+--------------+------+-----+---------+-------+
| NODE_ID | int(11)      | NO   | PRI |         |       |
| TITLE   | varchar(240) | YES  |     | NULL    |       |
+---------+--------------+------+-----+---------+-------+

(def-view-class user (node)
  ((user-id :accessor user-id :initarg :user-id
            :type integer :db-kind :key :db-constraints (:not-null))
   (nick :accessor nick :initarg :nick :type (varchar 64)))
  (:normalizedp t))

SQL table USER:
+---------+-------------+------+-----+---------+-------+
| Field   | Type        | Null | Key | Default | Extra |
+---------+-------------+------+-----+---------+-------+
| USER_ID | int(11)     | NO   | PRI |         |       |
| NICK    | varchar(64) | YES  |     | NULL    |       |
+---------+-------------+------+-----+---------+-------+
      

In this second case, all slots of the view-class 'node are also available in view-class 'user, and can be used as one would expect. For example, with the above normalized view-classes 'node and 'user, and SQL tracing turned on:

CLSQL> (setq test-user (make-instance 'user :node-id 1 :nick "test-user"
                                            :title "This is a test user"))
#<USER {1003B392E1}>

CLSQL> (update-records-from-instance test-user :database db)

;; .. => INSERT INTO NODE (NODE_ID,TITLE) VALUES (1,'This is a test user')
;; .. <= T
;; .. => INSERT INTO USER (USER_ID,NICK) VALUES (1,'test-user')
;; .. <= T
1


CLSQL> (node-id test-user)
1

CLSQL> (title test-user)
"This is a test user"

CLSQL> (nick test-user)
"test-user"
      

Notes from a refactor of this code. There are many assumptions that need to be met for normalized classes to work * The each of the classes should have its own single key column (of a different name) that will contain an identical value. EG: node has a node-id, setting which is a node has a node-id and a setting-id which must be equal. You cannot use node-id as the primary key on both tables (as I would have expected). The exception to this seems to be if your class has no slots at all, then you dont need to have a single key column, because your class is fully represented in the db by its parent(s) * more than one parent class per normalized class should be considered experimental and untested (vaya con Dios) * There are a few code paths that just dont pay any attention to normalized classes eg: delete-records-for-instance

Examples

The following examples are from the CLSQL test suite.

(def-view-class person (thing)
  ((height :db-kind :base :accessor height :type float
           :initarg :height)
   (married :db-kind :base :accessor married :type boolean
            :initarg :married)
   (birthday :type clsql:wall-time :initarg :birthday)
   (bd-utime :type clsql:universal-time :initarg :bd-utime)
   (hobby :db-kind :virtual :initarg :hobby :initform nil)))

(def-view-class employee (person)
  ((emplid
    :db-kind :key
    :db-constraints :not-null
    :type integer
    :initarg :emplid)
   (groupid
    :db-kind :key
    :db-constraints :not-null
    :type integer
    :initarg :groupid)
   (first-name
    :accessor first-name
    :type (varchar 30)
    :initarg :first-name)
   (last-name
    :accessor last-name
    :type (varchar 30)
    :initarg :last-name)
   (email
    :accessor employee-email
    :type (varchar 100)
    :initarg :email)
   (ecompanyid
    :type integer
    :initarg :companyid)
   (company
    :accessor employee-company
    :db-kind :join
    :db-info (:join-class company
			  :home-key ecompanyid
			  :foreign-key companyid
			  :set nil))
   (managerid
    :type integer
    :initarg :managerid)
   (manager
    :accessor employee-manager
    :db-kind :join
    :db-info (:join-class employee
			  :home-key managerid
			  :foreign-key emplid
			  :set nil))
   (addresses
    :accessor employee-addresses
    :db-kind :join
    :db-info (:join-class employee-address
			  :home-key emplid
			  :foreign-key aemplid
			  :target-slot address
			  :set t)))
  (:base-table employee))

(def-view-class company ()
  ((companyid
    :db-kind :key
    :db-constraints :not-null
    :type integer
    :initarg :companyid)
   (groupid
    :db-kind :key
    :db-constraints :not-null
    :type integer
    :initarg :groupid)
   (name
    :type (varchar 100)
    :initarg :name)
   (presidentid
    :type integer
    :initarg :presidentid)
   (president
    :reader president
    :db-kind :join
    :db-info (:join-class employee
			  :home-key presidentid
			  :foreign-key emplid
			  :set nil))
   (employees
    :reader company-employees
    :db-kind :join
    :db-info (:join-class employee
			  :home-key (companyid groupid)
			  :foreign-key (ecompanyid groupid)
			  :set t))))

(def-view-class address ()
  ((addressid
    :db-kind :key
    :db-constraints :not-null
    :type integer
    :initarg :addressid)
   (street-number
    :type integer
    :initarg :street-number)
   (street-name
    :type (varchar 30)
    :void-value ""
    :initarg :street-name)
   (city
    :column "city_field"
    :void-value "no city"
    :type (varchar 30)
    :initarg :city)
   (postal-code
    :column zip
    :type integer
    :void-value 0
    :initarg :postal-code))
  (:base-table addr))

;; many employees can reside at many addressess
(def-view-class employee-address ()
  ((aemplid :type integer :initarg :emplid)
   (aaddressid :type integer :initarg :addressid)
   (verified :type boolean :initarg :verified)
   (address :db-kind :join
	    :db-info (:join-class address
				  :home-key aaddressid
				  :foreign-key addressid
				  :retrieval :immediate)))
  (:base-table "ea_join"))

(def-view-class deferred-employee-address ()
  ((aemplid :type integer :initarg :emplid)
   (aaddressid :type integer :initarg :addressid)
   (verified :type boolean :initarg :verified)
   (address :db-kind :join
	    :db-info (:join-class address
				  :home-key aaddressid
				  :foreign-key addressid
				  :retrieval :deferred
				  :set nil)))
  (:base-table "ea_join"))
      

Side Effects

Creates a new CLOS class.

Affected by

Nothing.

Exceptional Situations

None.

See Also

create-view-from-class
standard-db-object
drop-view-from-class

Notes

The actual SQL type for a column depends up the database type in which the SQL table is stored. As an example, the view class type (varchar 100) specifies a SQL column type VARCHAR(100) in MySQL and a column type VARCHAR2(100) in Oracle

The actual lisp type for a slot may be different than the value specified by the :type attribute. For example, a slot declared with ":type (string 30)" actually sets the slots Lisp type as (or null string). This is to allow a NIL value or a string shorter than 30 characters to be stored in the slot.