Sha256: fcf055cc2f1cc411ac730f925f494d2c75f55fd1c9f68367e7d116700a98bbe5

Contents?: true

Size: 1.34 KB

Versions: 15

Compression:

Stored size: 1.34 KB

Contents

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

  def create(args)
    sql = "CREATE DATABASE"
    sql << " IF NOT EXISTS" if args[:if_not_exists]
    sql << " #{@db.sep_database}#{@db.escape_table(args.fetch(:name))}#{@db.sep_database}"

    @db.query(sql)
    true
  end

  def [](name)
    name = name.to_s
    list.each do |database|
      return database if database.name == name
    end

    raise Baza::Errors::DatabaseNotFound
  end

  def list
    ArrayEnumerator.new do |yielder|
      @db.query("SHOW DATABASES") do |data|
        yielder << Baza::Driver::Mysql::Database.new(
          name: data.fetch(:Database),
          driver: self,
          db: @db
        )
      end
    end
  end

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

    previous_db_name = @db.current_database_name
    @db.query("USE #{@db.sep_database}#{@db.escape_database(name)}#{@db.sep_database}")

    if block_given?
      begin
        yield
      ensure
        @db.query("USE #{@db.sep_database}#{@db.escape_database(previous_db_name)}#{@db.sep_database}")
      end
    end

    self
  end

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

  def current_database
    @db.databases[current_database_name]
  end
end

Version data entries

15 entries across 15 versions & 1 rubygems

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