DRY alert: copied from ActiveRecord::SchemaDumper#foreign_keys
494422
def dump_foreign_key(foreign_key)
      parts = [
        "add_foreign_key #{remove_prefix_and_suffix(foreign_key.from_table).inspect}",
        remove_prefix_and_suffix(foreign_key.to_table).inspect,
      ]

      if foreign_key.column != foreign_key_column_for(foreign_key.to_table)
        parts << "column: #{foreign_key.column.inspect}"
      end

      if foreign_key.custom_primary_key?
        parts << "primary_key: #{foreign_key.primary_key.inspect}"
      end

      if foreign_key.name !~ /^fk_rails_[0-9a-f]{10}$/
        parts << "name: #{foreign_key.name.inspect}"
      end

      parts << "on_update: #{foreign_key.on_update.inspect}" if foreign_key.on_update
      parts << "on_delete: #{foreign_key.on_delete.inspect}" if foreign_key.on_delete

      parts.join(', ')
    end
1215140
def table_rows
      now = ActiveRecord::Base.default_timezone == :utc ? Time.now.utc : Time.now
      now = now.to_s(:db)

      # allow a standard key to be used for doing defaults in YAML
      fixtures.delete('DEFAULTS')

      # track any join tables we need to insert later
      rows = Hash.new { |h,table| h[table] = [] }

      rows[table_name] = fixtures.map do |label, fixture|
        row = fixture.to_hash

        if model_class && model_class < ActiveRecord::Base
          # fill in timestamp columns if they aren't specified and the model is set to record_timestamps
          if model_class.record_timestamps
            timestamp_column_names.each do |name|
              row[name] = now unless row.key?(name)
            end
          end

          # interpolate the fixture label
          row.each do |key, value|
            row[key] = label if value == "$LABEL"
          end

          # generate a primary key if necessary
          if has_primary_key_column? && !row.include?(primary_key_name)
            row[primary_key_name] = ActiveRecord::Fixtures.identify(label)
          end

          # If STI is used, find the correct subclass for association reflection
          reflection_class =
            if row.include?(inheritance_column_name)
              row[inheritance_column_name].constantize rescue model_class
            else
              model_class
            end

          reflection_class.reflect_on_all_associations.each do |association|
            case association.macro
            when :belongs_to
              # Do not replace association name with association foreign key if they are named the same
              fk_name = (association.options[:foreign_key] || "#{association.name}_id").to_s

              if association.name.to_s != fk_name && value = row.delete(association.name.to_s)
                if association.options[:polymorphic] && value.sub!(/\s*\(([^\)]*)\)\s*$/, "")
                  # support polymorphic belongs_to as "label (Type)"
                  row[association.foreign_type] = $1
                end

                row[fk_name] = ActiveRecord::Fixtures.identify(value)
              end
            when :has_and_belongs_to_many
              if (targets = row.delete(association.name.to_s))
                targets = targets.is_a?(Array) ? targets : targets.split(/\s*,\s*/)
                table_name = association.options[:join_table]
                rows[table_name].concat targets.map { |target|
                  { association.foreign_key             => row[primary_key_name],
                    association.association_foreign_key => ActiveRecord::Fixtures.identify(target) }
                }
              end
            end
          end
        end

        row
      end
      rows
    end
240619
def columns
      begin
        excluded_column_names = %w[id created_at updated_at]
        Kernel.const_get(@model_name).columns.reject{|c| excluded_column_names.include?(c.name) }.collect{|c| Rails::Generators::GeneratedAttribute.new(c.name, c.type)} 
      rescue NoMethodError
        Kernel.const_get(@model_name).fields.collect{|c| c[1]}.reject{|c| excluded_column_names.include?(c.name) }.collect{|c| Rails::Generators::GeneratedAttribute.new(c.name, c.type.to_s)}
      end
    end
672076
def check_validity(reflection)
        if reflection.association_foreign_key == reflection.foreign_key
          raise ActiveRecord::HasAndBelongsToManyAssociationForeignKeyNeeded.new(reflection)
        end

        reflection.options[:join_table] ||= join_table_name(
          model.send(:undecorated_table_name, model.to_s),
          model.send(:undecorated_table_name, reflection.class_name)
        )
      end
1286269
function(r) {
					var rr = {};
					if (typeof r[col.columnid] === 'undefined') {
						return true;
					}
					rr[fk.columnid] = r[col.columnid];
					var addr = fktable.pk.onrightfn(rr);
					//						console.log(r, rr, addr);
					//						console.log(fktable.uniqs[fktable.pk.hh][addr]);
					if (!fktable.uniqs[fktable.pk.hh][addr]) {
						throw new Error(
							'Foreign key "' +
								r[col.columnid] +
								'" is not found in table ' +
								fktable.tableid
						);
					}
					return true;
				}
911373
function getBelongsToName(fkc) {
    var as          = fkc.foreignKey(0).name(),                                             // company_id
        tableName   = fkc.table().name(),
        camelCase   = getSpecificConfig(tableName, 'generate.relationAccessorCamelCase'),
        prefix      = getSpecificConfig(tableName, 'generate.prefixForBelongsTo');          // related

    if (as.match(/_id$/i)) {
        as = as.replace(/_id$/i, '');                                                       // company_id -> company
    } else {
        as = prefix + '_' + as;                                                             // company -> related_company
    }
    if (camelCase) {
        as = inflection.camelize(inflection.underscore(as), true);
    }
    return inflection.singularize(as);
}
1218077
private void ensureReferencedFKs(ModelDef modelDef, CollectionDescriptorDef collDef) throws ConstraintException
    {
        String             elementClassName = collDef.getProperty(PropertyHelper.OJB_PROPERTY_ELEMENT_CLASS_REF);
        ClassDescriptorDef elementClassDef  = modelDef.getClass(elementClassName);
        String             fkFieldNames     = collDef.getProperty(PropertyHelper.OJB_PROPERTY_FOREIGNKEY);
        ArrayList          missingFields    = new ArrayList();
        SequencedHashMap   fkFields         = new SequencedHashMap();

        // first we gather all field names
        for (CommaListIterator it = new CommaListIterator(fkFieldNames); it.hasNext();)
        {
            String             fieldName = (String)it.next();
            FieldDescriptorDef fieldDef  = elementClassDef.getField(fieldName);

            if (fieldDef == null)
            {
                missingFields.add(fieldName);
            }
            fkFields.put(fieldName, fieldDef);
        }

        // next we traverse all sub types and gather fields as we go
        for (Iterator it = elementClassDef.getAllExtentClasses(); it.hasNext() && !missingFields.isEmpty();)
        {
            ClassDescriptorDef subTypeDef = (ClassDescriptorDef)it.next();

            for (int idx = 0; idx < missingFields.size();)
            {
                FieldDescriptorDef fieldDef = subTypeDef.getField((String)missingFields.get(idx));

                if (fieldDef != null)
                {
                    fkFields.put(fieldDef.getName(), fieldDef);
                    missingFields.remove(idx);
                }
                else
                {
                    idx++;
                }
            }
        }
        if (!missingFields.isEmpty())
        {
            throw new ConstraintException("Cannot find field "+missingFields.get(0).toString()+" in the hierarchy with root type "+
                                          elementClassDef.getName()+" which is used as foreignkey in collection "+
                                          collDef.getName()+" in "+collDef.getOwner().getName());
        }

        // copy the found fields into the element class
        ensureFields(elementClassDef, fkFields.values());
    }
1108066
def CheckForeignKeysWrapper(conn):
    
    yield
    cur = conn.cursor()
    cur.execute('PRAGMA foreign_key_check')
    errors = cur.fetchall()
    if errors:
        raise ForeignKeyError(errors)
1313784
def method_missing(name, *args)
      groupname = (args[0] or raise "Database configuration group not specified for #{name}")
      dbname = (args[1] or raise "Database entry name not specified for #{name}")
      n = name.to_s
      begin
        unseparated_yaml(n => self[groupname, dbname])
      rescue Bcdatabase::Error => e
        if ENV['RAILS_ENV'] == n
          raise e
        else
          # Not using that configuration right now, so return a dummy instead
          # of throwing an exception
          unseparated_yaml(n => { 'error' => e.message })
        end
      end
    end
335577
function validateNaming(templateTable) {
    var ri, ci, pi, relationToValidate, column, catched, relation, duplicates = [];

    for (ri = 0; ri < templateTable.relations.length; ri = ri + 1) {
        relationToValidate = templateTable.relations[ri];

        // Check against columns
        for (ci = 0, catched = false; ci < templateTable.columns.length && !catched; ci = ci + 1) {
            column = templateTable.columns[ci];
            if (column.name === relationToValidate.as) {
                logger.warn('ERROR: %s is already used. %s relation is trying to have alias of previously defined column with same name in table %s.%s.', relationToValidate.as, relationToValidate.type, templateTable.schema, templateTable.tableName);
                duplicates.push(relationToValidate.as);
                catched = true;
            }
        }

        // Check against previous relations. Later realitons will check against this already.
        for (pi = 0, catched = false; pi < ri && !catched; pi = pi + 1) {
            relation = templateTable.relations[pi];
            if (relation.as === relationToValidate.as) {
                logger.warn('ERROR: %s is already used. %s relation is trying to have alias of previously defined %s relation in table %s.%s.', relationToValidate.as, relationToValidate.type, relation.type, templateTable.schema, templateTable.tableName);
                duplicates.push(relationToValidate.as);
                catched = true;
            }
        }
    }

    if (duplicates.length > 0) {
        return 'Table ' + templateTable.schema + '.' + templateTable.tableName + ' has duplicate relation aliases: ' + duplicates.join(',') + '.';
    }

}
686558
def modify_fk_constraint(apps, schema_editor):
    
    model = apps.get_model("message_sender", "OutboundSendFailure")
    table = model._meta.db_table

    with schema_editor.connection.cursor() as cursor:
        constraints = schema_editor.connection.introspection.get_constraints(
            cursor, table
        )
        [constraint] = filter(lambda c: c[1]["foreign_key"], constraints.items())
        [name, _] = constraint
    sql_delete_fk = (
        "SET CONSTRAINTS {name} IMMEDIATE; "
        "ALTER TABLE {table} DROP CONSTRAINT {name}"
    ).format(table=schema_editor.quote_name(table), name=schema_editor.quote_name(name))
    schema_editor.execute(sql_delete_fk)

    field = model.outbound.field
    to_table = field.remote_field.model._meta.db_table
    to_column = field.remote_field.model._meta.get_field(
        field.remote_field.field_name
    ).column
    sql_create_fk = (
        "ALTER TABLE {table} ADD CONSTRAINT {name} FOREIGN KEY "
        "({column}) REFERENCES {to_table} ({to_column}) "
        "ON DELETE CASCADE {deferrable};"
    ).format(
        table=schema_editor.quote_name(table),
        name=schema_editor.quote_name(name),
        column=schema_editor.quote_name(field.column),
        to_table=schema_editor.quote_name(to_table),
        to_column=schema_editor.quote_name(to_column),
        deferrable=schema_editor.connection.ops.deferrable_sql(),
    )
    schema_editor.execute(sql_create_fk)
518073
def model_attributes(model, ignored_tables, ignored_cols)
      return [] if model.abstract_class? && Rails::VERSION::MAJOR < 3

      if model.abstract_class?
        model.direct_descendants.reject {|m| ignored?(m.table_name, ignored_tables)}.inject([]) do |attrs, m|
          attrs.push(model_attributes(m, ignored_tables, ignored_cols)).flatten.uniq
        end
      elsif !ignored?(model.table_name, ignored_tables) && @existing_tables.include?(model.table_name)
        model.columns.reject { |c| ignored?(c.name, ignored_cols) }.collect { |c| c.name }
      else
        []
      end
    end
264798
def left_joins(*args)
			return self if args.compact.blank?

			relation = clone

			args.flatten!

			#	args could be just a single symbol
			#		...could be an array of symbols (
			#		...could be a hash (joins(:address => :address_type))
			#		...could be a string (SQL)

			#	here I really am just expecting an array of model names as a symbols

			#	this only works if the primary and foreign keys are conventional

			#	@klass (or its reader klass() ) is the calling class (Organization)
			#	@table (or its reader table() ) is the calling class's Arel::Table


#	StudySubject
# scope :join_patients, joins(
#   Arel::Nodes::OuterJoin.new(Patient.arel_table,Arel::Nodes::On.new(
#     self.arel_table[:id].eq(Patient.arel_table[:study_subject_id]))))
# scope :join_patients, left_joins(:patient)	#	WORKS

#	Organization
# scope :without_sample_location, joins(
#   Arel::Nodes::OuterJoin.new(
#     SampleLocation.arel_table,Arel::Nodes::On.new(
#       self.arel_table[:id].eq(SampleLocation.arel_table[:organization_id]))))
# scope :without_sample_location, left_joins(:sample_location)	#	WORKS
#
#	Organization has one Sample Location

# scope :without_hospital, joins(
#   Arel::Nodes::OuterJoin.new(
#     Hospital.arel_table,Arel::Nodes::On.new(
#       self.arel_table[:id].eq(Hospital.arel_table[:organization_id]))))
# scope :without_hospital, left_joins(:hospital)	#	WORKS

#	Organization has one Hospital


#		@zip_codes = ZipCode.joins(
#			Arel::Nodes::OuterJoin.new(County.arel_table,Arel::Nodes::On.new(
#				ZipCode.arel_table[:county_id].eq(County.arel_table[:id]))))
#
#		@zip_codes = ZipCode.left_joins(:county) #??? backwards? won't work?

#	ZipCode belongs to County



#	doesn't work on has_one or has_many ... :through


			args.each do |arg|	#	no, I'm not a pirate
				reflection = klass.reflections[arg]
				joining_model = reflection.klass
#
#	:has_one and probably :has_many	( BUT NOT :belongs_to )
#
				relation.joins_values += [
					Arel::Nodes::OuterJoin.new(
						joining_model.arel_table,
( reflection.macro == :belongs_to ) ?
						Arel::Nodes::On.new(
							table[ reflection.foreign_key ].eq(
#								joining_model.arel_table[ :id ]
								joining_model.arel_table[ reflection.options[:primary_key] || :id ]
							)
						) :
						Arel::Nodes::On.new(
							table[:id].eq(		#	won't ALWAYS be :id
								joining_model.arel_table[ reflection.foreign_key ]
							)
						)

					)
				]




			end	#	args.each do |arg|	#	no, I'm not a pirate

			relation
		end
727058
def foreign_key(name)
      attr = schema.foreign_key(name.dataset)

      if attr
        attr.name
      else
        :"#{Inflector.singularize(name.dataset)}_id"
      end
    end
938187
def get_foreign_keys(self, connection, table_name, schema=None, **kw):
        
        constraints = self._get_redshift_constraints(connection, table_name,
                                                     schema, **kw)
        fk_constraints = [c for c in constraints if c.contype == 'f']
        uniques = defaultdict(lambda: defaultdict(dict))
        for con in fk_constraints:
            uniques[con.conname]["key"] = con.conkey
            uniques[con.conname]["condef"] = con.condef
        fkeys = []
        for conname, attrs in uniques.items():
            m = FOREIGN_KEY_RE.match(attrs['condef'])
            colstring = m.group('referred_columns')
            referred_columns = SQL_IDENTIFIER_RE.findall(colstring)
            referred_table = m.group('referred_table')
            referred_schema = m.group('referred_schema')
            colstring = m.group('columns')
            constrained_columns = SQL_IDENTIFIER_RE.findall(colstring)
            fkey_d = {
                'name': conname,
                'constrained_columns': constrained_columns,
                'referred_schema': referred_schema,
                'referred_table': referred_table,
                'referred_columns': referred_columns,
            }
            fkeys.append(fkey_d)
        return fkeys
1348586
def random_uniq_attr(field, **options, &block)
      set_method = :"set_#{field}"
      generate_method = :"generate_#{field}"
      max_attempts = options.fetch(:max_attempts) { MAX_ATTEMPTS }

      after_create set_method, unless: :"#{field}?"

      # def self.generate_key
      define_singleton_method generate_method, &(block || DEFAULT_GENERATOR)

      # def set_key
      define_method(set_method) do
        attempt = 0
        begin
          raise 'Available only for persisted record' unless persisted?
          transaction(requires_new: true) do
            new_value = self.class.send(generate_method, self)
            update_column field, new_value # rubocop:disable Rails/SkipsModelValidations
          end
        rescue ActiveRecord::RecordNotUnique
          attempt += 1
          raise if attempt > max_attempts
          retry
        end
      end
    end
907022
function Schema(options, descriptors) {

    if (!descriptors) {
        descriptors = options;
        options = null;
    }

    function opt(name, type) {
        var value = options[name];
        if (value !== undefined) {
            if (typeof value === type) return value;
            else throw new TypeError(current + 'options : ' + name + ': "' +
                value + '" is not of type [' + type + ']');
        }
        else return false;
    }

    var current = 'Schema: arguments: ',
        defaults = { required: false };

    if (hasValue(options)) {
        if (type(options) === 'object') {
            defaults.required = opt('required', 'boolean');
            if (opt('validator', 'function')) defaults.validator = options.validator;
        }
        else throw new TypeError(current + 'options: must be of type [object]');
    }

    current += 'descriptors: ';
    if (typeof descriptors !== 'object')
        throw new TypeError(current + 'must be of type [object]');
    if (!Array.isArray(descriptors)) {
        descriptors = this.toDescriptors(descriptors, defaults);
    }
    if (options && options.extends instanceof Schema) {
        descriptors = this.extendDescriptors(descriptors, options.extends.descriptors);
    }
    if (!descriptors.length)
        throw new TypeError(current + 'contains no values');
    else if (!(descriptors[0] instanceof Descriptor)) {
        throw new TypeError(current + 'must be instances of Descriptor class');
    }
    var instance = this;
    this.descriptors = descriptors;

}