You can run into a problem when you are trying to set a table and it has a 
        foreign key to a table that doesn't exist, so this method will go through 
        all fk refs and make sure the tables exist
771626
def _set_all_tables(self, schema, **kwargs):
        
        with self.transaction(**kwargs) as connection:
            kwargs['connection'] = connection
            # go through and make sure all foreign key referenced tables exist
            for field_name, field_val in schema.fields.items():
                s = field_val.schema
                if s:
                    self._set_all_tables(s, **kwargs)

            # now that we know all fk tables exist, create this table
            self.set_table(schema, **kwargs)

        return True
518698
public void addForeignkey(String relationName, String remoteTable, List localColumns, List remoteColumns)
    {
        ForeignkeyDef foreignkeyDef = new ForeignkeyDef(relationName, remoteTable);

        // the field arrays have the same length if we already checked the constraints
        for (int idx = 0; idx < localColumns.size(); idx++)
        {
            foreignkeyDef.addColumnPair((String)localColumns.get(idx),
                                        (String)remoteColumns.get(idx));
        }

        // we got to determine whether this foreignkey is already present 
        ForeignkeyDef def = null;

        for (Iterator it = getForeignkeys(); it.hasNext();)
        {
            def = (ForeignkeyDef)it.next();
            if (foreignkeyDef.equals(def))
            {
                return;
            }
        }
        foreignkeyDef.setOwner(this);
        _foreignkeys.add(foreignkeyDef);
    }
1206141
private function preloadReferences()
    {

        // References defined in pg_catalog
        $sql = 'SELECT * FROM dev."vAttributeReferences" WHERE "isInherited" = false';

        $relationships = $this->db->query( new Query( $sql ) );

        foreach( $relationships->fetch() as $relationship ) {

            $fk = $this->instancesPersisted[$relationship['fk_key']];
            $pk = $this->instancesPersisted[$relationship['pk_key']];

            if( !$fk or !$pk ) {
                d_pr( $relationship );
                die();
            }

            // slower alternatives. They all do the same thing
            // $fk = $this->persistedGet()->findOneByKey( $relationship['fk_key'] );
            // $pk = $this->persistedGet()->findOneByKey( $relationship['pk_key'] );

            // $fk = $this->find( $relationship['fk_key'] );
            // $pk = $this->find( $relationship['pk_key'] );

            $fk->addReference( $pk );

        }

        // look for normality defined relationships
        $profiler = new Profiler( __FUNCTION__ );
        $profiler->log();

        foreach( EntityRelation::r()->findAll() as $relation ) {

            $tags = $relation->getNormalityTags();
            if( isset( $tags['references'] ) ) {

                foreach( $tags['references'] as $reference ) {

                    $reference = array_map( 'trim', explode( '=', $reference) );

                    $fk = $this->findByRelation( $relation )->findOneByName( $reference[0] );
                    $pk = $this->findByIdentifier( $reference[1] );

                    // go the database to get child records, using the Relation repo methods causes a infinite preload loop
                    $query = new Query(
                        "SELECT oid::text || '.' || %attnum:int%::text FROM dev.relationDescendants( %oid:int%::oid ) as _ ( oid );",
                        array(
                            'attnum' => $pk->get('attnum'),
                            'oid' => $pk->getRelation()->get('oid')
                        )
                    );

                    foreach( $this->db->query( $query )->fetch() as $pk_key ) {

                        $fk->addReference( $this->find( $pk_key ) );

                    }

                }

            }

        }

//        echo $profiler->log()->output();

    }
230538
def db_repair(name,
              table=None,
              **connection_args):
    '''
    
    '''
    ret = []
    if table is None:
        # we need to repair all tables
        tables = db_tables(name, **connection_args)
        for table in tables:
            log.info('Repairing table \'%s\' in db \'%s\'..', name, table)
            ret.append(__repair_table(name, table, **connection_args))
    else:
        log.info('Repairing table \'%s\' in db \'%s\'..', name, table)
        ret = __repair_table(name, table, **connection_args)
    return ret
160114
def table_exists?(name)
      return false unless name
      schema ? @connection.table_exists?(name, schema) : @connection.table_exists?(name)
    end
254955
function(instance, objects) {
    var foreignKeyAttr = this.foreignKeyAttr;
    var fk = instance.getAttribute(foreignKeyAttr);
    if (fk && objects.length === 0) {
      var relatedModel = this._relatedModel;
      var relatedClass = relatedModel.__identity__;
      var relatedName = relatedClass.__name__;
      throw new Error(util.format('Found no %s with %j %d',
        relatedName, foreignKeyAttr, fk));
    }
  }
333432
def get_create_foreign_key_sql(self, foreign_key, table):
        
        if isinstance(table, Table):
            table = table.get_quoted_name(self)

        query = "ALTER TABLE %s ADD %s" % (
            table,
            self.get_foreign_key_declaration_sql(foreign_key),
        )

        return query
310314
function setReference( $table, $name, $key ) {

        $this->references[ $table ][ $name ] = $key;

        return $this;

    }
364176
public ForeignkeyDef getForeignkey(String name, String tableName)
    {
        String        realName = (name == null ? "" : name);
        ForeignkeyDef def      = null;

        for (Iterator it = getForeignkeys(); it.hasNext();)
        {
            def = (ForeignkeyDef)it.next();
            if (realName.equals(def.getName()) &&
                def.getTableName().equals(tableName))
            {
                return def;
            }
        }
        return null;
    }
622467
Table REFERENTIAL_CONSTRAINTS() {

        Table t = sysTables[REFERENTIAL_CONSTRAINTS];

        if (t == null) {
            t = createBlankTable(sysTableHsqlNames[REFERENTIAL_CONSTRAINTS]);

            addColumn(t, "CONSTRAINT_CATALOG", SQL_IDENTIFIER);
            addColumn(t, "CONSTRAINT_SCHEMA", SQL_IDENTIFIER);
            addColumn(t, "CONSTRAINT_NAME", SQL_IDENTIFIER);              // not null
            addColumn(t, "UNIQUE_CONSTRAINT_CATALOG", SQL_IDENTIFIER);    // not null
            addColumn(t, "UNIQUE_CONSTRAINT_SCHEMA", SQL_IDENTIFIER);
            addColumn(t, "UNIQUE_CONSTRAINT_NAME", SQL_IDENTIFIER);
            addColumn(t, "MATCH_OPTION", CHARACTER_DATA);                 // not null
            addColumn(t, "UPDATE_RULE", CHARACTER_DATA);                  // not null
            addColumn(t, "DELETE_RULE", CHARACTER_DATA);                  // not null

            HsqlName name = HsqlNameManager.newInfoSchemaObjectName(
                sysTableHsqlNames[REFERENTIAL_CONSTRAINTS].name, false,
                SchemaObject.INDEX);

            t.createPrimaryKey(name, new int[] {
                0, 1, 2,
            }, false);

            return t;
        }

        // column number mappings
        final int constraint_catalog        = 0;
        final int constraint_schema         = 1;
        final int constraint_name           = 2;
        final int unique_constraint_catalog = 3;
        final int unique_constraint_schema  = 4;
        final int unique_constraint_name    = 5;
        final int match_option              = 6;
        final int update_rule               = 7;
        final int delete_rule               = 8;

        //
        PersistentStore store = database.persistentStoreCollection.getStore(t);
        Iterator        tables;
        Table           table;
        Constraint[]    constraints;
        Constraint      constraint;
        Object[]        row;

        tables =
            database.schemaManager.databaseObjectIterator(SchemaObject.TABLE);

        while (tables.hasNext()) {
            table = (Table) tables.next();

            if (table.isView()
                    || !session.getGrantee().hasNonSelectTableRight(table)) {
                continue;
            }

            constraints = table.getConstraints();

            for (int i = 0; i < constraints.length; i++) {
                constraint = constraints[i];

                if (constraint.getConstraintType() != Constraint.FOREIGN_KEY) {
                    continue;
                }

                HsqlName uniqueName = constraint.getUniqueName();

                row                     = t.getEmptyRowData();
                row[constraint_catalog] = database.getCatalogName().name;
                row[constraint_schema]  = constraint.getSchemaName().name;
                row[constraint_name]    = constraint.getName().name;

                if (isAccessibleTable(constraint.getMain())) {
                    row[unique_constraint_catalog] =
                        database.getCatalogName().name;
                    row[unique_constraint_schema] = uniqueName.schema.name;
                    row[unique_constraint_name]   = uniqueName.name;
                }

                row[match_option] = Tokens.T_NONE;
                row[update_rule]  = constraint.getUpdateActionString();
                row[delete_rule]  = constraint.getDeleteActionString();

                t.insertSys(store, row);
            }
        }

        return t;
    }
1189419
def has_foreign_key(self, name):
        
        name = self._normalize_identifier(name)

        return name in self._fk_constraints
1319401
function(record, foreign_key) {

		if (foreign_key in this._collections_by_foreign_id) {

			this._collections_by_foreign_id[foreign_key].push(record);

		} else {

			this._collections_by_foreign_id[foreign_key] = [record];

		}

	}
415266
def set_table(self, table):
        
        super(MultiField, self).set_table(table)
        if self.field and self.field.table is None:
            self.field.set_table(self.table)
157250
def _drop(self, table, existing_tables=None):
        """"""
        # Retrieve list of existing tables for comparison
        existing_tables = existing_tables if existing_tables else self.tables

        # Only drop table if it exists
        if table in existing_tables:
            # Set to avoid foreign key errorrs
            self.execute('SET FOREIGN_KEY_CHECKS = 0')

            query = 'DROP TABLE {0}'.format(wrap(table))
            self.execute(query)

            # Set again
            self.execute('SET FOREIGN_KEY_CHECKS = 1')
            self._printer('\tDropped table {0}'.format(table))
394771
async def add(self, *instances, using_db=None) -> None:
        
        if not instances:
            return
        if self.instance.id is None:
            raise OperationalError(
                "You should first call .save() on {model}".format(model=self.instance)
            )
        db = using_db if using_db else self.model._meta.db
        through_table = Table(self.field.through)
        select_query = (
            db.query_class.from_(through_table)
            .where(getattr(through_table, self.field.backward_key) == self.instance.id)
            .select(self.field.backward_key, self.field.forward_key)
        )
        query = db.query_class.into(through_table).columns(
            getattr(through_table, self.field.forward_key),
            getattr(through_table, self.field.backward_key),
        )

        if len(instances) == 1:
            criterion = getattr(through_table, self.field.forward_key) == instances[0].id
        else:
            criterion = getattr(through_table, self.field.forward_key).isin(
                [i.id for i in instances]
            )

        select_query = select_query.where(criterion)

        already_existing_relations_raw = await db.execute_query(str(select_query))
        already_existing_relations = {
            (r[self.field.backward_key], r[self.field.forward_key])
            for r in already_existing_relations_raw
        }

        insert_is_required = False
        for instance_to_add in instances:
            if instance_to_add.id is None:
                raise OperationalError(
                    "You should first call .save() on {model}".format(model=instance_to_add)
                )
            if (self.instance.id, instance_to_add.id) in already_existing_relations:
                continue
            query = query.insert(instance_to_add.id, self.instance.id)
            insert_is_required = True
        if insert_is_required:
            await db.execute_query(str(query))
656643
def table_absent(name, db):
    '''
    
    '''
    changes = {'name': name,
               'changes': {},
               'result': None,
               'comment': ''}
    conn = None
    try:
        conn = sqlite3.connect(db, detect_types=sqlite3.PARSE_DECLTYPES)
        tables = _query(conn, "SELECT sql FROM sqlite_master " +
                              " WHERE type='table' AND name=?", [name])

        if len(tables) == 1:
            if __opts__['test']:
                changes['result'] = True
                changes['comment'] = "'" + name + "' will be dropped"
            else:
                conn.execute("DROP TABLE " + name)
                conn.commit()
                changes['changes']['old'] = tables[0][0]
                changes['result'] = True
                changes['comment'] = "'" + name + "' was dropped"
        elif not tables:
            changes['result'] = True
            changes['comment'] = "'" + name + "' is already absent"
        else:
            changes['result'] = False
            changes['comment'] = "Multiple tables with the same name='" + \
                                 name + "'"

    except Exception as e:
        changes['result'] = False
        changes['comment'] = six.text_type(e)

    finally:
        if conn:
            conn.close()

    return changes
1246052
private void addForeignkeys(ReferenceDescriptorDef refDef, TableDef tableDef)
    {
        if (!refDef.getBooleanProperty(PropertyHelper.OJB_PROPERTY_DATABASE_FOREIGNKEY, true))
        {
            // we shall not generate a database foreignkey
            return;
        }

        // a foreignkey is added to the table schema if
        // the referenced table exists (i.e. the referenced type has an associated table)
        // then the foreignkey consists of:
        //   remote table  = table of referenced type
        //   local fields  = foreignkey fields of the reference 
        //   remote fields = primarykeys of the referenced type
        ClassDescriptorDef ownerClassDef      = (ClassDescriptorDef)refDef.getOwner();
        String             targetClassName    = refDef.getProperty(PropertyHelper.OJB_PROPERTY_CLASS_REF);
        ClassDescriptorDef referencedClassDef = ((ModelDef)ownerClassDef.getOwner()).getClass(targetClassName);

        // we can add a foreignkey only if the target type and all its subtypes either
        // map to the same table or do not map to a table at all
        String tableName = getHierarchyTable(referencedClassDef);

        if (tableName == null)
        {
            return;
        }

        try
        {
            String    name         = refDef.getName();
            ArrayList localFields  = ownerClassDef.getFields(refDef.getProperty(PropertyHelper.OJB_PROPERTY_FOREIGNKEY));
            ArrayList remoteFields = referencedClassDef.getPrimaryKeys();

            tableDef.addForeignkey(name, tableName, getColumns(localFields), getColumns(remoteFields));
        }
        catch (NoSuchFieldException ex)
        {
            // won't happen if we already checked the constraints
        }
    }