【问题标题】:Codeigniter Postgresql: Transaction with foreign key deadlockCodeigniter Postgresql:具有外键死锁的事务
【发布时间】:2014-06-25 09:26:34
【问题描述】:

我在使用 postgresql 事务(使用 codeigniter)时遇到问题,这里是涉及的表:

CREATE TABLE factura(
nro_factura serial NOT NULL,
fecha_emision date NOT NULL,    
(... more columns)
PRIMARY KEY (nro_factura));

CREATE TABLE detalle(
id_articulo integer NOT NULL REFERENCES articulos(id) ON UPDATE CASCADE ON DELETE RESTRICT,
nro_factura integer NOT NULL REFERENCES factura(nro_factura) ON UPDATE CASCADE ON DELETE RESTRICT,
(... more columns)
PRIMARY KEY(id_articulo,nro_factura));

这就是交易:

$this->db->trans_start();

        $queryFactura = $this->db->query("INSERT INTO factura (... all columns) VALUES (CURRENT_DATE,?,?,?,?,?,?,?,?,?,?,?,?)",$factura);

        $id_factura = $this->db->query("SELECT nro_factura FROM factura WHERE id_vehiculo=?",array($factura['id_vehiculo'])); 

        foreach ($articulos as $key){
            $queryFactura = $this->db->query("INSERT INTO detalle (id_articulo,nro_factura,precio_venta,descuento,cantidad) VALUES (?,$id_factura,?,?,?)",$key);
        } 

        $this->db->trans_complete();

现在,我无法执行 SELECT 查询,因为之前的插入尚未完成。如何在没有第一次插入的外键的情况下进行第二次插入?

编辑:2014 年 6 月 24 日

最后我使用了 postgre 的 currval() 函数。只需为此替换选择查询:

 $id_factura = $this->db->query("SELECT currval(pg_get_serial_sequence('factura', 'nro_factura'))",array())->result()[0]->currval;

【问题讨论】:

    标签: php sql codeigniter postgresql


    【解决方案1】:

    如果您只需要 INSERT 语句中的“nro_factura”值,则不应使用 SELECT 语句来获取它。

    PostgreSQL 通过其currval() function 公开特定序列返回的最后一个数字。它的记录行为是

    返回 nextval 最近获得的这个序列的值 在当前会话中。 (如果 nextval 从未 在这个会话中被调用这个序列。)因为这是 返回一个会话本地值,它给出一个可预测的答案是否 或者自当前会话以来没有其他会话执行过 nextval 做了。

    CodeIgniter 似乎将自己的函数 $this->db->insert_id() 包装在该 PostgreSQL 函数周围。

    AFAIK,每个广泛使用的 dbms、每个 ORM 和每个数据库抽象层的当前版本都包含这样的功能。

    【讨论】:

    • 谢谢,最后我使用了 currval 函数,它可以工作了。
    猜你喜欢
    • 2021-07-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-12-06
    • 1970-01-01
    相关资源
    最近更新 更多