Returning alternative value if null? - postgresql

Hello I am using postgres 12. I've been learning for a few days now.
I wanted to know if it's possible to write into the CREATE TABLE stage: IF column_x is NULL, return 'alternative value'?
This is my current table:
CREATE OR REPLACE FUNCTION update_modified_column()
RETURNS TRIGGER AS $$
BEGIN
NEW.modified = NOW();
RETURN NEW;
END;
$$ LANGUAGE plpgsql;
CREATE TABLE example (
id BIGSERIAL NOT NULL PRIMARY KEY,
entry_name VARCHAR(150) NOT NULL UNIQUE,
about VARCHAR(1500),
org_type VARCHAR(150),
category VARCHAR(150),
sub_categories VARCHAR(300),
website_link VARCHAR(300) UNIQUE,
membership VARCHAR(100),
instagram VARCHAR(150) UNIQUE,
twitter VARCHAR(150) UNIQUE,
link_lists VARCHAR(100) UNIQUE,
facebook VARCHAR(200) UNIQUE,
youtube VARCHAR(200) UNIQUE,
podcast VARCHAR(200) UNIQUE,
tags VARCHAR(150),
created TIMESTAMPTZ NOT NULL DEFAULT NOW(),
modified TIMESTAMPTZ NOT NULL DEFAULT NOW()
);
CREATE TRIGGER set_timestamp BEFORE UPDATE ON bbdb FOR EACH ROW EXECUTE PROCEDURE update_modified_column();
So in this scenario, I would like for any null entries in 'about' and 'website_link' to say 'Coming soon' and all the social media null entries to just say 'None'. I guess my UNIQUE constraint would not allow this? (I have them to avoid duplicates of entries in case the 'entry_name' is submitted with variations).
Thanks for any help.

As you defined all those columns as UNIQUE you can have multiple null values, but you can't have two rows with the same 'Coming soon' value.
But you can replace those NULL values during retrieval, with the desired replacement:
select id,
coalesce(website_link, 'Coming Soon') as website_link,
coalesce(about, 'Coming soon') as about,
coalesce(twitter, 'None') as twitter,
coalesce(instgram, 'None') as instagram
from the_table;
If you don't want to type that every time, create a view which does that for you.

Related

Creating a trigger that sets a timestamp on UPDATE

I have a table that has 3 columns. One is a record, one is created_time, and the last one is updated_at. I want to create a stored procedure that changes updated_at to NOW() when a record is UPDATED. Each row also has an id called id. I don't have any initial code to show as I am slightly confused on how triggers work. I understand that my trigger would be an update or record, but how do I tell the table to update its corresponding updated_at value to NOW().
I created my table as such:
CREATE TABLE keyvalue (
id id,
record VARCHAR(128) UNIQUE,
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
PRIMARY KEY(id)
);
Any help would be appreciated.
You don't update the table. Rather, you write a BEFORE trigger that modifies the row that is about to be inserted by changing and returning the NEW variable.
CREATE FUNCTION upd_trig() RETURNS trigger
LANGUAGE plpgsql AS
$$BEGIN
NEW.updated_at := current_timestamp;
RETURN NEW;
END;$$;
CREATE TRIGGER upd_trig BEFORE UPDATE ON keyvalue
FOR EACH ROW EXECUTE PROCEDURE upd_trig();

Postgres Trigger for Timestamp in related table

I want to use a trigger to auto-update a table's updated_at date, but the problem is that the actual "update" happens in a separate table. I'll water-down the tables to make it more clear:
-- Trigger
CREATE OR REPLACE FUNCTION trigger_set_timestamp()
RETURNS TRIGGER AS $$
BEGIN
NEW.updated_at = NOW();
RETURN NEW;
END;
$$ LANGUAGE plpgsql;
-- Table to update
CREATE TABLE bug (
id SERIAL PRIMARY KEY,
user_id INTEGER NOT NULL REFERENCES users(id) ON DELETE CASCADE,
updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
);
CREATE TRIGGER set_timestamp
BEFORE UPDATE ON bug
FOR EACH ROW
EXECUTE PROCEDURE trigger_set_timestamp();
Fairly standard, but there's no column to actually update. The real "update" is coming from a comment thread table:
CREATE TABLE comment_thread (
bug_id INTEGER REFERENCES bug(id) ON DELETE CASCADE,
user_id INTEGER REFERENCES users(id) ON DELETE CASCADE,
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
comment VARCHAR(2000),
PRIMARY KEY (bug_id, user_id)
);
So my question is if there's a way to use that trigger (or some variation of) to update the updated_at field in the related row when creating a comment?
Thanks!

First values in an auto increment trigger

I am working with the following table in PostgreSQL 10.3:
CREATE TABLE s_etpta.tab1 (
Number VARCHAR(40) NOT NULL,
id VARCHAR(8),
CONSTRAINT i_tab1 PRIMARY KEY(Number)
)
I need to increment the column id by 1 with every insert. I can't alter the table because I'm not the owner so I have no other choice than to increment a varchar column.
The column is type varchar prefixed with zeros. How can I specify that I want to start with '00000001' if the table is empty? Because when I already have values in my table the trigger gets the last value and increment it for the next insert which is correct, but when my table is empty the id column stays empty since the trigger has no value to increment.
CREATE OR REPLACE FUNCTION schema."Num" (
)
RETURNS trigger AS
$body$
DECLARE
BEGIN
NEW.id := lpad(CAST(CAST(max (id) AS INTEGER)+1 as varchar),8, '0') from
schema.tab1;
return NEW;
END;
$body$
LANGUAGE 'plpgsql'
VOLATILE
RETURNS NULL ON NULL INPUT
SECURITY INVOKER
COST 100;
A trigger design is unsafe and expensive trickery that can easily fail under concurrent write load. Don't use a trigger. Use a serial or IDENTITY column instead:
Auto increment table column
Don't use text (or varchar) for a numeric value.
Don't pad leading zeroes. You can format your numbers any way you like for display with to_char():
How to auto increment id with a character
In Postgres 10 or later your table could look like this:
CREATE TABLE s_etpta.tab1 (
number numeric NOT NULL PRIMARY KEY, -- not VARCHAR(40)
id bigint GENERATED ALWAYS AS IDENTITY -- or just int?
);
No trigger.
Seems odd that number is the PK. Would seem like id should be. Maybe you do not need the id column in the table at all?
Gap-less sequence where multiple transactions with multiple tables are involved
If you need to get the underlying sequence in sync:
How to reset postgres' primary key sequence when it falls out of sync?
Postgres manually alter sequence
If you cannot fix your table, this trigger function works with the existing one (unreliably under concurrent write load):
CREATE OR REPLACE FUNCTION schema.tab1_number_inc()
RETURNS trigger AS
$func$
DECLARE
BEGIN
SELECT to_char(COALESCE(max(id)::int + 1, 0), 'FM00000000')
FROM schema.tab1
INTO NEW.id;
RETURN NEW;
END
$func$ LANGUAGE plpgsql;
Trigger:
CREATE TRIGGER tab1_before_insert
BEFORE INSERT ON schema.tab1
FOR EACH ROW EXECUTE PROCEDURE schema.tab1_number_inc();
The FM modifier removes leading blanks from to_char() output:
Remove blank-padding from to_char() output

postgres update NEW variable before INSERT in a TRIGGER

I've two tables accounts and projects:
create table accounts (
id bigserial primary key,
slug text unique
);
create table projects (
id bigserial primary key,
account_id bigint not null references accounts (id),
name text
);
I want to be able to insert a new row into projects by specifying only account.slug (not account.id). What I'm trying to achieve is something like:
INSERT into projects (account_slug, name) values ('account_slug', 'project_name');
I thought about using a trigger (unfortunately it doesn't work):
create or replace function trigger_projects_insert() returns trigger as $$
begin
if TG_OP = 'INSERT' AND NEW.account_slug then
select id as account_id
from accounts as account
where account.slug = NEW.account_slug;
NEW.account_id = account_id;
-- we should also remove NEW.account_slug but don't know how
end if;
return NEW;
end;
$$ LANGUAGE plpgsql;
create trigger trigger_projects_insert before insert on projects
for each row execute procedure trigger_projects_insert();
What is the best way to achieve what I'm trying to do?
Is a trigger a good idea?
Is there any other solution?
WITH newacc AS (
INSERT INTO accounts (slug)
VALUES ('account_slug')
RETURNING id
)
INSERT INTO projects (account_id, name)
SELECT id, 'project_name'
FROM newacct;
If you are limited in the SQL you can use, another idea might be to define a view over both tables and create an INSTEAD OF INSERT trigger on the view that performs the two INSERTs on the underlying tables. Then an INSERT statement like the one in your question would work.

PostgreSQL trigger to make default value refer to another table

PostgreSQL default values cannot contain variables or refer to any other columns in the table, or in a different table.
However, is it possible to use a trigger to create a "Default value" that will behave in the following manner. First, let me illustrate with two example tables:
create table projects
(
id serial primary key,
created_at timestamp with time zone default now()
);
create table last_updated
(
project_id integer primary key references projects,
updated_at timestamp with time zone default ...
);
In the second table (last_updated) I would like the default to be something like default projects(created_at). I.e. if a date is not specified for updated_at, look at the project_id referenced in the projects table, find the created_at date, and set the updated_at to this date. However, you cannot write this as per the first paragraph of my question.
So how do you write a trigger that will give this functionality?
The correct answer depends on what you do not specify. Typically, one would make updates to the projects table and then audit that in the last_updated table, using an AFTER UPDATE trigger on table projects:
CREATE FUNCTION audit_project_update () RETURNS trigger AS $$
BEGIN
INSERT INTO last_updated VALUES
(NEW.id, -- NEW refers to the updated record in the projects table
now() -- this would be the logical value, but can use NEW.created_at
-- other columns, possibly log session_user
);
RETURN NEW;
END; $$ LANGUAGE plpgsql;
CREATE TRIGGER tr_projects_update
AFTER UPDATE ON projects
FOR EACH ROW EXECUTE PROCEDURE audit_project_update();
Note that in this approach there is never a situation where an INSERT is made on table last_updated without specifying a value for updated_at, assuming that you will not GRANT INSERT to any role on table last_updated, because the trigger function always specifies now(). In the table definition you do not have to specify a default value anymore: the trigger gives you the automated behavior you are looking for.
Your stated question - and confirmed in the comment below - would also use a trigger, but then on the last_updated table:
CREATE FUNCTION project_last_updated () RETURNS trigger AS $$
BEGIN
IF (NEW.updated_at IS NULL) THEN
SELECT created_at INTO NEW.updated_at
FROM projects
WHERE id = NEW.project_id;
END IF;
RETURN NEW;
END; $$ LANGUAGE plpgsql;
CREATE TRIGGER tr_projects_update
BEFORE INSERT ON last_updated
FOR EACH ROW EXECUTE PROCEDURE project_last_updated();
This specification begs the question why you do not simply add a column updated_at to the projects table. Since the project_id column is PK in the last_update table, you can only store a single last update date per project.