Class: Baza::Driver::Mysql::Sql::CreateTable

Inherits:
Object
  • Object
show all
Defined in:
lib/baza/driver/mysql/sql/create_table.rb

Instance Method Summary collapse

Constructor Details

#initialize(args) ⇒ CreateTable

Returns a new instance of CreateTable.



2
3
4
5
6
7
# File 'lib/baza/driver/mysql/sql/create_table.rb', line 2

def initialize(args)
  @name = args.fetch(:name)
  @columns = args.fetch(:columns)
  @indexes = args[:indexes]
  @temporary = args[:temporary]
end

Instance Method Details

#sqlObject



9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
# File 'lib/baza/driver/mysql/sql/create_table.rb', line 9

def sql
  sql = "CREATE"
  sql << " TEMPORARY" if @temporary
  sql << " TABLE #{Baza::Driver::Mysql.quote_table(@name)} ("

  first = true
  @columns.each do |col_data|
    sql << ", " unless first
    first = false if first

    col_data = col_data.clone
    col_data.delete(:after) if col_data[:after]
    col_data.delete(:foreign_key)

    sql << Baza::Driver::Mysql::Sql::Column.new(col_data).sql.first
  end

  if @indexes && !@indexes.empty?
    sql << ", "
    sql << Baza::Driver::Mysql::Sql::CreateIndexes.new(
      indexes: @indexes,
      create: false,
      on_table: false,
      table_name: @name
    ).sql.first
  end

  @columns.each do |col_data|
    next unless col_data.key?(:foreign_key)

    sql << ","
    sql << " CONSTRAINT `#{col_data.fetch(:foreign_key).fetch(:name)}`" if col_data.fetch(:foreign_key)[:name]
    sql << " FOREIGN KEY (`#{col_data.fetch(:name)}`) REFERENCES `#{col_data.fetch(:foreign_key).fetch(:to).fetch(0)}` (`#{col_data.fetch(:foreign_key).fetch(:to).fetch(1)}`)"
  end

  sql << ")"

  [sql]
end