Postgres插入触发器填充id

时间:2017-01-18 16:50:00

标签: postgresql

我有一个BEFORE触发器,它应该填充记录的根ID,当然,这将指向最根本的条目。即:

newObject.onsuccess = function(event){

                savedID = event.target.result;
                SExpenses.findRecord('SERVER_ID',item.SERVER_ID).set({ID:savedID});
                Ext.Ajax.request({
                    url: App.url.receipts,
                    async: true,
                    method: 'GET',
                    params: {
                        Request_Log_RC: item.SERVER_ID
                    },
                    success: function(retrieve){

                        var result2 = Ext.decode(retrieve.responseText);

                        Ext.each(result2.data,function(item2){
                            SReceipt.add(item2);
                            var newReceiptIDB = response.transaction(["ReceiptsLocal"],'readwrite')
                            .objectStore("ReceiptsLocal");

                            newReceiptIDB.add({EXPENSE_AMOUNT: item2.EXPENSE_AMOUNT, EXPENSE_CURRENCY_ID:item2.EXPENSE_CURRENCY_ID,
                                               EXPENSE_NAME: item2.EXPENSE_NAME, REPORT_ID: savedID, CURRENCY_ABB: item2.CURRENCY_ABB,
                                               EXPENSE_IMAGE: null, SYNCED: true, DELETED: item2.DELETED,
                                               SERVER_ID: item2.SERVER_ID, SERVER_REPORT_ID: item.SERVER_ID,
                                               EXPENSE_EXCHANGE_RATE: null
                                              });
                            newReceiptIDB.onsuccess = function(event){
                                savedRecID = event.target.result;
                                SReceipt.findRecord('SERVER_ID',item2.SERVER_ID).set({ID:savedRecID});

                            };   
                        });
                    }
                });   
            }.bind(null, item);

如果entry的parent_id为null,则指向记录本身。

问题是 - 在BEFORE INSERT触发器内部,如果parent_id为null,我可以或者是否应该获取下一个序列值,填充id和root_id以避免在AFTER触发器中填充root_id?

1 个答案:

答案 0 :(得分:0)

根据您自己的定义:

  

如果entry的parent_id为null,则指向记录本身

然后你必须这样做:

if new.parent_id is null then
    new.root_id = new.id ;
else
  WITH RECURSIVE p (parent_id, level) AS
  (
    -- Base case
    SELECT 
        parent_id, 0 as level
    FROM 
        t 
    WHERE 
        t.id = new.id
    UNION ALL
    SELECT
        t.parent_id, level + 1
    FROM
        t JOIN p ON t.id = p.parent_id
    WHERE
        t.parent_id IS NOT NULL
  )
  SELECT
    parent_id 
  INTO 
    new.root_id
  FROM
    p
  ORDER BY
    level DESC
  LIMIT
    1 ;
end if ;
RETURN new ;