Module: DataMigrations::Setup

Defined in:
lib/data_migrations/setup.rb

Instance Method Summary collapse

Instance Method Details

#install_upsertObject



10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
# File 'lib/data_migrations/setup.rb', line 10

def install_upsert
  ActiveRecord::Base.connection.execute <<-sql
    CREATE FUNCTION upsert (sql_update TEXT, sql_insert TEXT)
        RETURNS VOID
        LANGUAGE plpgsql
    AS $$
    BEGIN
        LOOP
            -- first try to update
            EXECUTE sql_update;
            -- check if the row is found
            IF FOUND THEN
                RETURN;
            END IF;
            -- not found so insert the row
            BEGIN
                EXECUTE sql_insert;
                RETURN;
                EXCEPTION WHEN unique_violation THEN
                    -- do nothing and loop
            END;
        END LOOP;
    END;
    $$;
  sql
rescue ActiveRecord::StatementInvalid
  # ignore duplicate installs
end

#setup_data_migrationsObject



3
4
5
6
7
8
# File 'lib/data_migrations/setup.rb', line 3

def setup_data_migrations
  unless @setup
    install_upsert
    @setup = true
  end
end