instance method
unique_constraints
Ruby on Rails 8.1.2
Since v7.1.6Signature
unique_constraints(table_name)
Returns an array of unique constraints for the given table. The unique constraints are represented as UniqueConstraintDefinition objects.
Parameters
-
table_namereq
Source
# File activerecord/lib/active_record/connection_adapters/postgresql/schema_statements.rb, line 726
def unique_constraints(table_name)
scope = quoted_scope(table_name)
unique_info = internal_exec_query(<<~SQL, "SCHEMA", allow_retry: true, materialize_transactions: false)
SELECT c.conname, c.conrelid, c.condeferrable, c.condeferred, pg_get_constraintdef(c.oid) AS constraintdef,
(
SELECT array_agg(a.attname ORDER BY idx)
FROM (
SELECT idx, c.conkey[idx] AS conkey_elem
FROM generate_subscripts(c.conkey, 1) AS idx
) indexed_conkeys
JOIN pg_attribute a ON a.attrelid = t.oid
AND a.attnum = indexed_conkeys.conkey_elem
) AS conkey_names
FROM pg_constraint c
JOIN pg_class t ON c.conrelid = t.oid
JOIN pg_namespace n ON n.oid = c.connamespace
WHERE c.contype = 'u'
AND t.relname = #{scope[:name]}
AND n.nspname = #{scope[:schema]}
SQL
unique_info.map do |row|
columns = decode_string_array(row["conkey_names"])
nulls_not_distinct = row["constraintdef"].start_with?("UNIQUE NULLS NOT DISTINCT")
deferrable = extract_constraint_deferrable(row["condeferrable"], row["condeferred"])
options = {
name: row["conname"],
nulls_not_distinct: nulls_not_distinct,
deferrable: deferrable
}
UniqueConstraintDefinition.new(table_name, columns, options)
end
end
Defined in activerecord/lib/active_record/connection_adapters/postgresql/schema_statements.rb line 726
· View on GitHub
· Improve this page
· Find usages on GitHub
Defined in ActiveRecord::ConnectionAdapters::PostgreSQL::SchemaStatements