我正在创建这样的表格:
CREATE TABLE foobar (id uniqueidentifier, foo text, bar text, PRIMARY KEY (id))
如何在表foobar中插入或生成id字段的值?
你可以认为SQLite根本不支持任何数据类型。在SQLite3中,例如可以这样做。
sqlite> create table test (id wibblewibble primary key);
SQLite可以愉快地创建具有“数据类型”wibblewibble的列。SQLite还可以愉快地创建具有“数据类型”uuid、guid和SuperChicken的列。
对于您来说,关键点可能是如何自动生成uid。在这方面SQLite帮不上什么忙。
您可以完全由客户端程序决定。如果您使用python编程,请使用uuid模块。在ruby中,您可以使用SecureRandom.uuid函数。其他语言也有类似的功能或解决方法。
您可以在C中编写自己的uid生成函数。 (请参见创建或重新定义SQL函数。)我认为这是相对极端的方法。
在线上的其他讨论中,人们普遍存在对UUID的误解。 UUID不仅仅是一个128位的随机数。 UUID具有结构和规则。 请参见RFC 4122。
Benjamin Berry的答案是不正确的,它会产生格式不正确的UUIDUUID,但它展示了一种有趣的技术,使用子查询生成随机数,然后从中选择子字符串。这里有一个类似的东西,我确认它可以工作:
select substr(u,1,8)||'-'||substr(u,9,4)||'-4'||substr(u,13,3)||
'-'||v||substr(u,17,3)||'-'||substr(u,21,12) from (
select lower(hex(randomblob(16))) as u, substr('89ab',abs(random()) % 4 + 1, 1) as v);
一些示例输出:
c71122df-18e4-4a78-a446-fbf7b8f2969b
61e75f87-978b-4d9e-b587-bedcc2d23898
30eee0fa-2ff2-4ff5-b8ef-f99378272999
这里有类似的内容可以直接用作表达式:
lower(hex(randomblob(4))) || '-' || lower(hex(randomblob(2))) || '-4' || substr(lower(hex(randomblob(2))),2) || '-' || substr('89ab',abs(random()) % 4 + 1, 1) || substr(lower(hex(randomblob(2))),2) || '-' || lower(hex(randomblob(6)))
例如,作为列的默认值传递:
sqlite> create table "table" (
"id" char(36) default (lower(hex(randomblob(4))) || '-' || lower(hex(randomblob(2))) || '-4' || substr(lower(hex(randomblob(2))),2) || '-' || substr('89ab',abs(random()) % 4 + 1, 1) || substr(lower(hex(randomblob(2))),2) || '-' || lower(hex(randomblob(6)))),
"data" varchar(255), primary key ("id")
);
sqlite> insert into "table" ("data") values ('foo');
sqlite> insert into "table" ("data") values ('bar');
sqlite> select * from "table";
947efcc9-4212-442a-b68c-eb6fbd8a7128|foo
a2c3857b-1eb4-40bd-aed2-6e8d68cc2ab8|bar
select SUBSTR(UUID, 0, 8)||'-'||SUBSTR(UUID,8,4)||'-'||SUBSTR(UUID,12,4)||'-'||SUBSTR(UUID,16)
from (
select lower(hex(randomblob(16))) AS UUID
);
var connection = new SqliteConnection("DataSource=:memory:");
connection.CreateFunction("newid", Guid.NewGuid);