Search code examples
postgresqltypeormhasura

Hasura cli.migration conainer fails to update typeorm @updatedatecolumn in postgres-11


I have a postgres database with tables setup using typeorm in an express api and all my tables have createdAt and updatedAt columns.

when I use my api directly everything works fine and my updatedAt columns get updated appropriately. but when i go write graphql queries through hasura, updatedAt never gets updated.

I am using hasura engine 1.0.0.beta.6.cli.migrations, with postgres 11.5 docker containers with express 4.17.1, [email protected] running locally on my ubuntu 19.04 system. I tried to reach hasura support on discord but it just seems a waste of time as i cannot get through. Has anyone experienced this? Am I missing something?


Solution

  • TypeORM handles createdAt and updatedAt columns outside of Postgres. When you insert data using TypeORM, it injects value into these columns.

    Since Hasura is talking to Postgres directly, neither Postgres nor Hasura knows that these columns should be updated.

    You should set default value now() for the created_at column and setup a triggerfor the updated_at column:

    CREATE TABLE "public"."test_table" (
      "id" serial NOT NULL,
      "created_at" timestamptz NOT NULL DEFAULT now(),
      "updated_at" timestamptz NOT NULL DEFAULT now(),
      PRIMARY KEY ("id")
    );
    
    CREATE OR REPLACE FUNCTION "public"."set_current_timestamp_updated_at"() RETURNS TRIGGER AS $$
      DECLARE _new record; 
      BEGIN _new := NEW;
      _new."updated_at" = NOW();
      RETURN _new; END; 
    $$ LANGUAGE PLPGSQL;
    
    CREATE TRIGGER "set_public_time_updated_at" BEFORE UPDATE ON "public"."test_table" FOR EACH ROW EXECUTE PROCEDURE "public"."set_current_timestamp_updated_at"();
    
    COMMENT ON TRIGGER "set_public_time_updated_at" ON "public"."test_table" IS 'trigger to set value of column "updated_at" to current timestamp on row update';
    

    This will update the columns irrespective of how you contact Postgres.