Module: Postgresql::Check::SchemaStatements
- Extended by:
- ActiveSupport::Concern
- Defined in:
- lib/postgresql/check/schema_statements.rb
Instance Method Summary collapse
-
#add_check(table_name, condition, options) ⇒ Object
Add a new Check constraint to table with given
table_nameusing givenconditions. - #checks(table_name) ⇒ Object private
- #create_table_with_checks(table_name, *args, &block) ⇒ Object private
-
#remove_check(table_name, options) ⇒ Object
Remove constraint with given name from table.
Instance Method Details
#add_check(table_name, condition, options) ⇒ Object
Note:
:name option is mandatory.
Add a new Check constraint to table with given table_name using given conditions. Constraint name should be specified by :name options in options argument.
26 27 28 29 30 31 32 33 34 |
# File 'lib/postgresql/check/schema_statements.rb', line 26 def add_check(table_name, condition, ) name = .fetch(:name) { raise 'add_check, :name option required' } sql = "ALTER TABLE #{quote_table_name(table_name)} " + "ADD CONSTRAINT #{quote_column_name(name)} " + "CHECK (#{condition})" execute(sql) end |
#checks(table_name) ⇒ Object
This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.
72 73 74 75 76 77 78 79 80 81 82 83 84 |
# File 'lib/postgresql/check/schema_statements.rb', line 72 def checks(table_name) checks_info = select_all %{ SELECT c.conname, c.consrc FROM pg_constraint c JOIN pg_class t ON c.conrelid = t.oid WHERE c.contype = 'c' AND t.relname = '#{table_name}' } checks_info.map do |row| Constraint.new(table_name, row['conname'], row['consrc']) end end |
#create_table_with_checks(table_name, *args, &block) ⇒ Object
This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.
58 59 60 61 62 63 64 65 66 67 68 69 |
# File 'lib/postgresql/check/schema_statements.rb', line 58 def create_table_with_checks(table_name, *args, &block) definition = nil create_table_without_checks(table_name, *args) do |td| definition = td # trick to get the definition block.call(td) unless block.nil? end definition.checks.each do |condition, | add_check(table_name, condition, ) end end |
#remove_check(table_name, options) ⇒ Object
Remove constraint with given name from table. Constraint name is specified with options hash.
48 49 50 51 52 53 54 55 |
# File 'lib/postgresql/check/schema_statements.rb', line 48 def remove_check(table_name, ) name = .fetch(:name) { raise 'remove_check, :name option required' } sql = "ALTER TABLE #{quote_table_name(table_name)} " + "DROP CONSTRAINT #{quote_column_name(name)}" execute(sql) end |