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

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

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



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

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



81
82
83
84
85
86
87
# File 'lib/baza/driver/sqlite3/table.rb', line 81

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



89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
# File 'lib/baza/driver/sqlite3/table.rb', line 89

def columns
  @db.columns
  ret = []

  @db.query("PRAGMA table_info(`#{@db.escape_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



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

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



130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
# File 'lib/baza/driver/sqlite3/table.rb', line 130

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 do |name, _col|
    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



120
121
122
123
124
125
126
127
128
# File 'lib/baza/driver/sqlite3/table.rb', line 120

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



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
354
355
356
357
358
359
# File 'lib/baza/driver/sqlite3/table.rb', line 320

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.sep_index}#{@db.escape_column(index_name)}#{@db.sep_index} ON #{@db.sep_table}#{@db.escape_table(name)}#{@db.sep_table} ("

    first = true
    index_data.fetch(:columns).each do |col_name|
      sql << ", " unless first
      first = false if first
      sql << "#{@db.sep_col}#{@db.escape_column(col_name)}#{@db.sep_col}"
    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



361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
# File 'lib/baza/driver/sqlite3/table.rb', line 361

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.



32
33
34
35
36
# File 'lib/baza/driver/sqlite3/table.rb', line 32

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

#index(index_name) ⇒ Object



259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
# File 'lib/baza/driver/sqlite3/table.rb', line 259

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



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

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

  @db.query("PRAGMA index_list(`#{@db.escape_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



379
380
381
# File 'lib/baza/driver/sqlite3/table.rb', line 379

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

#inspectObject



387
388
389
# File 'lib/baza/driver/sqlite3/table.rb', line 387

def inspect
  to_s
end

#maxlengthObject



15
16
17
# File 'lib/baza/driver/sqlite3/table.rb', line 15

def maxlength
  @data.fetch(:maxlength)
end

#native?Boolean

Returns true if the table is safe to drop.

Returns:

  • (Boolean)


39
40
41
42
# File 'lib/baza/driver/sqlite3/table.rb', line 39

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

#optimizeObject



44
45
46
# File 'lib/baza/driver/sqlite3/table.rb', line 44

def optimize
  # Not possible in SQLite3.
end

#reloadObject



19
20
21
22
23
24
# File 'lib/baza/driver/sqlite3/table.rb', line 19

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



48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
# File 'lib/baza/driver/sqlite3/table.rb', line 48

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 do |_name, column|
    column.args[:table_name] = newname
  end

  @indexes_list.each do |_name, index|
    index.args[:table_name] = newname
  end
end

#rows_countObject



26
27
28
29
# File 'lib/baza/driver/sqlite3/table.rb', line 26

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

#tableObject



77
78
79
# File 'lib/baza/driver/sqlite3/table.rb', line 77

def table
  @db.tables[@table_name]
end

#to_sObject



383
384
385
# File 'lib/baza/driver/sqlite3/table.rb', line 383

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

#truncateObject

Drops the table and creates it again



70
71
72
73
74
75
# File 'lib/baza/driver/sqlite3/table.rb', line 70

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