activerecord-redshift-adapter 8.0.0 → 8.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (22) hide show
  1. checksums.yaml +4 -4
  2. data/lib/active_record/connection_adapters/redshift_8_0/schema_statements.rb +4 -3
  3. data/lib/active_record/connection_adapters/redshift_8_0_adapter.rb +17 -0
  4. data/lib/active_record/connection_adapters/redshift_8_1/array_parser.rb +92 -0
  5. data/lib/active_record/connection_adapters/redshift_8_1/column.rb +20 -0
  6. data/lib/active_record/connection_adapters/redshift_8_1/database_statements.rb +181 -0
  7. data/lib/active_record/connection_adapters/redshift_8_1/oid/date_time.rb +36 -0
  8. data/lib/active_record/connection_adapters/redshift_8_1/oid/decimal.rb +15 -0
  9. data/lib/active_record/connection_adapters/redshift_8_1/oid/json.rb +41 -0
  10. data/lib/active_record/connection_adapters/redshift_8_1/oid/jsonb.rb +25 -0
  11. data/lib/active_record/connection_adapters/redshift_8_1/oid/type_map_initializer.rb +62 -0
  12. data/lib/active_record/connection_adapters/redshift_8_1/oid.rb +17 -0
  13. data/lib/active_record/connection_adapters/redshift_8_1/quoting.rb +164 -0
  14. data/lib/active_record/connection_adapters/redshift_8_1/referential_integrity.rb +17 -0
  15. data/lib/active_record/connection_adapters/redshift_8_1/schema_definitions.rb +70 -0
  16. data/lib/active_record/connection_adapters/redshift_8_1/schema_dumper.rb +17 -0
  17. data/lib/active_record/connection_adapters/redshift_8_1/schema_statements.rb +423 -0
  18. data/lib/active_record/connection_adapters/redshift_8_1/type_metadata.rb +43 -0
  19. data/lib/active_record/connection_adapters/redshift_8_1/utils.rb +81 -0
  20. data/lib/active_record/connection_adapters/redshift_8_1_adapter.rb +858 -0
  21. data/lib/active_record/connection_adapters/redshift_adapter.rb +3 -1
  22. metadata +22 -7
@@ -0,0 +1,164 @@
1
+ # frozen_string_literal: true
2
+
3
+ module ActiveRecord
4
+ module ConnectionAdapters
5
+ module Redshift
6
+ module Quoting
7
+ extend ActiveSupport::Concern
8
+
9
+ module ClassMethods
10
+ QUOTED_COLUMN_NAMES = Concurrent::Map.new # :nodoc:
11
+ QUOTED_TABLE_NAMES = Concurrent::Map.new # :nodoc:
12
+
13
+ # Checks the following cases:
14
+ #
15
+ # - table_name
16
+ # - "table.name"
17
+ # - schema_name.table_name
18
+ # - schema_name."table.name"
19
+ # - "schema.name".table_name
20
+ # - "schema.name"."table.name"
21
+ def quote_table_name(name)
22
+ QUOTED_TABLE_NAMES[name] ||= Utils.extract_schema_qualified_name(name.to_s).quoted.freeze
23
+ end
24
+
25
+ # Quotes column names for use in SQL queries.
26
+ def quote_column_name(name) # :nodoc:
27
+ QUOTED_COLUMN_NAMES[name] ||= PG::Connection.quote_ident(name.to_s).freeze
28
+ end
29
+
30
+ def column_name_matcher
31
+ COLUMN_NAME
32
+ end
33
+
34
+ def column_name_with_order_matcher
35
+ COLUMN_NAME_WITH_ORDER
36
+ end
37
+
38
+ COLUMN_NAME = /
39
+ \A
40
+ (
41
+ (?:
42
+ # "schema_name"."table_name"."column_name"::type_name | function(one or no argument)::type_name
43
+ ((?:\w+\.|"\w+"\.){,2}(?:\w+|"\w+")(?:::\w+)? | \w+\((?:|\g<2>)\)(?:::\w+)?)
44
+ )
45
+ (?:(?:\s+AS)?\s+(?:\w+|"\w+"))?
46
+ )
47
+ (?:\s*,\s*\g<1>)*
48
+ \z
49
+ /ix
50
+
51
+ COLUMN_NAME_WITH_ORDER = /
52
+ \A
53
+ (
54
+ (?:
55
+ # "schema_name"."table_name"."column_name"::type_name | function(one or no argument)::type_name
56
+ ((?:\w+\.|"\w+"\.){,2}(?:\w+|"\w+")(?:::\w+)? | \w+\((?:|\g<2>)\)(?:::\w+)?)
57
+ )
58
+ (?:\s+COLLATE\s+"\w+")?
59
+ (?:\s+ASC|\s+DESC)?
60
+ (?:\s+NULLS\s+(?:FIRST|LAST))?
61
+ )
62
+ (?:\s*,\s*\g<1>)*
63
+ \z
64
+ /ix
65
+
66
+ private_constant :COLUMN_NAME, :COLUMN_NAME_WITH_ORDER
67
+ end
68
+
69
+ # Escapes binary strings for bytea input to the database.
70
+ def escape_bytea(value)
71
+ valid_raw_connection.escape_bytea(value) if value
72
+ end
73
+
74
+ # Unescapes bytea output from a database to the binary string it represents.
75
+ # NOTE: This is NOT an inverse of escape_bytea! This is only to be used
76
+ # on escaped binary output from database drive.
77
+ def unescape_bytea(value)
78
+ valid_raw_connection.unescape_bytea(value) if value
79
+ end
80
+
81
+ # Quotes strings for use in SQL input.
82
+ def quote_string(s) # :nodoc:
83
+ with_raw_connection(allow_retry: true, materialize_transactions: false) do |connection|
84
+ connection.escape(s)
85
+ end
86
+ end
87
+
88
+ def quote_table_name_for_assignment(_table, attr)
89
+ quote_column_name(attr)
90
+ end
91
+
92
+ # Quotes schema names for use in SQL queries.
93
+ def quote_schema_name(name)
94
+ PG::Connection.quote_ident(name)
95
+ end
96
+
97
+ # Quote date/time values for use in SQL input.
98
+ def quoted_date(value) # :nodoc:
99
+ if value.year <= 0
100
+ bce_year = format("%04d", -value.year + 1)
101
+ super.sub(/^-?\d+/, bce_year) + " BC"
102
+ else
103
+ super
104
+ end
105
+ end
106
+
107
+ def quoted_binary(value) # :nodoc:
108
+ "'#{escape_bytea(value.to_s)}'"
109
+ end
110
+
111
+ # Does not quote function default values for UUID columns
112
+ def quote_default_value(value, column) # :nodoc:
113
+ if column.type == :uuid && value =~ /\(\)/
114
+ value
115
+ else
116
+ quote(value, column)
117
+ end
118
+ end
119
+
120
+ def quote(value)
121
+ case value
122
+ when Numeric
123
+ if value.finite?
124
+ super
125
+ else
126
+ "'#{value}'"
127
+ end
128
+ when Type::Binary::Data
129
+ "'#{escape_bytea(value.to_s)}'"
130
+ else
131
+ super
132
+ end
133
+ end
134
+
135
+ def quote_default_expression(value, column) # :nodoc:
136
+ if value.is_a?(Proc)
137
+ value.call
138
+ elsif column.type == :uuid && value.is_a?(String) && value.include?("()")
139
+ value # Does not quote function default values for UUID columns
140
+ else
141
+ super
142
+ end
143
+ end
144
+
145
+ def type_cast(value)
146
+ case value
147
+ when Type::Binary::Data
148
+ # Return a bind param hash with format as binary.
149
+ # See http://deveiate.org/code/pg/PGconn.html#method-i-exec_prepared-doc
150
+ # for more information
151
+ { value: value.to_s, format: 1 }
152
+ else
153
+ super
154
+ end
155
+ end
156
+
157
+ def lookup_cast_type_from_column(column) # :nodoc:
158
+ verify! if type_map.nil?
159
+ type_map.lookup(column.oid, column.fmod, column.sql_type)
160
+ end
161
+ end
162
+ end
163
+ end
164
+ end
@@ -0,0 +1,17 @@
1
+ # frozen_string_literal: true
2
+
3
+ module ActiveRecord
4
+ module ConnectionAdapters
5
+ module Redshift
6
+ module ReferentialIntegrity # :nodoc:
7
+ def supports_disable_referential_integrity? # :nodoc:
8
+ true
9
+ end
10
+
11
+ def disable_referential_integrity # :nodoc:
12
+ yield
13
+ end
14
+ end
15
+ end
16
+ end
17
+ end
@@ -0,0 +1,70 @@
1
+ # frozen_string_literal: true
2
+
3
+ module ActiveRecord
4
+ module ConnectionAdapters
5
+ module Redshift
6
+ module ColumnMethods
7
+ # Defines the primary key field.
8
+ # Use of the native PostgreSQL UUID type is supported, and can be used
9
+ # by defining your tables as such:
10
+ #
11
+ # create_table :stuffs, id: :uuid do |t|
12
+ # t.string :content
13
+ # t.timestamps
14
+ # end
15
+ #
16
+ # By default, this will use the +uuid_generate_v4()+ function from the
17
+ # +uuid-ossp+ extension, which MUST be enabled on your database. To enable
18
+ # the +uuid-ossp+ extension, you can use the +enable_extension+ method in your
19
+ # migrations. To use a UUID primary key without +uuid-ossp+ enabled, you can
20
+ # set the +:default+ option to +nil+:
21
+ #
22
+ # create_table :stuffs, id: false do |t|
23
+ # t.primary_key :id, :uuid, default: nil
24
+ # t.uuid :foo_id
25
+ # t.timestamps
26
+ # end
27
+ #
28
+ # You may also pass a different UUID generation function from +uuid-ossp+
29
+ # or another library.
30
+ #
31
+ # Note that setting the UUID primary key default value to +nil+ will
32
+ # require you to assure that you always provide a UUID value before saving
33
+ # a record (as primary keys cannot be +nil+). This might be done via the
34
+ # +SecureRandom.uuid+ method and a +before_save+ callback, for instance.
35
+ def primary_key(name, type = :primary_key, **options)
36
+ return super unless type == :uuid
37
+
38
+ options[:default] = options.fetch(:default, 'uuid_generate_v4()')
39
+ options[:primary_key] = true
40
+ column name, type, options
41
+ end
42
+
43
+ def json(name, **options)
44
+ column(name, :json, options)
45
+ end
46
+
47
+ def jsonb(name, **options)
48
+ column(name, :jsonb, options)
49
+ end
50
+ end
51
+
52
+ class ColumnDefinition < ActiveRecord::ConnectionAdapters::ColumnDefinition
53
+ end
54
+
55
+ class TableDefinition < ActiveRecord::ConnectionAdapters::TableDefinition
56
+ include ColumnMethods
57
+
58
+ private
59
+
60
+ def create_column_definition(*args)
61
+ Redshift::ColumnDefinition.new(*args)
62
+ end
63
+ end
64
+
65
+ class Table < ActiveRecord::ConnectionAdapters::Table
66
+ include ColumnMethods
67
+ end
68
+ end
69
+ end
70
+ end
@@ -0,0 +1,17 @@
1
+ # frozen_string_literal: true
2
+
3
+ module ActiveRecord
4
+ module ConnectionAdapters
5
+ module Redshift
6
+ module ColumnDumper
7
+ # Adds +:array+ option to the default set provided by the
8
+ # AbstractAdapter
9
+ def prepare_column_options(column) # :nodoc:
10
+ spec = super
11
+ spec[:default] = "\"#{column.default_function}\"" if column.default_function
12
+ spec
13
+ end
14
+ end
15
+ end
16
+ end
17
+ end
@@ -0,0 +1,423 @@
1
+ # frozen_string_literal: true
2
+
3
+ module ActiveRecord
4
+ module ConnectionAdapters
5
+ module Redshift
6
+ class SchemaCreation < SchemaCreation
7
+ private
8
+
9
+ def visit_ColumnDefinition(o)
10
+ o.sql_type = type_to_sql(o.type, limit: o.limit, precision: o.precision, scale: o.scale)
11
+ super
12
+ end
13
+
14
+ def add_column_options!(sql, options)
15
+ column = options.fetch(:column) { return super }
16
+ if column.type == :uuid && options[:default] =~ /\(\)/
17
+ sql << " DEFAULT #{options[:default]}"
18
+ else
19
+ super
20
+ end
21
+ end
22
+ end
23
+
24
+ module SchemaStatements
25
+ # Drops the database specified on the +name+ attribute
26
+ # and creates it again using the provided +options+.
27
+ def recreate_database(name, options = {}) # :nodoc:
28
+ drop_database(name)
29
+ create_database(name, options)
30
+ end
31
+
32
+ # Create a new Redshift database. Options include <tt>:owner</tt>, <tt>:template</tt>,
33
+ # <tt>:encoding</tt> (defaults to utf8), <tt>:collation</tt>, <tt>:ctype</tt>,
34
+ # <tt>:tablespace</tt>, and <tt>:connection_limit</tt> (note that MySQL uses
35
+ # <tt>:charset</tt> while Redshift uses <tt>:encoding</tt>).
36
+ #
37
+ # Example:
38
+ # create_database config[:database], config
39
+ # create_database 'foo_development', encoding: 'unicode'
40
+ def create_database(name, options = {})
41
+ options = { encoding: 'utf8' }.merge!(options.symbolize_keys)
42
+
43
+ option_string = options.inject('') do |memo, (key, value)|
44
+ next memo unless key == :owner
45
+
46
+ memo + " OWNER = \"#{value}\""
47
+ end
48
+
49
+ execute "CREATE DATABASE #{quote_table_name(name)}#{option_string}"
50
+ end
51
+
52
+ # Drops a Redshift database.
53
+ #
54
+ # Example:
55
+ # drop_database 'matt_development'
56
+ def drop_database(name) # :nodoc:
57
+ execute "DROP DATABASE #{quote_table_name(name)}"
58
+ end
59
+
60
+ # Returns an array of table names defined in the database.
61
+ def tables
62
+ select_values('SELECT tablename FROM pg_tables WHERE schemaname = ANY(current_schemas(false))', 'SCHEMA')
63
+ end
64
+
65
+ # :nodoc
66
+ def data_sources
67
+ select_values(<<-SQL, 'SCHEMA')
68
+ SELECT c.relname
69
+ FROM pg_class c
70
+ LEFT JOIN pg_namespace n ON n.oid = c.relnamespace
71
+ WHERE c.relkind IN ('r', 'v','m') -- (r)elation/table, (v)iew, (m)aterialized view
72
+ AND n.nspname = ANY (current_schemas(false))
73
+ SQL
74
+ end
75
+
76
+ # Returns true if table exists.
77
+ # If the schema is not specified as part of +name+ then it will only find tables within
78
+ # the current schema search path (regardless of permissions to access tables in other schemas)
79
+ def table_exists?(name)
80
+ name = Utils.extract_schema_qualified_name(name.to_s)
81
+ return false unless name.identifier
82
+
83
+ select_value(<<-SQL, 'SCHEMA').to_i > 0
84
+ SELECT COUNT(*)
85
+ FROM pg_class c
86
+ LEFT JOIN pg_namespace n ON n.oid = c.relnamespace
87
+ WHERE c.relkind = 'r' -- (r)elation/table
88
+ AND c.relname = '#{name.identifier}'
89
+ AND n.nspname = #{name.schema ? "'#{name.schema}'" : 'ANY (current_schemas(false))'}
90
+ SQL
91
+ end
92
+
93
+ def data_source_exists?(name)
94
+ name = Utils.extract_schema_qualified_name(name.to_s)
95
+ return false unless name.identifier
96
+
97
+ select_value(<<-SQL, 'SCHEMA').to_i > 0
98
+ SELECT COUNT(*)
99
+ FROM pg_class c
100
+ LEFT JOIN pg_namespace n ON n.oid = c.relnamespace
101
+ WHERE c.relkind IN ('r','v','m') -- (r)elation/table, (v)iew, (m)aterialized view
102
+ AND c.relname = '#{name.identifier}'
103
+ AND n.nspname = #{name.schema ? "'#{name.schema}'" : 'ANY (current_schemas(false))'}
104
+ SQL
105
+ end
106
+
107
+ def views # :nodoc:
108
+ select_values(<<-SQL, 'SCHEMA')
109
+ SELECT c.relname
110
+ FROM pg_class c
111
+ LEFT JOIN pg_namespace n ON n.oid = c.relnamespace
112
+ WHERE c.relkind IN ('v','m') -- (v)iew, (m)aterialized view
113
+ AND n.nspname = ANY (current_schemas(false))
114
+ SQL
115
+ end
116
+
117
+ def view_exists?(view_name) # :nodoc:
118
+ name = Utils.extract_schema_qualified_name(view_name.to_s)
119
+ return false unless name.identifier
120
+
121
+ select_values(<<-SQL, 'SCHEMA').any?
122
+ SELECT c.relname
123
+ FROM pg_class c
124
+ LEFT JOIN pg_namespace n ON n.oid = c.relnamespace
125
+ WHERE c.relkind IN ('v','m') -- (v)iew, (m)aterialized view
126
+ AND c.relname = '#{name.identifier}'
127
+ AND n.nspname = #{name.schema ? "'#{name.schema}'" : 'ANY (current_schemas(false))'}
128
+ SQL
129
+ end
130
+
131
+ def drop_table(table_name, **options)
132
+ execute "DROP TABLE#{' IF EXISTS' if options[:if_exists]} #{quote_table_name(table_name)}#{' CASCADE' if options[:force] == :cascade}"
133
+ end
134
+
135
+ # Returns true if schema exists.
136
+ def schema_exists?(name)
137
+ select_value("SELECT COUNT(*) FROM pg_namespace WHERE nspname = '#{name}'", 'SCHEMA').to_i > 0
138
+ end
139
+
140
+ def index_name_exists?(_table_name, _index_name)
141
+ false
142
+ end
143
+
144
+ # Returns an array of indexes for the given table.
145
+ def indexes(_table_name)
146
+ []
147
+ end
148
+
149
+ # Returns the list of all column definitions for a table.
150
+ def columns(table_name)
151
+ column_definitions(table_name.to_s).map do |column_name, type, default, notnull, oid, fmod|
152
+ default_value = extract_value_from_default(default)
153
+ type_metadata = fetch_type_metadata(column_name, type, oid, fmod)
154
+ default_function = extract_default_function(default_value, default)
155
+ cast_type = get_oid_type(oid.to_i, fmod.to_i, column_name, type)
156
+ new_column(column_name, default_value, type_metadata, !notnull, table_name, default_function, cast_type: cast_type)
157
+ end
158
+ end
159
+
160
+ def new_column(name, default, sql_type_metadata = nil, null = true, _table_name = nil, default_function = nil, cast_type: nil) # :nodoc:
161
+ RedshiftColumn.new(name, default, sql_type_metadata, null, default_function, cast_type: cast_type)
162
+ end
163
+
164
+ # Returns the current database name.
165
+ def current_database
166
+ select_value('select current_database()', 'SCHEMA')
167
+ end
168
+
169
+ # Returns the current schema name.
170
+ def current_schema
171
+ select_value('SELECT current_schema', 'SCHEMA')
172
+ end
173
+
174
+ # Returns the current database encoding format.
175
+ def encoding
176
+ select_value(
177
+ "SELECT pg_encoding_to_char(encoding) FROM pg_database WHERE datname LIKE '#{current_database}'", 'SCHEMA'
178
+ )
179
+ end
180
+
181
+ def collation; end
182
+
183
+ def ctype; end
184
+
185
+ # Returns an array of schema names.
186
+ def schema_names
187
+ select_values(<<-SQL, 'SCHEMA')
188
+ SELECT nspname
189
+ FROM pg_namespace
190
+ WHERE nspname !~ '^pg_.*'
191
+ AND nspname NOT IN ('information_schema')
192
+ ORDER by nspname;
193
+ SQL
194
+ end
195
+
196
+ # Creates a schema for the given schema name.
197
+ def create_schema(schema_name)
198
+ execute "CREATE SCHEMA #{quote_schema_name(schema_name)}"
199
+ end
200
+
201
+ # Drops the schema for the given schema name.
202
+ def drop_schema(schema_name, **options)
203
+ execute "DROP SCHEMA#{' IF EXISTS' if options[:if_exists]} #{quote_schema_name(schema_name)} CASCADE"
204
+ end
205
+
206
+ # Sets the schema search path to a string of comma-separated schema names.
207
+ # Names beginning with $ have to be quoted (e.g. $user => '$user').
208
+ # See: http://www.postgresql.org/docs/current/static/ddl-schemas.html
209
+ #
210
+ # This should be not be called manually but set in database.yml.
211
+ def schema_search_path=(schema_csv)
212
+ return unless schema_csv
213
+
214
+ execute("SET search_path TO #{schema_csv}", 'SCHEMA')
215
+ @schema_search_path = schema_csv
216
+ end
217
+
218
+ # Returns the active schema search path.
219
+ def schema_search_path
220
+ @schema_search_path ||= select_value('SHOW search_path', 'SCHEMA')
221
+ end
222
+
223
+ # Returns the sequence name for a table's primary key or some other specified key.
224
+ def default_sequence_name(table_name, pk = 'id') # :nodoc:
225
+ result = serial_sequence(table_name, pk)
226
+ return nil unless result
227
+
228
+ Utils.extract_schema_qualified_name(result).to_s
229
+ rescue ActiveRecord::StatementInvalid
230
+ Redshift::Name.new(nil, "#{table_name}_#{pk}_seq").to_s
231
+ end
232
+
233
+ def serial_sequence(table, column)
234
+ select_value("SELECT pg_get_serial_sequence(#{quote(table)}, #{quote(column)})".tap { puts _1 }, 'SCHEMA')
235
+ end
236
+
237
+ def set_pk_sequence!(table, value); end
238
+
239
+ def reset_pk_sequence!(table, pk = nil, sequence = nil); end
240
+
241
+ def pk_and_sequence_for(_table) # :nodoc:
242
+ [nil, nil]
243
+ end
244
+
245
+ # Returns just a table's primary key
246
+ def primary_keys(table)
247
+ pks = query(<<-END_SQL, 'SCHEMA')
248
+ SELECT DISTINCT attr.attname
249
+ FROM pg_attribute attr
250
+ INNER JOIN pg_depend dep ON attr.attrelid = dep.refobjid AND attr.attnum = dep.refobjsubid
251
+ INNER JOIN pg_constraint cons ON attr.attrelid = cons.conrelid AND attr.attnum = any(cons.conkey)
252
+ WHERE cons.contype = 'p'
253
+ AND dep.refobjid = '#{quote_table_name(table)}'::regclass
254
+ END_SQL
255
+ pks.present? ? pks[0] : pks
256
+ end
257
+
258
+ # Renames a table.
259
+ # Also renames a table's primary key sequence if the sequence name exists and
260
+ # matches the Active Record default.
261
+ #
262
+ # Example:
263
+ # rename_table('octopuses', 'octopi')
264
+ def rename_table(table_name, new_name, **options)
265
+ validate_table_length!(new_name) unless options[:_uses_legacy_table_name]
266
+ clear_cache!
267
+ execute "ALTER TABLE #{quote_table_name(table_name)} RENAME TO #{quote_table_name(new_name)}"
268
+ end
269
+
270
+ def add_column(table_name, column_name, type, **options) # :nodoc:
271
+ clear_cache!
272
+ super
273
+ end
274
+
275
+ # Changes the column of a table.
276
+ def change_column(table_name, column_name, type, **options)
277
+ clear_cache!
278
+ quoted_table_name = quote_table_name(table_name)
279
+ sql_type = type_to_sql(type, limit: options[:limit], precision: options[:precision], scale: options[:scale])
280
+ sql = "ALTER TABLE #{quoted_table_name} ALTER COLUMN #{quote_column_name(column_name)} TYPE #{sql_type}"
281
+ sql << " USING #{options[:using]}" if options[:using]
282
+ if options[:cast_as]
283
+ sql << " USING CAST(#{quote_column_name(column_name)} AS #{type_to_sql(options[:cast_as],
284
+ limit: options[:limit], precision: options[:precision], scale: options[:scale])})"
285
+ end
286
+ execute sql
287
+
288
+ change_column_default(table_name, column_name, options[:default]) if options_include_default?(options)
289
+ change_column_null(table_name, column_name, options[:null], options[:default]) if options.key?(:null)
290
+ end
291
+
292
+ # Changes the default value of a table column.
293
+ def change_column_default(table_name, column_name, default_or_changes)
294
+ clear_cache!
295
+ column = column_for(table_name, column_name)
296
+ return unless column
297
+
298
+ default = extract_new_default_value(default_or_changes)
299
+ alter_column_query = "ALTER TABLE #{quote_table_name(table_name)} ALTER COLUMN #{quote_column_name(column_name)} %s"
300
+ if default.nil?
301
+ # <tt>DEFAULT NULL</tt> results in the same behavior as <tt>DROP DEFAULT</tt>. However, PostgreSQL will
302
+ # cast the default to the columns type, which leaves us with a default like "default NULL::character varying".
303
+ execute alter_column_query % 'DROP DEFAULT'
304
+ else
305
+ execute alter_column_query % "SET DEFAULT #{quote_default_value(default, column)}"
306
+ end
307
+ end
308
+
309
+ def change_column_null(table_name, column_name, null, default = nil)
310
+ clear_cache!
311
+ unless null || default.nil?
312
+ column = column_for(table_name, column_name)
313
+ if column
314
+ execute("UPDATE #{quote_table_name(table_name)} SET #{quote_column_name(column_name)}=#{quote_default_value(
315
+ default, column
316
+ )} WHERE #{quote_column_name(column_name)} IS NULL")
317
+ end
318
+ end
319
+ execute("ALTER TABLE #{quote_table_name(table_name)} ALTER #{quote_column_name(column_name)} #{null ? 'DROP' : 'SET'} NOT NULL")
320
+ end
321
+
322
+ # Renames a column in a table.
323
+ def rename_column(table_name, column_name, new_column_name) # :nodoc:
324
+ clear_cache!
325
+ execute "ALTER TABLE #{quote_table_name(table_name)} RENAME COLUMN #{quote_column_name(column_name)} TO #{quote_column_name(new_column_name)}"
326
+ end
327
+
328
+ def add_index(table_name, column_name, **options); end
329
+
330
+ def remove_index!(table_name, index_name); end
331
+
332
+ def rename_index(table_name, old_name, new_name); end
333
+
334
+ def foreign_keys(table_name)
335
+ fk_info = select_all(<<-SQL.strip_heredoc, 'SCHEMA')
336
+ SELECT t2.relname AS to_table, a1.attname AS column, a2.attname AS primary_key, c.conname AS name, c.confupdtype AS on_update, c.confdeltype AS on_delete
337
+ FROM pg_constraint c
338
+ JOIN pg_class t1 ON c.conrelid = t1.oid
339
+ JOIN pg_class t2 ON c.confrelid = t2.oid
340
+ JOIN pg_attribute a1 ON a1.attnum = c.conkey[1] AND a1.attrelid = t1.oid
341
+ JOIN pg_attribute a2 ON a2.attnum = c.confkey[1] AND a2.attrelid = t2.oid
342
+ JOIN pg_namespace t3 ON c.connamespace = t3.oid
343
+ WHERE c.contype = 'f'
344
+ AND t1.relname = #{quote(table_name)}
345
+ AND t3.nspname = ANY (current_schemas(false))
346
+ ORDER BY c.conname
347
+ SQL
348
+
349
+ fk_info.map do |row|
350
+ options = {
351
+ column: row['column'],
352
+ name: row['name'],
353
+ primary_key: row['primary_key']
354
+ }
355
+
356
+ options[:on_delete] = extract_foreign_key_action(row['on_delete'])
357
+ options[:on_update] = extract_foreign_key_action(row['on_update'])
358
+
359
+ ForeignKeyDefinition.new(table_name, row['to_table'], options)
360
+ end
361
+ end
362
+
363
+ FOREIGN_KEY_ACTIONS = {
364
+ 'c' => :cascade,
365
+ 'n' => :nullify,
366
+ 'r' => :restrict
367
+ }.freeze
368
+
369
+ def extract_foreign_key_action(specifier)
370
+ FOREIGN_KEY_ACTIONS[specifier]
371
+ end
372
+
373
+ def index_name_length
374
+ 63
375
+ end
376
+
377
+ # Maps logical Rails types to PostgreSQL-specific data types.
378
+ def type_to_sql(type, limit: nil, precision: nil, scale: nil, **)
379
+ case type.to_s
380
+ when 'integer'
381
+ return 'integer' unless limit
382
+
383
+ case limit
384
+ when 1, 2 then 'smallint'
385
+ when nil, 3, 4 then 'integer'
386
+ when 5..8 then 'bigint'
387
+ else raise(ActiveRecordError,
388
+ "No integer type has byte size #{limit}. Use a numeric with precision 0 instead.")
389
+ end
390
+ else
391
+ super
392
+ end
393
+ end
394
+
395
+ # PostgreSQL requires the ORDER BY columns in the select list for distinct queries, and
396
+ # requires that the ORDER BY include the distinct column.
397
+ def columns_for_distinct(columns, orders) # :nodoc:
398
+ order_columns = orders.compact_blank.map { |s|
399
+ # Convert Arel node to string
400
+ s = visitor.compile(s) unless s.is_a?(String)
401
+ # Remove any ASC/DESC modifiers
402
+ s.gsub(/\s+(?:ASC|DESC)\b/i, "")
403
+ .gsub(/\s+NULLS\s+(?:FIRST|LAST)\b/i, "")
404
+ }.compact_blank.map.with_index { |column, i| "#{column} AS alias_#{i}" }
405
+
406
+ (order_columns << super).join(", ")
407
+ end
408
+
409
+ def fetch_type_metadata(column_name, sql_type, oid, fmod)
410
+ cast_type = get_oid_type(oid.to_i, fmod.to_i, column_name, sql_type)
411
+ simple_type = SqlTypeMetadata.new(
412
+ sql_type: sql_type,
413
+ type: cast_type.type,
414
+ limit: cast_type.limit,
415
+ precision: cast_type.precision,
416
+ scale: cast_type.scale
417
+ )
418
+ TypeMetadata.new(simple_type, oid: oid, fmod: fmod)
419
+ end
420
+ end
421
+ end
422
+ end
423
+ end