Class: Baza::Driver::Mysql::Table

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

Instance Attribute Summary collapse

Attributes inherited from Table

#db

Class Method Summary collapse

Instance Method Summary collapse

Methods inherited from Table

#inspect, #row, #rows, #to_param, #to_s

Methods included from Baza::DatabaseModelFunctionality

#model_name, #to_model

Constructor Details

#initialize(args) ⇒ Table

Returns a new instance of Table.



4
5
6
7
8
9
10
11
# File 'lib/baza/drivers/mysql/table.rb', line 4

def initialize(args)
  @db = args.fetch(:db)
  @data = args.fetch(:data)
  @list = Wref::Map.new
  @indexes_list = Wref::Map.new
  @name = @data.fetch(:name)
  @tables = args.fetch(:tables)
end

Instance Attribute Details

#listObject (readonly)

Returns the value of attribute list.



2
3
4
# File 'lib/baza/drivers/mysql/table.rb', line 2

def list
  @list
end

#nameObject (readonly)

Returns the value of attribute name.



2
3
4
# File 'lib/baza/drivers/mysql/table.rb', line 2

def name
  @name
end

Class Method Details

.create_indexes(index_arr, args = {}) ⇒ Object



158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
# File 'lib/baza/drivers/mysql/table.rb', line 158

def self.create_indexes(index_arr, args = {})
  db = args[:db]

  if args[:return_sql]
    sql = ""
    first = true
  end

  index_arr.each do |index_data|
    sql = "" unless args[:return_sql]

    sql << "CREATE" if args[:create] || !args.key?(:create)

    if index_data.is_a?(String) || index_data.is_a?(Symbol)
      index_data = {name: index_data, columns: [index_data]}
    end

    raise "No name was given: '#{index_data}'." if !index_data.key?(:name) || index_data[:name].to_s.strip.empty?
    raise "No columns was given on index: '#{index_data.fetch(:name)}'." if !index_data[:columns] || index_data[:columns].empty?

    if args[:return_sql]
      if first
        first = false
      else
        sql << ", "
      end
    end

    sql << " UNIQUE" if index_data[:unique]
    sql << " INDEX `#{db.escape_column(index_data.fetch(:name))}`"

    if args[:on_table] || !args.key?(:on_table)
      sql << " ON `#{db.escape_table(args.fetch(:table_name))}`"
    end

    sql << " ("

    first = true
    index_data[:columns].each do |col_name|
      sql << ", " unless first
      first = false if first

      sql << "`#{db.escape_column(col_name)}`"
    end

    sql << ")"

    db.query(sql) unless args[:return_sql]
  end

  sql if args[:return_sql]
end

Instance Method Details

#__object_unique_id__Object

Used to validate in Wref::Map.



21
22
23
# File 'lib/baza/drivers/mysql/table.rb', line 21

def __object_unique_id__
  name
end

#clone(newname, args = {}) ⇒ Object



258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
# File 'lib/baza/drivers/mysql/table.rb', line 258

def clone(newname, args = {})
  raise "Invalid name." if newname.to_s.strip.empty?

  sql = "CREATE TABLE `#{@db.escape_table(newname)}` ("
  first = true
  pkey_found = false
  pkeys = []

  columns do |col|
    sql << ", " unless first
    first = false if first

    col_data = col.data
    pkey_found = true if !pkey_found && col_data[:primarykey] && args[:force_single_pkey]

    if args[:no_pkey] || (pkey_found && col_data[:primarykey] && args[:force_single_pkey])
      col_data[:primarykey] = false
    end

    if col_data[:primarykey]
      pkeys << col_data[:name]
      col_data.delete(:primarykey)
    end

    col_data[:storage] = args[:all_cols_storage] if args[:all_cols_storage]

    sql << @db.cols.data_sql(col_data)
  end

  unless pkeys.empty?
    sql << ", PRIMARY KEY ("

    first = true
    pkeys.each do |pkey|
      sql << ", " unless first
      first = false if first
      sql << "`#{@db.escape_column(pkey)}`"
    end

    sql << ")"
  end

  sql << ")"
  sql << " TABLESPACE #{args[:tablespace]}" if args[:tablespace]
  sql << " ENGINE=#{args[:engine]}" if args[:engine]
  sql << ";"

  # Create table.
  @db.query(sql)


  # Insert data of previous data in a single query.
  @db.query("INSERT INTO `#{@db.escape_table(newname)}` SELECT * FROM `#{@db.escape_table(name)}`")


  # Create indexes.
  new_table = @db.tables[newname]
  indexes_list = []
  indexes do |index|
    indexes_list << index.data unless index.primary?
  end

  new_table.create_indexes(indexes_list)


  # Return new table.
  new_table
end

#column(name) ⇒ Object



48
49
50
51
52
53
54
55
56
57
58
59
60
# File 'lib/baza/drivers/mysql/table.rb', line 48

def column(name)
  name = name.to_s

  if col = @list.get(name)
    return @list[name]
  end

  columns(name: name) do |col_i|
    return col_i if col_i.name == name
  end

  raise Baza::Errors::ColumnNotFound, "Column not found: '#{name}'"
end

#columns(args = nil) ⇒ Object



62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
# File 'lib/baza/drivers/mysql/table.rb', line 62

def columns(args = nil)
  @db.cols
  ret = []
  sql = "SHOW FULL COLUMNS FROM `#{@db.escape_table(name)}`"
  sql << " WHERE `Field` = '#{@db.esc(args.fetch(:name))}'" if args && args.key?(:name)

  @db.q(sql) do |d_cols|
    column_name = d_cols.fetch(:Field)
    obj = @list.get(name)

    unless obj
      obj = Baza::Driver::Mysql::Column.new(
        table_name: name,
        db: @db,
        data: d_cols
      )
      @list[column_name] = obj
    end

    if block_given?
      yield obj
    else
      ret << obj
    end
  end

  if block_given?
    return nil
  else
    return ret
  end
end

#create_columns(col_arr) ⇒ Object



145
146
147
148
149
150
151
152
# File 'lib/baza/drivers/mysql/table.rb', line 145

def create_columns(col_arr)
  @db.transaction do
    col_arr.each do |col_data|
      sql = "ALTER TABLE `#{name}` ADD COLUMN #{@db.cols.data_sql(col_data)};"
      @db.query(sql)
    end
  end
end

#create_indexes(index_arr, args = {}) ⇒ Object



154
155
156
# File 'lib/baza/drivers/mysql/table.rb', line 154

def create_indexes(index_arr, args = {})
  Baza::Driver::Mysql::Table.create_indexes(index_arr, args.merge(table_name: name, db: @db))
end

#dataObject



236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
# File 'lib/baza/drivers/mysql/table.rb', line 236

def data
  ret = {
    name: name,
    columns: [],
    indexes: []
  }

  columns do |column|
    ret[:columns] << column.data
  end

  indexes do |index|
    ret[:indexes] << index.data unless index.name == "PRIMARY"
  end

  ret
end

#dropObject



25
26
27
28
29
30
# File 'lib/baza/drivers/mysql/table.rb', line 25

def drop
  raise "Cant drop native table: '#{name}'." if self.native?
  @db.query("DROP TABLE `#{@db.escape_table(name)}`")
  @tables.__send__(:remove_from_list, self)
  nil
end

#engineObject

Returns the current engine of the table.



328
329
330
# File 'lib/baza/drivers/mysql/table.rb', line 328

def engine
  @data[:engine]
end

#engine=(newengine) ⇒ Object

Changes the engine for a table.



333
334
335
336
337
# File 'lib/baza/drivers/mysql/table.rb', line 333

def engine=(newengine)
  raise "Invalid engine: '#{newengine}'." unless newengine.to_s.match(/^[A-z]+$/)
  @db.query("ALTER TABLE `#{@db.escape_table(name)}` ENGINE = #{newengine}") if engine.to_s != newengine.to_s
  @data[:engine] = newengine
end

#index(name) ⇒ Object



131
132
133
134
135
136
137
138
139
140
141
142
143
# File 'lib/baza/drivers/mysql/table.rb', line 131

def index(name)
  name = name.to_s

  if index = @indexes_list.get(name)
    return index
  end

  indexes(name: name) do |index_i|
    return index_i if index_i.name == name
  end

  raise Baza::Errors::IndexNotFound, "Index not found: #{name}."
end

#indexes(args = nil) ⇒ Object



95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
# File 'lib/baza/drivers/mysql/table.rb', line 95

def indexes(args = nil)
  @db.indexes
  ret = []

  sql = "SHOW INDEX FROM `#{@db.escape_table(name)}`"
  sql << " WHERE `Key_name` = '#{@db.esc(args.fetch(:name))}'" if args && args.key?(:name)

  @db.query(sql) do |d_indexes|
    next if d_indexes[:Key_name] == "PRIMARY"
    index_name = d_indexes.fetch(:Key_name)
    obj = @indexes_list.get(index_name)

    unless obj
      obj = Baza::Driver::Mysql::Index.new(
        table_name: name,
        db: @db,
        data: d_indexes
      )
      obj.columns << d_indexes.fetch(:Column_name)
      @indexes_list[index_name] = obj
    end

    if block_given?
      yield obj
    else
      ret << obj
    end
  end

  if block_given?
    return nil
  else
    return ret
  end
end

#insert(data) ⇒ Object



254
255
256
# File 'lib/baza/drivers/mysql/table.rb', line 254

def insert(data)
  @db.insert(name, data)
end

#native?Boolean

Returns true if the table is safe to drop.

Returns:

  • (Boolean)


33
34
35
36
37
# File 'lib/baza/drivers/mysql/table.rb', line 33

def native?
  data = @db.q("SELECT DATABASE() AS db").fetch
  return true if data.fetch(:db) == "mysql"
  false
end

#optimizeObject



39
40
41
42
# File 'lib/baza/drivers/mysql/table.rb', line 39

def optimize
  @db.query("OPTIMIZE TABLE `#{@db.escape_table(name)}`")
  self
end

#reloadObject



13
14
15
16
17
18
# File 'lib/baza/drivers/mysql/table.rb', line 13

def reload
  data = @db.q("SHOW TABLE STATUS WHERE `Name` = '#{@db.esc(name)}'").fetch
  raise Baza::Errors::TableNotFound unless data
  @data = data
  self
end

#rename(newname) ⇒ Object



211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
# File 'lib/baza/drivers/mysql/table.rb', line 211

def rename(newname)
  newname = newname.to_s
  oldname = name

  @tables.__send__(:remove_from_list, self)
  @db.query("ALTER TABLE `#{@db.escape_table(oldname)}` RENAME TO `#{@db.escape_table(newname)}`")

  @data[:name] = newname
  @name = newname
  @tables.__send__(:add_to_list, self)

  @list.each do |_name, column|
    column.args[:table_name] = newname
  end

  @indexes_list.each do |_name, index|
    index.table_name = newname
  end
end

#rows_countObject



44
45
46
# File 'lib/baza/drivers/mysql/table.rb', line 44

def rows_count
  @db.query("SELECT COUNT(*) AS count FROM `#{@db.escape_table(name)}`").fetch.fetch(:count).to_i
end

#truncateObject



231
232
233
234
# File 'lib/baza/drivers/mysql/table.rb', line 231

def truncate
  @db.query("TRUNCATE `#{@db.escape_table(name)}`")
  self
end