Search code examples
sqlpostgresqlecto

Postgres - Insert timestamps in an INSERT INTO query while selecting values from tables?


I'm trying to run a migration in a Phoenix application, but Postgrex returns the following error:

null value in column "inserted_at" violates not-null constraint

The query that generated that error is:

execute "INSERT INTO contract_groups
  (SELECT c.id, fg.group_id FROM contracts c, folder_groups fg
  WHERE c.folder_id = fg.folder_id)"

I tried updating the query to this:

execute "INSERT INTO contract_groups
  (contract_id, group_id, inserted_at)
  VALUES ((SELECT c.id, fg.group_id FROM contracts c, folder_groups fg 
  WHERE c.folder_id = fg.folder_id), NOW())"

but I get another error saying subquery must return only one column.

This is the rough definition of the tables.


Solution

  • insert into contract_groups (contract_id, group_id, inserted_at)
    select c.id, fg.group_id, CURRENT_TIMESTAMP
    from contracts c
    inner join folder_groups fg
    on fg.folder_id = c.folder_id
    

    Note, this relies on the columns selected matching the order of the columns in statement

    UPDATE:

    As per comment, try:

    insert into contract_groups (contract_id, group_id, inserted_at)
    select distinct c.id, -- distinct added to prevent duplicates
                    fg.group_id, 
                    CURRENT_TIMESTAMP
    from contracts c
    inner join folder_groups fg
    on fg.folder_id = c.folder_id
    where not exists ( -- exclude any combos that are in the target table
                     select 1 
                     from contract_groups cg
                     where cg.contract_id = c.id
                     and fg.froup_id = cg.group_id
                     )