From 2c5e84d8360615de6316e183535a25210c9f43d4 Mon Sep 17 00:00:00 2001 From: Deepak Date: Sat, 26 Dec 2020 15:04:51 -0600 Subject: [PATCH] adds create and update time to actions --- .../000001_create_action_table.down.sql | 2 ++ .../000001_create_action_table.up.sql | 18 +++++++++++++- db/postgres.go | 2 +- models/action.go | 24 ++++++++++++------- 4 files changed, 35 insertions(+), 11 deletions(-) diff --git a/db/migrations/000001_create_action_table.down.sql b/db/migrations/000001_create_action_table.down.sql index 5f6fe56..48d368f 100644 --- a/db/migrations/000001_create_action_table.down.sql +++ b/db/migrations/000001_create_action_table.down.sql @@ -1 +1,3 @@ DROP TABLE IF EXISTS actions; + +DROP FUNCTION IF EXISTS trigger_set_timestamp; diff --git a/db/migrations/000001_create_action_table.up.sql b/db/migrations/000001_create_action_table.up.sql index 9844843..d7539f5 100644 --- a/db/migrations/000001_create_action_table.up.sql +++ b/db/migrations/000001_create_action_table.up.sql @@ -1,4 +1,20 @@ CREATE TABLE IF NOT EXISTS actions( id serial PRIMARY KEY, - description VARCHAR (500) + description VARCHAR (500), + created_at TIMESTAMP WITH TIME ZONE DEFAULT CURRENT_TIMESTAMP, + updated_at TIMESTAMP WITH TIME ZONE DEFAULT CURRENT_TIMESTAMP ); + + +CREATE OR REPLACE FUNCTION trigger_set_timestamp() +RETURNS TRIGGER AS $set_updated$ +BEGIN + NEW.updated_at = NOW(); + RETURN NEW; +END; +$set_updated$ LANGUAGE plpgsql; + +CREATE TRIGGER set_updated +BEFORE UPDATE ON actions +FOR EACH ROW +EXECUTE PROCEDURE trigger_set_timestamp(); diff --git a/db/postgres.go b/db/postgres.go index c6a94fe..1340092 100644 --- a/db/postgres.go +++ b/db/postgres.go @@ -61,7 +61,7 @@ func GetStore() *postgresStore { func (store *postgresStore) SelectActions() ([]*models.Action, error) { actions := make([]*models.Action, 0) - err := store.db.Select(&actions, "SELECT id, description FROM actions") + err := store.db.Select(&actions, "SELECT id, description, created_at AS createdat, updated_at AS updatedat FROM actions") if err != nil { return nil, err } diff --git a/models/action.go b/models/action.go index a7a050a..8ab87bc 100644 --- a/models/action.go +++ b/models/action.go @@ -1,10 +1,16 @@ package models - -type Action struct { - ID int64 - Description string -} - -func (m *Model) Actions() ([]*Action, error) { - return m.SelectActions() -} + +import ( + "time" +) + +type Action struct { + ID int64 + Description string + CreatedAt time.Time + UpdatedAt time.Time +} + +func (m *Model) Actions() ([]*Action, error) { + return m.SelectActions() +}