Class: Baza::Driver::Mysql::Tables

Inherits:
Object
  • Object
show all
Defined in:
lib/baza/drivers/mysql/tables.rb

Overview

This class handels various MySQL-table-specific behaviour.

Constant Summary collapse

CREATE_ALLOWED_KEYS =
[:columns, :indexes, :temp, :return_sql]

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(args) ⇒ Tables

Constructor. This should not be called manually.



8
9
10
11
12
13
14
# File 'lib/baza/drivers/mysql/tables.rb', line 8

def initialize(args)
  @args = args
  @db = @args[:db]
  @list_mutex = Monitor.new
  @list = Wref::Map.new
  @list_should_be_reloaded = true
end

Instance Attribute Details

#dbObject (readonly)

Returns the value of attribute db.



5
6
7
# File 'lib/baza/drivers/mysql/tables.rb', line 5

def db
  @db
end

#list(args = {}) ⇒ Object (readonly)

Yields the tables of the current database.



37
38
39
# File 'lib/baza/drivers/mysql/tables.rb', line 37

def list
  @list
end

Instance Method Details

#[](table_name) ⇒ Object

Returns a table by the given table-name.



22
23
24
25
26
27
28
29
30
31
32
33
34
# File 'lib/baza/drivers/mysql/tables.rb', line 22

def [](table_name)
  table_name = table_name.to_s

  if table = @list[table_name]
    return table
  end

  list(name: table_name) do |table_i|
    return table_i if table_i.name == table_name
  end

  raise Baza::Errors::TableNotFound, "Table was not found: '#{table_name}'"
end

#cleanObject

Cleans the wref-map.



17
18
19
# File 'lib/baza/drivers/mysql/tables.rb', line 17

def clean
  @list.clean
end

#create(name, data, args = nil) ⇒ Object

Creates a new table by the given name and data.



80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
# File 'lib/baza/drivers/mysql/tables.rb', line 80

def create(name, data, args = nil)
  raise "No columns was given for '#{name}'." if !data[:columns] || data[:columns].empty?

  sql = "CREATE"
  sql << " TEMPORARY" if data[:temp]
  sql << " TABLE `#{name}` ("

  first = true
  data[:columns].each do |col_data|
    sql << ", " unless first
    first = false if first
    col_data.delete(:after) if col_data[:after]
    sql << @db.cols.data_sql(col_data)
  end

  if data[:indexes] && !data[:indexes].empty?
    sql << ", "
    sql << Baza::Driver::Mysql::Table.create_indexes(data[:indexes],         db: @db,
                                                                             return_sql: true,
                                                                             create: false,
                                                                             on_table: false,
                                                                             table_name: name)
  end

  sql << ")"

  return [sql] if args && args[:return_sql]
  @db.query(sql)
end