Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Use text templates to generate triggers #66

Merged
merged 3 commits into from
Aug 29, 2023
Merged

Conversation

andrew-farries
Copy link
Collaborator

Refactor the unwieldy Sprintf-based trigger generation code:

https://github.com/xataio/pg-roll/blob/main/pkg/migrations/triggers.go#L54-L78

With an equivalent approach that uses text templates:

package templates

const Function = `CREATE OR REPLACE FUNCTION {{ .Name | qi }}()
    RETURNS TRIGGER
    LANGUAGE PLPGSQL
    AS $$
    DECLARE
      {{- $schemaName := .SchemaName  }}
      {{- $tableName := .TableName  }}
      {{ range .Columns }} 
      {{- .Name | qi }} {{ $schemaName | qi }}.{{ $tableName | qi}}.{{ .Name | qi }}%TYPE := NEW.{{ .Name | qi }};
      {{ end -}}
      latest_schema text;
      search_path text;
    BEGIN
      SELECT {{ .SchemaName | ql }} || '_' || latest_version
        INTO latest_schema
        FROM {{ .StateSchema | qi }}.latest_version({{ .SchemaName | ql }});

      SELECT current_setting
        INTO search_path
        FROM current_setting('search_path');

      IF search_path {{- if eq .Direction "up" }} != {{- else }} = {{ end }} latest_schema {{ if .TestExpr  -}} AND {{ .TestExpr }} {{ end -}} THEN
        NEW.{{ .PhysicalColumn | qi  }} = {{ .SQL }};
      {{- if .ElseExpr }}
      ELSE
        {{ .ElseExpr }};
      {{- end }}
      END IF;

      RETURN NEW;
    END; $$
`

The templates are easier to read, easier to extend and result in cleaner triggers without oddities in indentation levels or empty ELSE blocks when no ElseExpr is provided.

This is in response to this comment.

@andrew-farries andrew-farries requested a review from exekias August 29, 2023 07:45
Copy link
Member

@exekias exekias left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🤩

Base automatically changed from set-not-null to main August 29, 2023 13:53
@andrew-farries andrew-farries merged commit a1e8b45 into main Aug 29, 2023
@andrew-farries andrew-farries deleted the use-text-template branch August 29, 2023 13:55
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants