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

Adding define functions #427

Merged
merged 6 commits into from
Jul 27, 2020
Merged

Adding define functions #427

merged 6 commits into from
Jul 27, 2020

Conversation

jwoertink
Copy link
Member

This is a precursor to #393

This PR adds the ability to define postgres functions. By default I have made these trigger functions because I feel those may be the most common. A trigger function is a function that can only be called from a trigger. A trigger is just basically a callback in postgres.

Now, postgres functions can get super complicated real quick. There's a ton of possible options you can have, and all kinds of return types. What this PR does is gives you the ability to do some simple functions by providing you with some boilerplate. Beyond the simple ones you may need you can always use the execute() method in your migrations to hand roll your own complex functions.

The ability to define triggers will come in another PR.

def migrate
  # simple trigger function
  create_function "set_updated_at", <<-SQL
    IF NEW.updated_at IS NULL OR NEW.updated_at = OLD.updated_at THEN
      NEW.updated_at := now();
    END IF;
    RETURN NEW;
  SQL
end

def migrate
  # more complex example
  create_function "increment(i integer)", <<-SQL, returns: "integer"
    RETURN i + 1;
  SQL

  execute("SELECT increment(1)") #=> returns 2
end

Copy link
Member

@paulcsmith paulcsmith left a comment

Choose a reason for hiding this comment

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

Looks great!

@jwoertink jwoertink merged commit 29c03d6 into master Jul 27, 2020
@jwoertink jwoertink deleted the features/add_functions branch July 27, 2020 16:16
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.

None yet

2 participants