我有一个SQLite表定义如下:
create table if not exists KeyValuePair (
key CHAR(255) primary key not null,
val text not null,
fup timestamp default current_timestamp not null, -- time of first upload
lup timestamp default current_timestamp not null -- time of last upload
);
create trigger if not exists entry_first_insert after insert
on KeyValuePair
begin
update KeyValuePair set lup = current_timestamp where key = new.key;
end;
create trigger if not exists entry_last_updated after update of value
on KeyValuePair
begin
update KeyValuePair set lup = current_timestamp where key = old.key;
end;
我试图用Python为这个表写一个peewee.Model
。到目前为止,我得到的是:
当我检查最后一行生成的SQL时,我得到:
CREATE TABLE "keyvaluepair" (
"key" CHAR(255) NOT NULL PRIMARY KEY,
"val" TEXT NOT NULL,
"fup" DATETIME NOT NULL,
"lup" DATETIME NOT NULL
);
所以我现在有两个问题:
entry_first_insert
和entry_last_updated
触发器行为的方法。peewee
是否支持触发器?如果不是,有没有办法只从.sql文件而不是Model
类定义创建表?在fup
和lup
的默认值分配给SQL定义吗?在
不久前,我偶然发现了这个问题,并花了一些时间想出了一个支持PeeWee触发器的优化设计(受上述答案的启发)。我很高兴我们最终实现了它,并希望与大家分享这一点。在某个时候,我会为这个做一个公关。
在PeeWee中创建触发器和触发器侦听器
目的
本文档分两部分介绍如何进行此操作:
Trigger
。在ListenThread
,该函数将在每次更新表时通知回调函数。在如何实施
这个设计的好处是你只需要一个项目:TriggerModelMixin模型。然后很容易创建侦听器来订阅/拥有回调方法。
TriggerModelMixin可以复制粘贴为:
实施示例:
^{pr2}$如何使用这个
1。向数据库中的模型添加触发器
这很容易。只需将mixin TriggerModelMixin添加到要添加支持的模型中。这个Mixin将处理触发器的创建,以及在调用触发器时通知的侦听方法。
2。创建ListenThread以进行回调
侦听器有两种模式:}(阻塞)。默认情况下,它将是
async
(非阻塞)和{non-blocking
,如果希望它被阻塞,可以用sync=True
来更改它。要使用它(无论哪种情况),请创建一个回调方法。请注意,当接收到更新(记录是串行处理的)时,此回调方法将被阻塞,因此在该方法中不要有重载或I/O。此方法的唯一要求是
record
的键控参数,该参数将作为字典返回数据库中的记录。在此基础上,只需创建侦听器,然后调用
listen_and_call
。可以重写插入时间戳的模型的save函数。有关示例,请参见TimeStampModel。
这两个问题我都想好了。此解决方案实际上在sqlddl中强制使用所需的触发器和默认时间戳。
首先,我们定义一个便利类来包装触发器的SQL。对于
peewee.Node
对象,有一种更合适的方法来实现这一点,但我没有时间为这个项目深入研究所有这些内容。这个Trigger
类只提供字符串格式,以输出正确的sql来创建触发器。接下来,我们定义一个继承
^{pr2}$BaseModel
的类TriggerTable
。这个类重写默认的create_table
,以便在创建表之后创建触发器。如果任何触发器未能创建,则整个创建操作都将回滚。下一步是创建一个类
BetterDateTimeField
。如果default
实例变量设置为datetime.datetime.now
函数,则此Field
对象重写默认的__ddl__
以附加一个“default current}时间戳”字符串。当然有更好的方法可以做到这一点,但这一个抓住了基本的用例。最后,我们定义了新的和改进的
KeyValuePair
模型,其中包含了触发器和日期时间字段的改进。我们通过创建表来结束Python代码。现在模式已正确创建:
相关问题 更多 >
编程相关推荐