Sha256: 4351d3a2ea63c3d14a3544d2fd65dd2d388f32aae5145e01e7879de28e5e4210

Contents?: true

Size: 1005 Bytes

Versions: 1

Compression:

Stored size: 1005 Bytes

Contents

module DataMigrations
  module Setup
    def setup_data_migrations
      unless @setup
        install_upsert
        @setup = true
      end
    end

    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
  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
data_migrations-0.0.1 lib/data_migrations/setup.rb