使用 clsql 在 postgresql 中自动生成主键

Autogenerated primary key in postgresql with clsql

我正在尝试使用 Common Lisp ORM 创建一个简单的数据库。我使用 PostgreSQL 和 CLSQL。我可以创建 类 并生成表,但是当我想插入一个没有主键的值以获得生成的值时,它不起作用。它似乎适用于 mysql 数据库。可以用 PostgreSQL 做到这一点吗?

我定义主键为:

(id :db-kind :key
    :db-type "serial" 
    :db-constraints (:not-null :unique)
    :type integer
    :initarg :id)

我得到这个错误:

While accessing database #<POSTGRESQL-DATABASE localhost/cl_ormex/postgres OPEN {1004FCC403}>
  with expression "SELECT currval ('NIL')":
   Error 42P01 / relation "nil" does not exist
   LINE 1: SELECT currval ('NIL')
                           ^  
 has occurred.
   [Condition of type SQL-DATABASE-DATA-ERROR]

我使用 PostgreSQL 9.5.2 和 SBCL 1.3.1。

编辑

这是一个例子:

(require 'clsql)
(defpackage :orm-ex (:use :cl :clsql))
(in-package :orm-ex)
(file-enable-sql-reader-syntax)
(enable-sql-reader-syntax)
(setf *default-caching* nil)
(connect '("localhost" "examp" "postgres" "postgres")
     :database-type :postgresql)

(def-view-class person ()
  ((id :db-kind :key
       :db-type "serial"
       :db-constraints (:not-null :unique)
       :type integer
       :initarg :id
       :accessor person-id)
   (name :type (varchar 30)
     :initarg :name
     :accessor person-name)))

(defparameter person1
  (make-instance 'person
         :name "Matt"))

(dolist (c '(person)) (create-view-from-class c))
(update-records-from-instance person1)

我不太明白这个错误,但该行似乎已插入到数据库中。

这个好像不行。它有一个 todo file 表示:

  • Test that ":db-kind :key" adds an index for that key. This is complicated by different backends showing autogenerated primary key in different ways.

所以它可能不适用于 Postgres。我相信你有很多可能。

使用更新一点的其他框架,比如 cl-dbi,take a look here:

cl-dbi provides a uniform interface to the various database server-specific libraries (cl-postgres, cl-mysql, etc.). SxQL provides a DSL for building safe, automatically parametrized SQL queries.

There are two fairly complete ORMs: Crane, by yours truly, and Integral, by the author of cl-dbi.

Consolidation:
Discourage using anything other than cl-dbi.

Future Work:

Bindings for other database systems, e.g. Oracle, exist. Writing drivers for cl-dbi would be the best course of action and help consolidation.

我发现生成 ID 很容易,这些 ID 可以使用时间戳轻松按创建时间升序或降序排列,或者您也可以使用生成器或考虑您插入的最后一个数字

但是这会做一些技巧,世界时和添加一个随机数,用于同时创建许多实体并且碰撞率较低

(format nil "~12,'0d-~6,'0d" (get-universal-time) (random 1000000))

来自 Mark Watson 的 Loving Lisp - db-constraints 需要用 :auto-increment 定义。
注意 - 今天 (25/10/2019) 的书籍版本不正确,但下载的代码是:

(clsql:def-view-class article ()
  ((id
    :db-kind :key
    :db-constraints (:auto-increment :not-null :unique)
    :type integer
    :initarg :id)
   (uri
    :accessor uri
    :type (string 60)
    :initarg :uri)
   (title
    :accessor title
    :type (string 90)
    :initarg :title)
   (text
    :accessor text
    :type (string 500)
    :nulls-ok t
    :initarg :text)))