惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

WordPress大学
WordPress大学
Microsoft Azure Blog
Microsoft Azure Blog
aimingoo的专栏
aimingoo的专栏
Vercel News
Vercel News
U
Unit 42
L
LangChain Blog
J
Java Code Geeks
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
The Cloudflare Blog
F
Fortinet All Blogs
小众软件
小众软件
I
InfoQ
P
Proofpoint News Feed
D
DataBreaches.Net
Martin Fowler
Martin Fowler
H
Help Net Security
T
Tailwind CSS Blog
N
Netflix TechBlog - Medium
有赞技术团队
有赞技术团队
Y
Y Combinator Blog
Recent Announcements
Recent Announcements
B
Blog RSS Feed
酷 壳 – CoolShell
酷 壳 – CoolShell
B
Blog

jdhao's digital space

Conversion between base64 and OpenCV or PIL Image 腾讯云对象存储博客图床开启 CDN 加速(不需要购买额外域名) Search and Replace in Multiple Files in Vim/Neovim Change Table Column Width in LaTeX Image or Table Side by Side in LaTeX LaTeX 并排显示图像或表格 Firenvim: Neovim inside Your Browser Content inside HTML tags missing in Latest Hugo? Creating Markdown Front Matter with Ultisnips Labelme JSON 标注格式转 voc XML 格式 Nifty Nvim Techniques That Make My Life Easier -- Series 6 macOS 下如何为视频制作字幕 Running Command Asynchronously inside Neovim Resolving Merge Conflict after Git Stash Pop Pylint: command not found? A Hands-on Experience with Neovim's Built-in LSP Support How to Convert PDF to Images with Imagemagick 互联网上常用缩略语集锦 File Backup in Neovim Converting PDF Pages to Images with Poppler Nifty Nvim Techniques That Make My Life Easier -- Series 5 Neovim Configuration for System-wide Use How to sort a list of tuple or list in Python -- lambda or itemgetter? Building A Vim Statusline from Scratch 人类第一颗原子弹爆炸始末 Distributed Training in PyTorch with Horovod Learning Expect Programming Essential Knowledge about SSH Nifty LaTeX Techniques -- Series 1 更改 Adsense 邮寄地址,重新寄送 PIN
Creating A Trigger in PostgreSQL
2022-09-12 · via jdhao's digital space

We can use trigger to automate oerations, for example, preventing insertion of a record if certain condition is met. In this post, we show an example trigger function and its usage.

Suppose we have a loan table with following column:

  • copy_id: id for an item
  • lend_date: date when it is lent
  • return_date: date when it is returned, can be NULL (has been returned yet)

Create a trigger function#

In this example, we create a function to check whether the new record is a valid record. If lend_date for new record is later than existing record, and is smaller than return_date of the copy, or if this copy hasn’t been returned (loan.return_data IS NULL), then this is invalid record.

CREATE OR REPLACE FUNCTION check_loan_validity()
    RETURNS TRIGGER
    LANGUAGE PLPGSQL
AS
$func$
BEGIN
    IF EXISTS(SELECT 1
              FROM loan
              WHERE loan.copy_id = NEW.copy_id
                AND NEW.lend_date >= loan.lend_date
                AND (NEW.lend_date <= loan.return_date OR loan.return_date IS NULL))
    THEN
        RAISE EXCEPTION 'Invalid lend_date provided: %', NEW.lend_date;
    END IF;

    RETURN NEW;
END;
$func$;

The statement LANGUAGE PLPGSQL tells postgres that we can using plpgsql syntax, which is more powerful than plain SQL. See more discussion here.

You can also put the language declaration after the function body (see also this post):

$func$
<function body>
$func$ LANGUAGE PLPGSQL;

All string inside the dollar signs are function body definition. The use of dollar sign here is to simplify the writing of the function, as indicated by official doc on functions:

The function body is simply a string literal so far as CREATE FUNCTION is concerned. It is often helpful to use dollar quoting (see Section 4.1.2.4) to write the function body, rather than the normal single quote syntax. Without dollar quoting, any single quotes or backslashes in the function body must be escaped by doubling them

When creating a trigger function, the variable NEW represents the new records that is going to be inserted or updated.

Create the trigger#

After creating the trigger function, we can now create a trigger on this table.

CREATE TRIGGER check_loan_trigger
    BEFORE INSERT
    ON loan
    FOR EACH ROW
EXECUTE PROCEDURE check_loan_validity();

References#