Start add a foreign key definition in DDL, detail usage see demo
503404
public FKeyModel fkey(String fkeyName) {
		checkReadOnly();
		FKeyModel fkey = new FKeyModel();
		fkey.setTableName(this.tableName);
		fkey.setFkeyName(fkeyName);
		fkey.setTableModel(this);
		getFkeyConstraints().add(fkey);
		return fkey;
	}
123323
def _set_join(self, query=None):
        
        if not query:
            query = self._query

        foreign_key = '%s.%s' % (self._related.get_table(), self._second_key)

        query.join(self._parent.get_table(), self.get_qualified_parent_key_name(), '=', foreign_key)
908312
def set_up(self, u, engine):
        """"""
        def connect_listener_enable_fk(connection, record):
            # fk must be enabled for all connections
            if not getattr(engine, "fk_disabled", False):
                return  # http://trac.buildbot.net/ticket/3490#ticket
                # connection.execute('pragma foreign_keys=ON')

        sa.event.listen(engine.pool, 'connect', connect_listener_enable_fk)
        # try to enable WAL logging
        if u.database:
            def connect_listener(connection, record):
                connection.execute("pragma checkpoint_fullfsync = off")

            sa.event.listen(engine.pool, 'connect', connect_listener)

            log.msg("setting database journal mode to 'wal'")
            try:
                engine.execute("pragma journal_mode = wal")
            except Exception:
                log.msg("failed to set journal mode - database may fail")
1169193
def init(ctx):
    ''''''

    log.info('Apply DB migrations if needed')
    ctx.invoke(migrate, record=True)

    ctx.invoke(index)

    if IS_TTY:
        text = _('Do you want to create a superadmin user?')
        if click.confirm(text, default=True):
            user = ctx.invoke(user_commands.create)
            ctx.invoke(user_commands.set_admin, email=user.email)

        text = _('Do you want to import some data-related license?')
        if click.confirm(text, default=True):
            ctx.invoke(licenses)

        text = _('Do you want to create some sample data?')
        if click.confirm(text, default=True):
            ctx.invoke(generate_fixtures)

    success(_('Your udata instance is ready!'))
349165
protected <T extends RelationDefinition> void add(T td, Map<RelationID, T> schema) {
        if (!isStillMutable) {
            throw new IllegalStateException("Too late, cannot add a schema");
        }
        schema.put(td.getID(), td);
        if (td.getID().hasSchema()) {
            RelationID noSchemaID = td.getID().getSchemalessID();
            if (!schema.containsKey(noSchemaID)) {
                schema.put(noSchemaID, td);
            }
            else {
                LOGGER.warn("DUPLICATE TABLE NAMES, USE QUALIFIED NAMES:\n" + td + "\nAND\n" + schema.get(noSchemaID));
                //schema.remove(noSchemaID);
                // TODO (ROMAN 8 Oct 2015): think of a better way of resolving ambiguities
            }
        }
    }
723674
def _set_keys_for_save_query(self, query):
        
        query.where(self.__foreign_key, self.get_attribute(self.__foreign_key))

        return query.where(self.__other_key, self.get_attribute(self.__other_key))
5620
public function doFinalInitialization()
    {
        // add the referrers for the foreign keys
        $this->setupTableReferrers();

        // execute database behaviors
        foreach ($this->getBehaviors() as $behavior) {
            $behavior->modifyDatabase();
        }

        // execute table behaviors (may add new tables and new behaviors)
        while ($behavior = $this->getNextTableBehavior()) {
            $behavior->getTableModifier()->modifyTable();
            $behavior->setTableModified(true);
        }

        // do naming and heavy indexing
        foreach ($this->tables as $table) {
            $table->doFinalInitialization();
            // setup referrers again, since final initialization may have added columns
            $table->setupReferrers(true);
        }
    }
563194
def create(cls, parent, child, relation_type, index=None):
        """"""
        try:
            with db.session.begin_nested():
                obj = cls(parent_id=parent.id,
                          child_id=child.id,
                          relation_type=relation_type,
                          index=index)
                db.session.add(obj)
        except IntegrityError:
            raise Exception("PID Relation already exists.")
            # msg = "PIDRelation already exists: " \
            #       "{0} -> {1} ({2})".format(
            #         parent_pid, child_pid, relation_type)
            # logger.exception(msg)
            # raise Exception(msg)
        return obj
1224843
private DDF sql2ddf(String sqlCommand, String errorMessage) throws DDFException {
    try {
      return this.getManager().sql2ddf(String.format(sqlCommand, "{1}"),
          new SQLDataSourceDescriptor(sqlCommand, null, null, null, this
              .getDDF().getUUID().toString()));

    } catch (Exception e) {
      throw new DDFException(String.format(errorMessage, this.getDDF().getTableName()), e);
    }
  }
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
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))
464388
def foreign_keys(self):
        
        foreign_keys = self.__current_descriptor.get('foreignKeys', [])
        for key in foreign_keys:
            key.setdefault('fields', [])
            key.setdefault('reference', {})
            key['reference'].setdefault('resource', '')
            key['reference'].setdefault('fields', [])
            if not isinstance(key['fields'], list):
                key['fields'] = [key['fields']]
            if not isinstance(key['reference']['fields'], list):
                key['reference']['fields'] = [key['reference']['fields']]
        return foreign_keys
1264811
static function TableKeyHasMany($table, $tablePKey, $foreignRef, $foreignKey = false, $foreignClass = 'ADODB_Active_Record')
	{
		if (!is_array($tablePKey)) {
			$tablePKey = array($tablePKey);
		}
		$ar = new ADODB_Active_Record($table,$tablePKey);
		$ar->hasMany($foreignRef, $foreignKey, $foreignClass);
	}
87795
private String createKeyDefinition(final List<FieldDefinition> keyDefinitionList) {
        final StringBuilder sql = new StringBuilder();

        sql.append(" PRIMARY KEY");
        boolean isFirst = true;

        for (FieldDefinition fieldDefinition : keyDefinitionList) {
            if (isFirst) {
                sql.append("(");
                isFirst = false;
            } else {
                sql.append(",");
            }

            sql.append(fieldDefinition.getName());
        }

        sql.append(")");
        return sql.toString();
    }
359895
public function getAddForeignKeyDDL(ForeignKey $fk)
    {
        if ($fk->isSkipSql() || $fk->isPolymorphic()) {
            return;
        }
        $pattern = "
ALTER TABLE %s ADD %s;
";

        return sprintf($pattern,
            $this->quoteIdentifier($fk->getTable()->getName()),
            $this->getForeignKeyDDL($fk)
        );
    }
1296488
public function addForeignKey(ForeignKey $foreignKey)
    {
        $this->table = $this->table->withForeignKeys(
            array_merge($this->table->getForeignKeys(), [$foreignKey])
        );
    }
738495
def build_definitions(dpath="sqlalchemy_models/_definitions.json"):
    
    command.run(AlsoChildrenWalker, module=todo, outdir="sqlalchemy_models", definition_name="_definitions.json",
                relation_decision=RelationDesicion())
    pass  # skip due to unpatched issue in alchemyjsonschema run()
    definitions = ""
    for line in open(dpath, 'r'):
        definitions += line
    definitions = json.loads(definitions)
    newdef = open(dpath.replace("_def", "def"), 'w+')
    for name in definitions['definitions']:
        for mod in [um, em, wm, bm]:
            if hasattr(mod, name):
                model = getattr(mod, name)
                for attr in definitions['definitions'][name]['properties']:
                    if hasattr(getattr(model, attr).property, 'columns') and \
                            isinstance(getattr(model, attr).property.columns[0].type, LedgerAmount):
                        definitions['definitions'][name]['properties'][attr]['type'] = "number"
    newdef.write(json.dumps(definitions, indent=2))
    newdef.close()