Sha256: 4f17b04c3aecb8a95e87b437c10765c28691f1e2d72074d673f8c98c01779674

Contents?: true

Size: 1.42 KB

Versions: 1

Compression:

Stored size: 1.42 KB

Contents

require 'sequel'
module Proxy
  module ContainerGateway
    class Database
      attr_reader :connection

      def initialize(connection_string, prior_sqlite_db_path = nil)
        @connection = Sequel.connect(connection_string)
        if connection_string.start_with?('sqlite://')
          @connection.run("PRAGMA foreign_keys = ON;")
          @connection.run("PRAGMA journal_mode = wal;")
        elsif prior_sqlite_db_path && File.exist?(prior_sqlite_db_path) &&
              (!@connection.table_exists?(:repositories) || @connection[:repositories].count.zero?)
          migrate_to_postgres(Sequel.sqlite(prior_sqlite_db_path), @connection)
          File.delete(prior_sqlite_db_path)
        end
        migrate
      end

      private

      def migrate
        Sequel.extension :migration, :core_extensions
        migration_path = File.join(__dir__, 'sequel_migrations')
        begin
          Sequel::Migrator.check_current(@connection, migration_path)
        rescue Sequel::Migrator::NotCurrentError
          Sequel::Migrator.run(@connection, migration_path)
        end
      end

      def migrate_to_postgres(sqlite_db, postgres_db)
        migrate
        sqlite_db.transaction do
          sqlite_db.tables.each do |table|
            next if table == :schema_info

            sqlite_db[table].each do |row|
              postgres_db[table.to_sym].insert(row)
            end
          end
        end
      end
    end
  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
smart_proxy_container_gateway-3.1.0 lib/smart_proxy_container_gateway/database.rb