Constructs model from multiple tables.
Queries will join tables, inserts, updates and deletes will be applied on both tables
340023
public function join(
        $foreign_table,
        $master_field = null,
        $join_kind = null,
        $_foreign_alias = null,
        $relation = null
    ) {
        if (!$_foreign_alias) {
            $_foreign_alias = '_'.$foreign_table[0];
        }
        $_foreign_alias = $this->_unique($this->relations, $_foreign_alias);

        /** @type SQL_Relation $rel */
        $rel = $this->add('SQL_Relation', $_foreign_alias);

        return $this->relations[$_foreign_alias] = $rel
            ->set($foreign_table, $master_field, $join_kind, $relation);
    }
207722
public function build()
    {
        $options           = $this->suppliedOptions;
        $this->tablePrefix = $this->db->getTablePrefix();
        $nested            = $this->getNestedRelationships($options['relationship']);

        $relevantName      = $nested['pieces'][sizeof($nested['pieces']) - 1];
        $relevantModel     = $nested['models'][sizeof($nested['models']) - 2];
        $options['nested'] = $nested;

        $relationship = $relevantModel->{$relevantName}();
        $selectTable  = $options['column_name'].'_'.$this->tablePrefix.$relationship->getRelated()->getTable();

        //set the relationship object so we can use it later
        $this->relationshipObject = $relationship;

        //replace the (:table) with the generated $selectTable
        $options['select'] = str_replace('(:table)', $selectTable, $options['select']);

        $this->suppliedOptions = $options;
    }
622099
function createTable (model) {
    var columnSql = []
    var keySql = []
    var primaryKeySql = []
    var uniqueKeySql = []
    // create sql for columns
    _.each(model.columnNames, name => {
        // get spec
        var spec = model.columns[name]
        // create column sql
        columnSql.push(createTableColumn(model, name, spec))
        // column has index
        if (spec.index || spec.primary || spec.unique) {
            // index is primary
            if (spec.primary) {
                primaryKeySql.push(createTablePrimaryKey(name, spec))
            }
            // index is unique
            else if (spec.unique) {
                uniqueKeySql.push(createTableUniqueKey(name, spec))
            }
            // index is not unique
            else {
                keySql.push(createTableKey(name, spec))
            }
        }
    })
    // require table to have at most one primary key
    assert.ok(primaryKeySql.length <= 1, model.name+': table must not have more than one primary key')
    // add any multi-column indexes
    _.each(model.indexes, (spec) => {
        // index is unique
        if (spec.unique) {
            uniqueKeySql.push(createTableUniqueKeyMulti(spec))
        }
        // index is not unique
        else {
            keySql.push(createTableKeyMulti(spec))
        }
    })
    // return create table sql
    return 'CREATE TABLE '+quoteName(model.name)+' ('
        + columnSql.concat(primaryKeySql, uniqueKeySql, keySql).join(', ')
        + ') ENGINE='+model.engine+' DEFAULT CHARSET='+model.charset
}
31732
def creating_schema_and_index(self, models, func):
        
        waiting_models = []
        self.base_thread.do_with_submit(func, models, waiting_models, threads=self.threads)
        if waiting_models:
            print("WAITING MODELS ARE CHECKING...")
            self.creating_schema_and_index(waiting_models, func)
201058
def generate_models(args):
  """"""
  data_table = get_data_table(args.filename)
  tables = to_tables(data_table.rows_to_dicts())
  attr_indent = "\n" + args.indent * 2
  attr_sep = "," + attr_indent

  for tname, cols in tables.items():
    model_name = table_to_model_name(tname, list(cols.values())[0]["table_schema"])
    pk_cols, oth_cols = split_pks(cols)
    timestamps = get_timestamps(cols, args.created_at_col_name, args.updated_at_col_name)
    is_auto = len(pk_cols) == 1 and cols[pk_cols[0]]["is_auto"] == "t"

    attrs = OrderedDict()
    for cname in oth_cols:
      if cname not in timestamps:
        attrs[cname] = None

    print(_MODEL_SOURCE.format(
      class_name=model_name,
      base_class_name="ModelBase",
      indent=args.indent,
      table_name=repr(tname),
      pk_name=repr(pk_cols[0] if len(pk_cols) == 1 else pk_cols),
      pk_is_auto=is_auto,
      timestamps=timestamps,
      attrs="dict(" + attr_indent + attr_sep.join("{0}={1}".format(k, v) for k, v in attrs.items()) + ")"))
    print()
451939
def build_from_table(self):
        
        table_parts = []

        # get the table sql for each table
        for table in self.tables:
            sql = table.get_sql()
            if len(sql):
                table_parts.append(sql)

        # combine all table sql separated by a comma
        sql = 'FROM {0} '.format(', '.join(table_parts))

        return sql
287269
def create(self):
        
        # Calls each of these methods in order.  _populate_from_lines and
        # _update_relations must be implemented in subclasses.
        self._init_tables()
        self._populate_from_lines(self.iterator)
        self._update_relations()
        self._finalize()
1036781
def _merge_model_defined_relation_wheres_to_has_query(self, has_query, relation):
        
        relation_query = relation.get_base_query()

        has_query.merge_wheres(relation_query.wheres, relation_query.get_bindings())

        self._query.add_binding(has_query.get_query().get_bindings(), "where")
391845
protected function buildRelationshipQuery($field_parameters)
    {
        if (isset($field_parameters['table']) && ! $this->onlyQueryFrom == 'model') {
            $table = $field_parameters['table'];

            return DB::table($table);
        } elseif (isset($field_parameters['model']) && ! $this->onlyQueryFrom == 'table') {
            $class = $field_parameters['model'];
            $model = new $class;

            if ($model instanceof Model) {
                return $model;
            }

            throw new Exception('Class \''.$class.'\' must be an isntance of \''.Model::class.'\'');
        }

        throw new Exception('No valid query to build from field parameters');
    }
51653
function mysqlBulkUpsert(model, data) {
  var mysql = require("mysql");
  var queries = ["SET AUTOCOMMIT = 0"];

  // Transform data
  _.each(data, function(d) {
    var query = "REPLACE INTO " + model.tableName + " ([[COLUMNS]]) VALUES (?)";
    query = query.replace("[[COLUMNS]]", _.keys(d).join(", "));
    query = mysql.format(query, [ _.values(d) ]);
    queries.push(query);
  });

  // Create final output and format
  queries.push("COMMIT");
  queries.push("SET AUTOCOMMIT = 1");
  return queries.join("; ");
}
169510
def add_eager_constraints(self, models):
        
        table = self._parent.get_table()

        self._query.where_in("%s.%s" % (table, self._first_key), self.get_keys(models))
1002003
def insert_model(self, model, *, upsert=None):
    
    pkname = model.primary_key_name
    include_keys = set(model.attrs.keys()).difference(model.exclude_keys_sql)

    if model.primary_key_is_auto:
      if pkname in include_keys:
        include_keys.remove(pkname)
    else:
      if isinstance(pkname, str):
        include_keys.add(pkname)
      else:
        include_keys.update(set(pkname))

    data = model.to_dict(include_keys=include_keys)
    returnings = []

    if model.primary_key_is_auto:
      returnings.append(pkname)
    if model.timestamps:
      returnings.extend(ts_name for ts_name in model.timestamps if ts_name)

    returning = ", ".join(returnings)
    cr = self.insert(model.table_name, data, returning=returning, upsert=upsert)

    if self.core.supports_returning_syntax:
      if returning:
        rec = cr.fetchone()
        if rec:
          for idx, attr_name in enumerate(returnings):
            setattr(model, attr_name, rec[idx])
    else:
      if model.primary_key_is_auto:
        setattr(model, model.primary_key_name, cr.lastrowid)

    return model
1207564
function buildWhereModel (name, value, alias) {
    // skip updefined values
    if (value === undefined) {
        return
    }
    // get id columns for model
    var idColumn = this.model.columnName('id')
    var originalIdColumn = this.model.columnName('originalId')
    // model column belongs to
    var model
    // column spec
    var spec
    // isDeleted where clause
    if (name === 'isDeleted') {
        // if value is null do nothing
        if (value === null) {
            return
        }
        // change column name to real column name (d)
        name = 'd'
    }
    // join column where clause
    if (name.match(/\./)) {
        var [prefix, column] = name.split('.')
        // prefix is for join
        if (this.joinRelations[prefix]) {
            // get join
            var join = this.joinRelations[prefix]
            // get relation
            var relation = this.model.relation(prefix)
            // set model for where clause
            model = relation.model
            // get column name from relation model
            name = model.columnName(column, true)
            // get spec
            spec = model.columns[name]
            // get alias
            alias = join.relationAlias
        }
        // error
        else {
            throw new Error('invalid column name in where '+name)
        }
    }
    // where clause for column on primary model table
    else {
        // model is base model
        model = this.model
        // validate column name - throw error
        name = this.model.columnName(name, true)
        // get column spec
        spec = this.model.columns[name]
        // if value is set for only the first column then need to add join to
        // select the record that matches the value
        if (spec.firstOnly) {
            // get new alias for primary table
            alias = this.newAlias(this.table)
            // add join
            this.join.push( this.joinSql(this.table, alias, originalIdColumn, this.alias, originalIdColumn) )
        }
    }
    // if optional alias is not set then get table alias for model name
    if (!alias) {
        alias = this.getAlias(model.name)
    }
    // flag set to true if this is negated statement
    var isNot = false
    // every where statement will begin with the alias and column name
    var whereSql = `${alias}.${this.quoteName(name)}`
    // if value is a string then do a simple column = :value
    if (typeof value === 'string' || typeof value === 'number') {
        // get param name for value placeholder
        var paramName = this.newParam(name)
        // set value for param placeholder
        this.params[paramName] = value
        // create sql
        whereSql += spec.type === 'id' && this.model.binaryIds
            ? ` = UNHEX(:${paramName})`
            : ` = :${paramName}`
    }
    // if value is boolean then do column = 1|0
    else if (spec.type === 'boolean' && typeof value === 'boolean') {
        // get param name for value placeholder
        var paramName = this.newParam(name)
        // create sql
        whereSql += ` = ${value ? 1 : 0}`
    }
    // if value is array then do IN () query
    else if (Array.isArray(value)) {
        var placeholders = _.map(value, v => {
            // get param name for each placeholder
            var paramName = this.newParam(name)
            // set value for param placeholder
            this.params[paramName] = v
            // create placeholder
            return spec.type === 'id' && this.model.binaryIds
                ? `UNHEX(:${paramName})`
                : `:${paramName}`
        })
        // create sql
        whereSql += ` IN(${placeholders.join(', ')})`
    }
    // if value is null then do IF NULL
    else if (value === null) {
        // create sql
        whereSql += ' IS NULL'
    }
    // if value is object then it should be a match type and value
    else if (typeof value === 'object') {
        // get keys of object
        var keys = _.keys(value)
        // there should be only one key
        assert.equal(keys.length, 1, 'statement must have one comparison operator in where '+name)
        // get operator
        var operator = keys[0]
        // get value
        var operatorValue = value[operator]
        var operatorValueType = typeof operatorValue
        // validate operator value
        if (operatorValueType === 'object' && operator !== 'in' && operator !== 'between' && operator !== 'not') {
            // if value is array change the type from object to array
            if (Array.isArray(operatorValue)) {
                operatorValueType = 'array'
            }
            // throw error
            throw new Error(`${model.name} query error: invalid value type '${operatorValueType}' for operator '${operator}'`)
        }
        // if operator is not then need to get next level deeper
        if (operator === 'not') {
            // if value is null than do IF NULL
            if (operatorValue === null) {
                // create sql
                whereSql += ' IS NOT NULL'
                // add sql to list of where clauses
                this.where.push(whereSql)
                // TODO: refactor this
                return
            }
            else {
                // get keys of not object
                keys = _.keys(operatorValue)
                // there should be only one key
                assert.equal(keys.length, 1, 'statement must have one comparison operator in where '+name)
                // get operator
                operator = keys[0]
                // get value
                operatorValue = operatorValue[operator]
                // set flag to negate statement
                isNot = true
            }
        }
        // LIKE :value
        if (operator === 'like') {
            // get param name for value placeholder
            var paramName = this.newParam(name)
            // set value for param placeholder
            this.params[paramName] = operatorValue
            // create sql
            whereSql += ` LIKE :${paramName}`
        }
        // > : value
        else if (operator === 'gt') {
            // get param name for value placeholder
            var paramName = this.newParam(name)
            // set value for param placeholder
            this.params[paramName] = operatorValue
            // create sql
            whereSql += ` > :${paramName}`
        }
        // >= : value
        else if (operator === 'gte') {
            // get param name for value placeholder
            var paramName = this.newParam(name)
            // set value for param placeholder
            this.params[paramName] = operatorValue
            // create sql
            whereSql += ` >= :${paramName}`
        }
        // < : value
        else if (operator === 'lt') {
            // get param name for value placeholder
            var paramName = this.newParam(name)
            // set value for param placeholder
            this.params[paramName] = operatorValue
            // create sql
            whereSql += ` < :${paramName}`
        }
        // <= : value
        else if (operator === 'lte') {
            // get param name for value placeholder
            var paramName = this.newParam(name)
            // set value for param placeholder
            this.params[paramName] = operatorValue
            // create sql
            whereSql += ` <= :${paramName}`
        }
        else if (operator === 'between') {
            assert.ok(Array.isArray(operatorValue), 'between value must be array in where '+name)
            assert.equal(operatorValue.length, 2, 'between array must have 2 elements in where '+name)
            // get param name for value placeholder
            var paramName1 = this.newParam(name)
            // set value for param placeholder
            this.params[paramName1] = operatorValue[0]
            // get param name for value placeholder
            var paramName2 = this.newParam(name)
            // set value for param placeholder
            this.params[paramName2] = operatorValue[1]
            // create sql
            whereSql += ` BETWEEN :${paramName1} AND :${paramName2}`
        }
        else if (operator === 'in') {
            assert.ok(Array.isArray(operatorValue), 'in value must be array in where '+name)
            // get placeholder for each in value
            var placeholders = _.map(operatorValue, v => {
                // get param name for each placeholder
                var paramName = this.newParam(name)
                // set value for param placeholder
                this.params[paramName] = v
                // create placeholder
                return spec.type === 'id' && this.model.binaryIds
                    ? `UNHEX(:${paramName})`
                    : `:${paramName}`
            })
            // create sql
            whereSql += ` IN(${placeholders.join(', ')})`
        }
        // = : value
        else if (operator === 'eq') {
            // get param name for value placeholder
            var paramName = this.newParam(name)
            // set value for param placeholder
            this.params[paramName] = operatorValue
            // create sql
            whereSql += spec.type === 'id' && this.model.binaryIds
                ? ` = UNHEX(:${paramName})`
                : ` = :${paramName}`
        }
        // operator type not supported
        else {
            throw new Error('invalid operator '+operator+' in where '+name)
        }
    }
    // query type not supported
    else {
        throw new Error('invalid value type '+typeof value+' in where '+name)
    }

    // if this is NOT statement then wrap in negation
    if (isNot) {
        whereSql = '!('+whereSql+')'
    }

    // add sql to list of where clauses
    this.where.push(whereSql)
}
509645
def create_object(self, data, view_kwargs):
        
        self.before_create_object(data, view_kwargs)

        relationship_fields = get_relationships(self.resource.schema, model_field=True)
        nested_fields = get_nested_fields(self.resource.schema, model_field=True)

        join_fields = relationship_fields + nested_fields

        obj = self.model(**{key: value
                            for (key, value) in data.items() if key not in join_fields})
        self.apply_relationships(data, obj)
        self.apply_nested_fields(data, obj)

        self.session.add(obj)
        try:
            self.session.commit()
        except JsonApiException as e:
            self.session.rollback()
            raise e
        except Exception as e:
            self.session.rollback()
            raise JsonApiException("Object creation error: " + str(e), source={'pointer': '/data'})

        self.after_create_object(obj, data, view_kwargs)

        return obj
302384
private function buildRelationships() {
        /** @var Relationship[] $relationships */
        $relationships = array();
        $dbCompareTable = new Table($this->getConfiguration()->getConnection(), $this->getTableName());
        foreach($dbCompareTable->getConstraints() as $constraint) {
            $relationship = new Relationship(
                $this->getConfiguration(),
                $this->getTableName(),
                implode(', ', $constraint->getLocalColumns()),
                $constraint->getRemoteTable(),
                implode(', ', $constraint->getRemoteColumns()),
                'belongsTo',
                'ON DELETE ' . $constraint->getDeleteAction() . ' ON UPDATE ' . $constraint->getUpdateAction()
            );
            $this->getAbstractClass()->addUse('Phalcon\Mvc\Model\Relation');
            $this->getAbstractClass()->addUse($relationship->getRemoteModel() . ' as Child' . $relationship->getRemoteShortModel());
            $relationships[] = $relationship;
        }

        //Get One to Many relationships

        $database = $this->getCurrentDatabaseName();
        $sql = 'SELECT DISTINCT(TABLE_NAME) as tableName FROM information_schema.`KEY_COLUMN_USAGE` WHERE REFERENCED_TABLE_NAME="' . $this->getTableName() . '" AND REFERENCED_TABLE_SCHEMA="' . $database . '"';
        /** @var ResultSet $results */
        $foreignKeys = $this->getConfiguration()->getConnection()->query($sql);
        while($foreignKey = $foreignKeys->fetch()) {
            $foreignKey = (object)$foreignKey;
            $tableName = $foreignKey->tableName;

            $dbCompareTable = new Table($this->getConfiguration()->getConnection(), $tableName);
            foreach($dbCompareTable->getConstraints() as $constraint) {
                if($constraint->getRemoteTable() == $this->getTableName()) {
                    if(implode(', ', $constraint->getRemoteColumns())==='venueId`, `userID') {
                        exit;
                    }
                    $relationship = new Relationship(
                        $this->getConfiguration(),
                        $this->getTableName(),
                        implode(', ', $constraint->getRemoteColumns()),
                        $tableName,
                        implode(', ', $constraint->getLocalColumns()),
                        'hasMany',
                        'ON DELETE ' . $constraint->getDeleteAction() . ' ON UPDATE ' . $constraint->getUpdateAction()
                    );
                    $this->getAbstractClass()->addUse('Phalcon\Mvc\Model\Relation');
                    $this->getAbstractClass()->addUse($relationship->getRemoteModel() . ' as Child' . $relationship->getRemoteShortModel());
                    $this->getAbstractClass()->addUse('Phalcon\Mvc\Model\Relation');
                    $this->getAbstractClass()->addUse('Phalcon\Mvc\Model\Resultset\Simple as ResultSet');
                    $this->getAbstractClass()->addUse($relationship->getRemoteModel() . ' as Child' . $relationship->getRemoteShortModel());
                    $relationships[] = $relationship;
                }
            }

        }
        foreach($relationships as $relationship) {
            $relationship->setRelationships($relationships);
        }
        $this->setRelationships($relationships);
    }
679646
function( options ){

			options 			= options || {};
			options.$db 		= cOptions.db;
			options.$dbName 	= cOptions.database;
			options.$model 		= cOptions.model;

			return new cOptions.cls( options );
		}
1095761
def find_models(self, constructor, constraints=None, *, columns=None, order_by=None,
                  limiting=None, table_name=None):
    """"""
    return self._find_models(
      constructor, table_name or constructor.table_name, constraints, columns=columns,
      order_by=order_by, limiting=limiting)