Module: ActiveRecord::ConnectionAdapters::CockroachDB::SchemaStatements

Includes:
PostgreSQL::SchemaStatements
Included in:
ActiveRecord::ConnectionAdapters::CockroachDBAdapter
Defined in:
lib/active_record/connection_adapters/cockroachdb/schema_statements.rb

Instance Method Summary collapse

Instance Method Details

#add_index(table_name, column_name, options = {}) ⇒ Object



7
8
9
10
11
12
13
14
15
# File 'lib/active_record/connection_adapters/cockroachdb/schema_statements.rb', line 7

def add_index(table_name, column_name, options = {})
  super
rescue ActiveRecord::StatementInvalid => error
  if debugging? && error.cause.class == PG::FeatureNotSupported
    warn "#{error}\n\nThis error will be ignored and the index will not be created.\n\n"
  else
    raise error
  end
end

#default_sequence_name(table_name, pk = "id") ⇒ Object

CockroachDB uses unique_rowid() for primary keys, not sequences. It’s possible to force a table to use sequences, but since it’s not the default behavior we’ll always return nil for default_sequence_name.



38
39
40
# File 'lib/active_record/connection_adapters/cockroachdb/schema_statements.rb', line 38

def default_sequence_name(table_name, pk = "id")
  nil
end

#primary_key(table_name) ⇒ Object

ActiveRecord allows for tables to exist without primary keys. Databases like PostgreSQL support this behavior, but CockroachDB does not. If a table is created without a primary key, CockroachDB will add a rowid column to serve as its primary key. This breaks a lot of ActiveRecord’s assumptions so we’ll treat tables with rowid primary keys as if they didn’t have primary keys at all. www.cockroachlabs.com/docs/v19.2/create-table.html#create-a-table api.rubyonrails.org/v5.2.4/classes/ActiveRecord/ConnectionAdapters/SchemaStatements.html#method-i-create_table



25
26
27
28
29
30
31
32
33
# File 'lib/active_record/connection_adapters/cockroachdb/schema_statements.rb', line 25

def primary_key(table_name)
  pk = super

  if pk == CockroachDBAdapter::DEFAULT_PRIMARY_KEY
    nil
  else
    pk
  end
end

#type_to_sql(type, limit: nil, precision: nil, scale: nil, array: nil) ⇒ Object

CockroachDB will use INT8 if the SQL type is INTEGER, so we make it use INT4 explicitly when needed.



44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
# File 'lib/active_record/connection_adapters/cockroachdb/schema_statements.rb', line 44

def type_to_sql(type, limit: nil, precision: nil, scale: nil, array: nil, **) # :nodoc:
  sql = \
    case type.to_s
    when "integer"
      case limit
      when nil; "int"
      when 1, 2; "int2"
      when 3, 4; "int4"
      when 5..8; "int8"
      else super
      end
    else
      super
    end
  # The call to super might have appeneded [] already.
  if array && type != :primary_key && !sql.end_with?("[]")
    sql = "#{sql}[]" 
  end
  sql
end