Sha256: a6c797f02a500006f2e852eb4d83ca6ade7a615c7aed06ec1f6534e10dcb8c34

Contents?: true

Size: 1.59 KB

Versions: 8

Compression:

Stored size: 1.59 KB

Contents

class Baza::Driver::Pg::Columns
  def initialize(args)
    @db = args.fetch(:db)
  end

  DATA_SQL_ALLOWED_KEYS = [:type, :maxlength, :name, :primarykey, :autoincr, :default, :comment, :after, :first, :storage, :null, :renames].freeze
  def data_sql(data)
    data.each_key do |key|
      raise "Invalid key: '#{key}' (#{key.class.name})." unless DATA_SQL_ALLOWED_KEYS.include?(key)
    end

    maxlength = data[:maxlength]

    raise "No type given." unless data[:type]
    type = data[:type].to_sym
    type = :timestamp if type == :datetime

    if type == :int && data[:autoincr]
      type = :serial
      maxlength = nil
    end

    if type == :int
      type = :integer
      maxlength = nil
    end

    if type == :tinyint
      type = :smallint
      maxlength = nil
    end

    data[:maxlength] = 255 if type == :varchar && !data.key?(:maxlength)

    sql = "#{@db.sep_col}#{@db.escape_column(data.fetch(:name))}#{@db.sep_col} #{type}"
    sql << "(#{maxlength})" if maxlength
    sql << " PRIMARY KEY" if data[:primarykey]
    sql << " NOT NULL" if data.key?(:null) && !data[:null]

    if data.key?(:default_func)
      sql << " DEFAULT #{data[:default_func]}"
    elsif data.key?(:default) && data[:default]
      sql << " DEFAULT #{@db.sqlval(data.fetch(:default))}"
    end

    sql << " COMMENT '#{@db.escape(data.fetch(:comment))}'" if data.key?(:comment)
    sql << " AFTER #{@db.sep_col}#{@db.escape_column(data.fetch(:after))}#{@db.sep_col}" if data[:after] && !data[:first]
    sql << " FIRST" if data[:first]
    sql << " STORAGE #{data[:storage].to_s.upcase}" if data[:storage]

    sql
  end
end

Version data entries

8 entries across 8 versions & 1 rubygems

Version Path
baza-0.0.35 lib/baza/driver/pg/columns.rb
baza-0.0.34 lib/baza/driver/pg/columns.rb
baza-0.0.33 lib/baza/driver/pg/columns.rb
baza-0.0.32 lib/baza/driver/pg/columns.rb
baza-0.0.31 lib/baza/driver/pg/columns.rb
baza-0.0.30 lib/baza/driver/pg/columns.rb
baza-0.0.29 lib/baza/driver/pg/columns.rb
baza-0.0.28 lib/baza/driver/pg/columns.rb