M
M
MaxLich2017-07-28 21:17:35
PostgreSQL
MaxLich, 2017-07-28 21:17:35

Why do I get an error when starting a trigger?

Hello. I watch video courses on SQL. I am training on PostgreSQL. And in one lesson, trigger functions are dealt with. I copied the code from this video. I tried to do everything. Triggers related to the insertion of a new record and its deletion work properly. And here triggers which should be launched at change of record - give an error. The error is like this:


loftblog_lesson4=# UPDATE profiles SET name = 'Alex' WHERE user_id = 2;
ERROR: record "old" has no field "user_id"
CONTEXT: SQL statement "UPDATE users SET updated_at = NOW() WHERE id = OLD.user_id"
PL/pgSQL function update_user() line 3 at SQL statement
SQL statement "UPDATE users SET updated_at = NOW() WHERE id = OLD.user_id"
PL/pgSQL function update_user() line 3 at SQL statement

And here is the code for creating tables and a trigger:
CREATE TABLE IF NOT EXISTS users (
    id SERIAL PRIMARY KEY,
    username VARCHAR(32) NOT NULL UNIQUE,
    password VARCHAR(255) NOT NULL,
    email VARCHAR(255) NOT NULL UNIQUE,
    created_at TIMESTAMP NOT NULL,
    updated_at TIMESTAMP NOT NULL);

CREATE TABLE IF NOT EXISTS profiles (
    id SERIAL PRIMARY KEY,
    user_id INTEGER NOT NULL,
    name VARCHAR(255),
    last_name VARCHAR(255),
    photo_path VARCHAR(255),
    about TEXT,
    FOREIGN KEY (user_id) REFERENCES users(id)
    );

CREATE OR REPLACE FUNCTION update_user() RETURNS TRIGGER
 AS $$
 BEGIN
    UPDATE users SET updated_at = NOW() WHERE id = OLD.user_id;

    RETURN OLD;
 END;
 $$ LANGUAGE plpgsql;

DROP TRIGGER IF EXISTS tr_update_user ON profiles;

CREATE TRIGGER tr_update_user AFTER UPDATE ON profiles
FOR EACH ROW  EXECUTE PROCEDURE update_user();

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Alexander Kuznetsov, 2017-07-29
@MaxLich

The example you provided is completely working.
Check the table structure, have you changed it?

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question