Sha256: d01e858e2719039c56a889b202ec4bce1d3c9aa1fb9eb01b9792b727d4cbf7db

Contents?: true

Size: 843 Bytes

Versions: 6

Compression:

Stored size: 843 Bytes

Contents

# -- A basic table ----------------------------------------------------------

class MicroSql::Table
  attr :db, :table_name
  
  def initialize(db, sql)
    @db = db

    if sql !~ /\s/
      # no space: sql must be the table_name
      @table_name = sql
      raise "No such table: '#{@table_name}'" unless exists?
    elsif sql =~ /\s*CREATE TABLE\s+([^\( ]+)/
      @table_name = $1
      raise ArgumentError, "Cannot determine table_name from SQL: #{sql}" unless table_name
      build(sql) unless exists?
    end
  end

  def insert(*values)
    db.insert table_name, *values
  end

  def primary_key
    @primary_key ||= db.primary_key(table_name)
  end
  
  private

  def exists?
    db.tables.include?(table_name.to_s)
  end

  def build(sql)
    MicroSql.logger.info "Create table #{table_name}"
    db.execute_batch(sql)
  end
end

Version data entries

6 entries across 6 versions & 1 rubygems

Version Path
micro_sql-0.4.3 lib/micro_sql/table.rb
micro_sql-0.4.2 lib/micro_sql/table.rb
micro_sql-0.4.1 lib/micro_sql/table.rb
micro_sql-0.3.2 lib/micro_sql/table.rb
micro_sql-0.3.1 lib/micro_sql/table.rb
micro_sql-0.3.0 lib/micro_sql/table.rb