Sha256: 12df5c8dfc7b92e9bec27da6a7d79f6d5c60eab2a5d7112b7205b15d57bc47e9

Contents?: true

Size: 1.63 KB

Versions: 15

Compression:

Stored size: 1.63 KB

Contents

class Baza::Driver::Pg::Databases
  def initialize(args)
    @db = args.fetch(:db)
  end

  def current_database
    @db.databases[current_database_name]
  end

  def current_database_name
    @db.query("SELECT current_database()").fetch.values.first
  end

  def create(args)
    if args[:if_not_exists]
      begin
        __send__(:[], args.fetch(:name).to_s)
        return true
      # rubocop:disable Lint/HandleExceptions
      rescue Baza::Errors::DatabaseNotFound
        # rubocop:enable Lint/HandleExceptions
      end
    end

    @db.query("CREATE DATABASE #{@db.sep_database}#{@db.escape_table(args.fetch(:name))}#{@db.sep_database}")
    true
  end

  def [](name)
    database = list(name: name).first
    raise Baza::Errors::DatabaseNotFound unless database
    database
  end

  def list(args = {})
    where_args = {}
    where_args[:datname] = args.fetch(:name) if args[:name]

    database_list = [] unless block_given?
    @db.select(:pg_database, where_args) do |database_data|
      database = Baza::Driver::Pg::Database.new(
        db: @db,
        driver: @db.driver,
        name: database_data.fetch(:datname)
      )

      if database_list
        database_list << database
      else
        yield database
      end
    end

    database_list
  end

  def with_database(name)
    if @db.opts[:db].to_s == name
      yield if block_given?
      return self
    end

    previous_db_name = @db.current_database_name

    @db.opts[:db] = name
    @db.driver.reconnect

    if block_given?
      begin
        yield
      ensure
        @db.opts[:db] = previous_db_name
        @db.driver.reconnect
      end
    end

    self
  end
end

Version data entries

15 entries across 15 versions & 1 rubygems

Version Path
baza-0.0.35 lib/baza/driver/pg/databases.rb
baza-0.0.34 lib/baza/driver/pg/databases.rb
baza-0.0.33 lib/baza/driver/pg/databases.rb
baza-0.0.32 lib/baza/driver/pg/databases.rb
baza-0.0.31 lib/baza/driver/pg/databases.rb
baza-0.0.30 lib/baza/driver/pg/databases.rb
baza-0.0.29 lib/baza/driver/pg/databases.rb
baza-0.0.28 lib/baza/driver/pg/databases.rb
baza-0.0.27 lib/baza/driver/pg/databases.rb
baza-0.0.26 lib/baza/driver/pg/databases.rb
baza-0.0.25 lib/baza/driver/pg/databases.rb
baza-0.0.24 lib/baza/driver/pg/databases.rb
baza-0.0.23 lib/baza/driver/pg/databases.rb
baza-0.0.22 lib/baza/driver/pg/databases.rb
baza-0.0.21 lib/baza/driver/pg/databases.rb