Class: MotionRecord::Schema::ColumnDefinition

Inherits:
Object
  • Object
show all
Defined in:
lib/motion_record/schema/column_definition.rb

Constant Summary collapse

TYPE_MAP =
{
  :integer => "INTEGER",
  :text    => "TEXT",
  :float   => "REAL"
}
INVERSE_TYPE_MAP =
{
  "INTEGER" => :integer,
  "TEXT"    => :text,
  "REAL"    => :float
}

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(type, name, options) ⇒ ColumnDefinition

name - name of the column type - a Symbol representing the column type options - Hash of constraints for the column:

:primary - set to true to configure as the primary auto-incrementing key
:null - set to false to add a "NOT NULL" constraint
:default - TODO


25
26
27
28
29
# File 'lib/motion_record/schema/column_definition.rb', line 25

def initialize(type, name, options)
  @type = type.to_sym
  @name = name.to_sym
  @options = options
end

Instance Attribute Details

#nameObject (readonly)

Returns the value of attribute name.



16
17
18
# File 'lib/motion_record/schema/column_definition.rb', line 16

def name
  @name
end

#optionsObject (readonly)

Returns the value of attribute options.



17
18
19
# File 'lib/motion_record/schema/column_definition.rb', line 17

def options
  @options
end

#typeObject (readonly)

Returns the value of attribute type.



15
16
17
# File 'lib/motion_record/schema/column_definition.rb', line 15

def type
  @type
end

Class Method Details

.from_pragma(pragma) ⇒ Object

Build a new ColumnDefinition from the result of a “PRAGMA table_info()” query

pragma - Hash representing a row of the query’s result:

:cid - column index
:name - column name
:type - column type
:notnull - integer flag for "NOT NULL"
:dflt_value - default value
:pk - integer flag for primary key

Returns the new ColumnDefinition



51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
# File 'lib/motion_record/schema/column_definition.rb', line 51

def self.from_pragma(pragma)
  type = INVERSE_TYPE_MAP[pragma[:type]]
  options = {
    :null    => (pragma[:notnull] != 1),
    :primary => (pragma[:pk] == 1),
    :default => (pragma[:dflt_value])
  }

  if options[:default]
    case type
    when :integer
      options[:default] = options[:default].to_i
    when :float
      options[:default] = options[:default].to_f
    end
  end

  self.new(type, pragma[:name], options)
end

Instance Method Details

#defaultObject



35
36
37
# File 'lib/motion_record/schema/column_definition.rb', line 35

def default
  @options[:default]
end

#to_sql_definitionObject



31
32
33
# File 'lib/motion_record/schema/column_definition.rb', line 31

def to_sql_definition
  [@name, sql_type, sql_options].compact.join(" ")
end