I'm trying to create tigger function but I cannot ...
# orm-help
t
I'm trying to create tigger function but I cannot use $$ delimeter, then I tried with ' and it worked but I'm receiving this error: `The column
new
does not exist in the current database.`
r
Are you creating it in Migrate?
đź‘€ 1
t
Im creating it in my sql schema then I'm using introspect and generate
Creating table works and everything else but triggers not, I mean they get created but then there's that strange error.
r
Triggers will not be shown in your schema. If you’re creating them in SQL directly then it should work fine unless there’s a syntax error in the trigger.
t
Copy code
CREATE TABLE members (
    name varchar(50) NOT NULL,
    username varchar(50)
    );
    
CREATE OR REPLACE FUNCTION insert_username() 
	RETURNS trigger 
	LANGUAGE plpgsql AS 'BEGIN IF NEW.username IS NULL THEN NEW.username := to_tsvector(NEW.name); END IF; RETURN NEW; END;';


CREATE trigger trig_insert_members
BEFORE INSERT ON members
FOR EACH ROW
EXECUTE PROCEDURE insert_username();


insert into members(name) values('asd');
Works on db-fiddle
Important: I get this error when trying to insert new row.
r
So the above SQL doesn’t work on your database?
t
It doesn't.
r
Tried this and it works perfectly:
Copy code
CREATE TABLE "members" (
	"name" varchar(50) NOT NULL,
	"username" varchar(50)
);

CREATE OR REPLACE FUNCTION insert_username() 
RETURNS trigger
language plpgsql as $$
	begin
		if NEW."username" is null then
			NEW."username" := 'something';
		end if;
		return NEW;
	end;
$$;

CREATE trigger trig_insert_members
BEFORE INSERT ON "members"
FOR EACH ROW
EXECUTE PROCEDURE insert_username();

insert into "members" ("name") values('asd');

select * from "members";
Postgres version 13. It may be an issue with
to_tsvector
in this case.