kind: Table
name: secrets
columns:
  ref:
    type: text
    nullable: false
  encrypted_secret:
    type: text
    nullable: true
indexes:
  secrets_pkey:
    on:
      - column: ref
    primary_key: true
    unique: true
---
kind: Table
name: unencrypted_secrets
columns:
  ref:
    type: text
    nullable: false
  unencrypted_secret:
    type: text
    nullable: false
foreign_keys:
  - on:
      - ref
    references:
      table: secrets
      columns:
        - ref
indexes:
  unencrypted_secrets_pkey:
    unique: true
    primary_key: true
    on:
      - column: ref
triggers:
  after_insert:
    - name: encrypt_unencrypted_secret
      language: plpgsql
      for_each: row
      order: 1
      body: |
        begin
          perform graphile_worker.add_job(
            'encrypt-secret', 
            json_build_object('ref', NEW.ref)
          );
          return NEW;
        end;
---
kind: Test
name: inserting into unencrypted secrets should create an encrypt job
setup: |
  insert into secrets (ref)
  values ('my-secret');

  insert into unencrypted_secrets (ref, unencrypted_secret)
  values ('my-secret', 'unencrypted');
assertions:
  - name: should have a job in graphile_worker.jobs
    return: select count(*) from graphile_worker.jobs
    expect: "1"
---
kind: Function
name: set_secret
arguments:
  - name: secret_ref
    type: text
  - name: unencrypted_secret
    type: text
returns: text
language: plpgsql
volatility: volatile
security: definer
body: |
  begin
    insert into secrets (ref)
    values (set_secret.secret_ref)
    on conflict (ref) do nothing;

    insert into unencrypted_secrets (ref, unencrypted_secret)
    values (set_secret.secret_ref, set_secret.unencrypted_secret);

    return secret_ref;
  end;
