Class: Baza::Driver::Mysql::Databases

Inherits:
Object
  • Object
show all
Defined in:
lib/baza/driver/mysql/databases.rb

Instance Method Summary collapse

Constructor Details

#initialize(args) ⇒ Databases

Returns a new instance of Databases.



2
3
4
# File 'lib/baza/driver/mysql/databases.rb', line 2

def initialize(args)
  @db = args.fetch(:db)
end

Instance Method Details

#[](name) ⇒ Object



15
16
17
18
19
20
21
22
# File 'lib/baza/driver/mysql/databases.rb', line 15

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

  raise Baza::Errors::DatabaseNotFound
end

#create(args) ⇒ Object



6
7
8
9
10
11
12
13
# File 'lib/baza/driver/mysql/databases.rb', line 6

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

#current_databaseObject



60
61
62
# File 'lib/baza/driver/mysql/databases.rb', line 60

def current_database
  @db.databases[current_database_name]
end

#current_database_nameObject



56
57
58
# File 'lib/baza/driver/mysql/databases.rb', line 56

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

#listObject



24
25
26
27
28
29
30
31
32
33
34
# File 'lib/baza/driver/mysql/databases.rb', line 24

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

#with_database(name) ⇒ Object



36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
# File 'lib/baza/driver/mysql/databases.rb', line 36

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