Class: Migsupo::Parser::TableDslContext

Inherits:
Object
  • Object
show all
Defined in:
lib/migsupo/parser/table_dsl_context.rb

Constant Summary collapse

COLUMN_TYPES =
%i[
  string text integer bigint float decimal boolean
  date datetime time timestamp binary blob json jsonb
  uuid hstore inet cidr macaddr bit varbit
  virtual primary_key
].freeze

Instance Method Summary collapse

Constructor Details

#initialize(table_name, options = {}) ⇒ TableDslContext

Returns a new instance of TableDslContext.



15
16
17
18
19
20
# File 'lib/migsupo/parser/table_dsl_context.rb', line 15

def initialize(table_name, options = {})
  @table_name = table_name.to_s
  @options    = options
  @columns    = []
  @indexes    = []
end

Instance Method Details

#column(name, type, **opts) ⇒ Object



28
29
30
# File 'lib/migsupo/parser/table_dsl_context.rb', line 28

def column(name, type, **opts)
  add_column(name, type, opts)
end

#index(columns, **opts) ⇒ Object



62
63
64
# File 'lib/migsupo/parser/table_dsl_context.rb', line 62

def index(columns, **opts)
  add_index_entry(Array(columns).map(&:to_s), opts)
end

#references(name, **opts) ⇒ Object Also known as: belongs_to



32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
# File 'lib/migsupo/parser/table_dsl_context.rb', line 32

def references(name, **opts)
  polymorphic = opts.delete(:polymorphic)
  index_opt   = opts.delete(:index) { true }
  foreign_key = opts.delete(:foreign_key)

  col_type = opts.delete(:type) { :bigint }
  add_column("#{name}_id", col_type, opts)

  if polymorphic
    add_column("#{name}_type", :string, {})
    if index_opt
      add_index_entry([@table_name, "#{name}_type", "#{name}_id"],
                      name: "index_#{@table_name}_on_#{name}_type_and_#{name}_id")
    end
  elsif index_opt
    idx_opts = index_opt.is_a?(Hash) ? index_opt : {}
    add_index_entry(["#{name}_id"], idx_opts)
  end
end

#timestamps(**opts) ⇒ Object



54
55
56
57
58
59
60
# File 'lib/migsupo/parser/table_dsl_context.rb', line 54

def timestamps(**opts)
  precision = opts.fetch(:precision, nil)
  col_opts  = precision ? { precision: precision } : {}
  col_opts[:null] = opts[:null] if opts.key?(:null)
  add_column("created_at", :datetime, col_opts)
  add_column("updated_at", :datetime, col_opts)
end

#to_table_definitionObject



66
67
68
69
70
71
72
73
# File 'lib/migsupo/parser/table_dsl_context.rb', line 66

def to_table_definition
  Schema::TableDefinition.new(
    name:    @table_name,
    columns: @columns,
    indexes: @indexes,
    options: @options
  )
end