Class: Baza::Table

Inherits:
Object
  • Object
show all
Includes:
DatabaseModelFunctionality, Comparable
Defined in:
lib/baza/table.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Methods included from DatabaseModelFunctionality

#model_name, #to_model

Instance Attribute Details

#dbObject (readonly)

Returns the value of attribute db.



5
6
7
# File 'lib/baza/table.rb', line 5

def db
  @db
end

Instance Method Details

#<=>(other) ⇒ Object



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

def <=>(other)
  return false unless other.is_a?(Baza::Table)
  return false unless other.db.opts.fetch(:db) == db.opts.fetch(:db)
  other.name <=> name
end

#create_columns(col_arr) ⇒ Object



61
62
63
64
65
66
# File 'lib/baza/table.rb', line 61

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

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



37
38
39
# File 'lib/baza/table.rb', line 37

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

#inspectObject



11
12
13
# File 'lib/baza/table.rb', line 11

def inspect
  to_s
end

#row(id) ⇒ Object



27
28
29
30
31
# File 'lib/baza/table.rb', line 27

def row(id)
  row = rows({id: id}, limit: 1).first
  raise Baza::Errors::RowNotFound unless row
  row
end

#rows(*args) ⇒ Object



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

def rows(*args)
  ArrayEnumerator.new do |yielder|
    db.select(name, *args) do |data|
      yielder << Baza::Row.new(
        db: db,
        table: name,
        data: data
      )
    end
  end
end

#rows_countObject



45
46
47
48
# File 'lib/baza/table.rb', line 45

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

#to_paramObject



33
34
35
# File 'lib/baza/table.rb', line 33

def to_param
  name
end

#to_sObject



7
8
9
# File 'lib/baza/table.rb', line 7

def to_s
  "#<#{self.class.name} name=\"#{name}\">"
end

#truncateObject



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

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

#upsert_duplicate_key(data, terms = {}, args = {}) ⇒ Object



41
42
43
# File 'lib/baza/table.rb', line 41

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