gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-29 11:45:02 27 4
gpt4 key购买 nike

我正在尝试使用 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)

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

最佳答案

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

(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)))

关于postgresql - 使用 clsql 在 postgresql 中自动生成主键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36687705/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com