Class: Baza::Driver::Sqlite3::Table

Inherits:
Table
  • Object
show all
Defined in:
lib/baza/driver/sqlite3/table.rb

Overview

rubocop:disable Metrics/ClassLength

Direct Known Subclasses

Baza::Driver::Sqlite3Java::Table

Instance Attribute Summary collapse

Attributes inherited from Table

#db

Instance Method Summary collapse

Methods inherited from Table

#<=>, #row, #rows, #to_param, #upsert_duplicate_key

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
12
13
# File 'lib/baza/driver/sqlite3/table.rb', line 4

def initialize(args)
  @db = args.fetch(:db)
  @data = args.fetch(:data)
  @name = @data.fetch(:name)
  @type = @data.fetch(:type).to_sym
  @tables = args.fetch(:tables)

  @list = Wref::Map.new
  @indexes_list = Wref::Map.new
end

Instance Attribute Details

#nameObject (readonly)

Returns the value of attribute name.



2
3
4
# File 'lib/baza/driver/sqlite3/table.rb', line 2

def name
  @name
end

#typeObject (readonly)

Returns the value of attribute type.



2
3
4
# File 'lib/baza/driver/sqlite3/table.rb', line 2

def type
  @type
end

Instance Method Details

#clone(newname, args = nil) ⇒ Object



200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
# File 'lib/baza/driver/sqlite3/table.rb', line 200

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

  sql = "CREATE TABLE `#{newname}` ("
  first = true
  columns.each do |col|
    sql << ", " unless first
    first = false if first
    sql << @db.columns.data_sql(col.data)
  end
  sql << ");"

  @db.query(sql)
  @db.query("INSERT INTO `#{newname}` SELECT * FROM `#{name}`")

  indexes_to_create = []
  new_table = @db.tables[newname.to_sym]
  indexes.each do |index|
    index_name = index.name.gsub(/\A#{Regexp.escape(name)}_/, "")

    if @db.opts[:index_append_table_name] && (match = index_name.match(/\A(.+?)__(.+)\Z/))
      index_name = match[2]
    else
      # Two indexes with the same name can't exist, and we are cloning, so we need to change the name
      index_name = "#{newname}_#{index_name}"
    end

    create_data = index.data
    create_data[:name] = index_name

    indexes_to_create << create_data
  end

  new_table.create_indexes(indexes_to_create)

  if args && args[:return_table] == false
    return nil
  else
    return new_table
  end
end

#column(name) ⇒ Object



116
117
118
119
120
121
122
# File 'lib/baza/driver/sqlite3/table.rb', line 116

def column(name)
  columns do |column|
    return column if column.name == name.to_s
  end

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

#columnsObject



124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
# File 'lib/baza/driver/sqlite3/table.rb', line 124

def columns
  @db.columns
  ret = []

  @db.query("PRAGMA table_info(#{@db.quote_table(name)})") do |d_cols|
    column_name = d_cols.fetch(:name)
    obj = @list.get(column_name)

    unless obj
      obj = Baza::Driver::Sqlite3::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

#copy(args = {}) ⇒ Object



242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
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
# File 'lib/baza/driver/sqlite3/table.rb', line 242

def copy(args = {})
  temp_name = "temptable_#{Time.now.to_f.to_s.hash}"
  clone(temp_name)
  cols_cur = columns
  @db.query("DROP TABLE `#{name}`")

  sql = "CREATE TABLE `#{name}` ("
  first = true
  cols_cur.each do |col|
    next if args[:drops] && args[:drops].to_s.include?(col.name)

    sql << ", " unless first
    first = false if first

    if args.key?(:alter_columns) && args[:alter_columns][col.name]
      sql << @db.columns.data_sql(args[:alter_columns][col.name])
    else
      sql << @db.columns.data_sql(col.data)
    end

    next unless args[:new]
    args[:new].each do |col_data|
      if col_data[:after] && col_data[:after] == col.name
        sql << ", #{@db.columns.data_sql(col_data)}"
      end
    end
  end

  sql << ");"
  @db.query(sql)

  sql = "INSERT INTO `#{name}` SELECT "
  first = true
  cols_cur.each do |col|
    next if args[:drops] && args[:drops].to_s.include?(col.name)

    sql << ", " unless first
    first = false if first

    sql << "`#{col.name}`"

    next unless args[:news]
    args[:news].each do |col_data|
      sql << ", ''" if col_data[:after] && col_data[:after] == col.name
    end
  end

  sql << " FROM `#{temp_name}`"
  @db.query(sql)
  @db.query("DROP TABLE `#{temp_name}`")
end

#create_column_programmatic(col_data) ⇒ Object



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
# File 'lib/baza/driver/sqlite3/table.rb', line 165

def create_column_programmatic(col_data)
  temp_name = "temptable_#{Time.now.to_f.to_s.hash}"
  clone(temp_name)
  cols_cur = columns
  @db.query("DROP TABLE `#{name}`")

  sql = "CREATE TABLE `#{name}` ("
  first = true
  cols_cur.each do |name, col|
    sql << ", " unless first
    first = false if first
    sql << @db.columns.data_sql(col.data)

    if col_data[:after] && col_data[:after] == name
      sql << ", #{@db.columns.data_sql(col_data)}"
    end
  end
  sql << ");"
  @db.query(sql)

  sql = "INSERT INTO `#{self.name}` SELECT "
  first = true
  cols_cur.each_key do |name|
    sql << ", " unless first
    first = false if first

    sql << "`#{name}`"

    sql << ", ''" if col_data[:after] && col_data[:after] == name
  end
  sql << " FROM `#{temp_name}`"
  @db.query(sql)
  @db.query("DROP TABLE `#{temp_name}`")
end

#create_columns(col_arr) ⇒ Object



155
156
157
158
159
160
161
162
163
# File 'lib/baza/driver/sqlite3/table.rb', line 155

def create_columns(col_arr)
  col_arr.each do |col_data|
    # if col_data.key?("after")
    #  self.create_column_programmatic(col_data)
    # else
    @db.query("ALTER TABLE `#{name}` ADD COLUMN #{@db.columns.data_sql(col_data)};")
    # end
  end
end

#create_indexes(index_arr, args = nil) ⇒ Object



355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
# File 'lib/baza/driver/sqlite3/table.rb', line 355

def create_indexes(index_arr, args = nil)
  ret = [] if args && args[:return_sql]

  index_arr.each do |index_data|
    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 in data: '#{index_data}'." if !index_data.key?(:name) || index_data[:name].to_s.strip.empty?
    raise "No columns was given on index #{index_data[:name]}." if !index_data[:columns] || index_data[:columns].empty?

    index_name = index_data.fetch(:name).to_s
    index_name = "#{name}__#{index_name}" if @db.opts[:index_append_table_name] && !index_name.start_with?("#{name}__")

    sql = "CREATE"
    sql << " UNIQUE" if index_data[:unique]
    sql << " INDEX #{@db.quote_index(index_name)} ON #{@db.quote_table(name)} ("

    first = true
    index_data.fetch(:columns).each do |col_name|
      sql << ", " unless first
      first = false if first
      sql << @db.quote_column(col_name)
    end

    sql << ")"

    if args && args[:return_sql]
      ret << sql
    else
      @db.query(sql)
    end
  end

  if args && args[:return_sql]
    return ret
  else
    return nil
  end
end

#dataObject



396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
# File 'lib/baza/driver/sqlite3/table.rb', line 396

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

Drops the table from the database.



67
68
69
70
71
# File 'lib/baza/driver/sqlite3/table.rb', line 67

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

#foreign_keysObject



15
16
17
18
19
20
21
22
23
# File 'lib/baza/driver/sqlite3/table.rb', line 15

def foreign_keys
  db.query("PRAGMA foreign_key_list('#{name}')").map do |foreign_key_data|
    data = foreign_key_data.clone
    data[:referenced_table] = data.fetch(:table)
    data[:table] = name

    Baza::Driver::Sqlite3::ForeignKey.new(db: db, data: data)
  end
end

#index(index_name) ⇒ Object



294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
# File 'lib/baza/driver/sqlite3/table.rb', line 294

def index(index_name)
  index_name = index_name.to_s

  if (index = @indexes_list[index_name])
    return index
  end

  if @db.opts[:index_append_table_name]
    tryname = "#{name}__#{index_name}"

    if (index = @indexes_list[tryname])
      return index
    end
  end

  indexes do |index_i|
    return index_i if index_i.name == "#{name}__#{index_name}"
    return index_i if index_i.name == index_name
  end

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

#indexesObject



317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
# File 'lib/baza/driver/sqlite3/table.rb', line 317

def indexes
  @db.indexes
  ret = [] unless block_given?

  @db.query("PRAGMA index_list(#{@db.quote_table(name)})") do |d_indexes|
    next if d_indexes[:Key_name] == "PRIMARY"
    obj = @indexes_list.get(d_indexes[:name])

    unless obj
      obj = Baza::Driver::Sqlite3::Index.new(
        table_name: name,
        db: @db,
        data: d_indexes
      )

      @indexes_list[d_indexes[:name].to_sym] = obj

      # Get columns from index.
      index_master_data = @db.single(:sqlite_master, type: "index", name: d_indexes[:name])
      parse_columns_from_sql(index_master_data[:sql]).each do |column|
        obj.columns << column
      end
    end

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

  if block_given?
    return nil
  else
    return ret
  end
end

#insert(data, args = {}) ⇒ Object



414
415
416
# File 'lib/baza/driver/sqlite3/table.rb', line 414

def insert(data, args = {})
  @db.insert(name, data, args)
end

#inspectObject



422
423
424
# File 'lib/baza/driver/sqlite3/table.rb', line 422

def inspect
  to_s
end

#maxlengthObject



50
51
52
# File 'lib/baza/driver/sqlite3/table.rb', line 50

def maxlength
  @data.fetch(:maxlength)
end

#native?Boolean

Returns true if the table is safe to drop.

Returns:

  • (Boolean)


74
75
76
77
# File 'lib/baza/driver/sqlite3/table.rb', line 74

def native?
  return true if name.to_s == "sqlite_sequence"
  false
end

#optimizeObject



79
80
81
# File 'lib/baza/driver/sqlite3/table.rb', line 79

def optimize
  # Not possible in SQLite3.
end

#referenced_foreign_keysObject



25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
# File 'lib/baza/driver/sqlite3/table.rb', line 25

def referenced_foreign_keys
  sql = "
    SELECT
      sqlite_master.name,
      pragma_join.*

    FROM
      sqlite_master

    JOIN pragma_foreign_key_list(sqlite_master.name) pragma_join ON
      pragma_join.\"table\" != sqlite_master.name

    WHERE sqlite_master.type = 'table'
    ORDER BY sqlite_master.name
  "

  db.query(sql).map do |foreign_key_data|
    data = foreign_key_data.clone
    data[:referenced_table] = data.fetch(:table)
    data[:table] = data.fetch(:name)

    Baza::Driver::Sqlite3::ForeignKey.new(db: db, data: data)
  end
end

#reloadObject



54
55
56
57
58
59
# File 'lib/baza/driver/sqlite3/table.rb', line 54

def reload
  data = @db.select("sqlite_master", {type: "table", name: name}, orderby: "name").fetch
  raise Baza::Errors::TableNotFound unless data
  @data = data
  self
end

#rename(newname) ⇒ Object



83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
# File 'lib/baza/driver/sqlite3/table.rb', line 83

def rename(newname)
  newname = newname.to_s

  @tables.remove_from_list(self)
  newtable = clone(newname)
  @db.tables.remove_from_list(newtable)
  drop
  @data[:name] = newname
  @name = newname
  @tables.add_to_list(self)

  # Rename table on all columns and indexes.
  @list.each_value do |column|
    column.args[:table_name] = newname
  end

  @indexes_list.each_value do |index|
    index.args[:table_name] = newname
  end
end

#rows_countObject



61
62
63
64
# File 'lib/baza/driver/sqlite3/table.rb', line 61

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

#tableObject



112
113
114
# File 'lib/baza/driver/sqlite3/table.rb', line 112

def table
  @db.tables[@table_name]
end

#to_sObject



418
419
420
# File 'lib/baza/driver/sqlite3/table.rb', line 418

def to_s
  "#<Baza::Driver::Sqlite3::Table name: \"#{name}\">"
end

#truncateObject

Drops the table and creates it again



105
106
107
108
109
110
# File 'lib/baza/driver/sqlite3/table.rb', line 105

def truncate
  table_data = data.clone
  drop
  @db.tables.create(table_data.delete(:name), **table_data)
  self
end