Add a RAW JOIN source to the query
513443
public function raw_join($table, $constraint, $table_alias, $parameters = [])
        {
            // Add table alias if present
            if (!is_null($table_alias)) {
                $table_alias = $this->_quoteIdentifier($table_alias);
                $table .= " {$table_alias}";
            }

            $this->_values = array_merge($this->_values, $parameters);

            // Build the constraint
            if (Arrays::is($constraint)) {
                list($first_column, $operator, $second_column) = $constraint;

                $first_column = $this->_quoteIdentifier($first_column);
                $second_column = $this->_quoteIdentifier($second_column);
                $constraint = "{$first_column} {$operator} {$second_column}";
            }

            $this->_join_sources[] = "{$table} ON {$constraint}";

            return $this;
        }
355026
static QueryMeta buildInsertSql(ActiveRecord activeRecord) {
        QueryMeta     queryMeta = new QueryMeta();
        String        tableName = activeRecord.getTableName();
        StringBuilder sb        = new StringBuilder(Const.SQL_INSERT + " ");
        sb.append(tableName);
        sb.append(" (");

        StringBuffer values = new StringBuffer(" VALUES (");
        Stream.of(activeRecord.getClass().getDeclaredFields())
                .filter(field -> null == field.getAnnotation(Transient.class))
                .forEach(field -> {
                    try {
                        field.setAccessible(true);
                        if (field.get(activeRecord) != null) {
                            Pair<String, String> pair = getColumnName(field);
                            sb.append(pair.getLeft()).append(", ");
                            values.append(':').append(pair.getRight()).append(", ");
                        }
                    } catch (Exception e) {
                    }
                });

        sb.append(')');
        values.append(')');

        String sql = sb.append(values).toString().replace(", )", ")");
        queryMeta.setSql(sql);
        return queryMeta;
    }
253461
def _join_results(self, results, coarse, join):
    '''
    
    '''
    rval = OrderedDict()
    i_keys = set()
    for res in results:
      i_keys.update( res.keys() )
    for i_key in sorted(i_keys):
      if coarse:
        rval[i_key] = join( [res.get(i_key) for res in results] )
      else:
        rval[i_key] = OrderedDict()
        r_keys = set()
        for res in results:
          r_keys.update( res.get(i_key,{}).keys() )
        for r_key in sorted(r_keys):
          rval[i_key][r_key] = join( [res.get(i_key,{}).get(r_key) for res in results] )
    return rval
359269
def query_insert(self, direction='max'):
        
        if direction == 'min':
            return Layer.objects.aggregate(
                Min('last_updated'))['last_updated__min'].strftime('%Y-%m-%dT%H:%M:%SZ')
        return self._get_repo_filter(Layer.objects).aggregate(
            Max('last_updated'))['last_updated__max'].strftime('%Y-%m-%dT%H:%M:%SZ')
631816
public QueryBuilder<T, ID> join(QueryBuilder<?, ?> joinedQueryBuilder, JoinType type, JoinWhereOperation operation)
			throws SQLException {
		addJoinInfo(type, null, null, joinedQueryBuilder, operation);
		return this;
	}
1118430
def _compile_update_join_wheres(self, query):
        
        join_wheres = []

        for join in query.joins:
            for clause in join.clauses:
                join_wheres.append(self._compile_join_constraints(clause))

        return " ".join(join_wheres)
1290491
def get_raw_query(self):
        
        query = self.base_query.copy()
        search_query = self.search_query.copy()
        query.update(search_query)

        # Add sorting criteria
        sorting = self.resolve_sorting(query)
        query.update(sorting)

        # Check if sort_on is an index and if is sortable. Otherwise, assume
        # the sorting must be done manually
        catalog = api.get_tool(self.catalog_name)
        sort_on = query.get("sort_on", None)
        if sort_on and not self.is_sortable_index(sort_on, catalog):
            del(query["sort_on"])
        return query
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")
1219809
def order_by_raw(self, sql, bindings=None):
        
        if bindings is None:
            bindings = []

        type = "raw"

        self.orders.append({"type": type, "sql": sql})

        self.add_binding(bindings, "order")

        return self
370783
def rawsql(query, ec=None):
    
    if isinstance(query, Result):
        query = query.get_query()

    ec = ec or __default_engine__
    if isinstance(ec, (str, unicode)):
        engine = engine_manager[ec]
        dialect = engine.engine.dialect
    else:
        dialect = ec.dialect
    if isinstance(query, (str, unicode)):
        return query
    # comp = query.compile(dialect=dialect)

    compiler = query._compiler(dialect)
    class LiteralCompiler(compiler.__class__):
        def visit_bindparam(
                self, bindparam, within_columns_clause=False,
                literal_binds=False, **kwargs
        ):
            return super(LiteralCompiler, self).render_literal_bindparam(
                    bindparam, within_columns_clause=within_columns_clause,
                    literal_binds=literal_binds, **kwargs
            )
        def render_literal_value(self, value, type_):
            """Render the value of a bind parameter as a quoted literal.

            This is used for statement sections that do not accept bind paramters
            on the target driver/database.

            This should be implemented by subclasses using the quoting services
            of the DBAPI.

            """
            return repr_value(value)

    compiler = LiteralCompiler(dialect, query)
    return str(compiler.process(query)).replace('\n', '')
1184838
private void appendJoinSQL92(Join join, StringBuffer where, StringBuffer buf)
    {
        if (join.isOuter)
        {
            buf.append(" LEFT OUTER JOIN ");
        }
        else
        {
            buf.append(" INNER JOIN ");
        }
        if (join.right.hasJoins())
        {
            buf.append("(");
            appendTableWithJoins(join.right, where, buf);
            buf.append(")");
        }
        else
        {
            appendTableWithJoins(join.right, where, buf);
        }
        buf.append(" ON ");
        join.appendJoinEqualities(buf);
    }
157282
function buildJoinRelation (join) {
    // if there is already a join on this relation then throw error
    assert.ok(!this.joinRelations[join.relation], 'join already exists for '+join.relation)
    // get relation for join
    var relation = this.model.relation(join.relation)
    // add join to joins
    this.joinRelations[join.relation] = join
    this.joinRelationNames.push(join.relation)
    // create alias for relation table to use in query
    join.relationAlias = this.newAlias(relation.model.name)
    // if join is via another model then join on that table
    if (relation.via) {
        // create alias for via table to use in query
        join.viaAlias = this.newAlias(relation.viaModel.name)
        // add join on alias table to query
        this.join.push( this.joinSql(relation.viaModel.name, join.viaAlias, relation.viaModelIdColumn, this.alias, relation.modelIdColumn, join.left ? 'LEFT JOIN' : 'JOIN') )
        // add join from alias to relation table to query
        this.join.push( this.joinSql(relation.model.name, join.relationAlias, relation.relationIdColumn, join.viaAlias, relation.viaRelationIdColumn, join.left ? 'LEFT JOIN' : 'JOIN') )
    }
    // join directly to related table
    else {
        this.join.push( this.joinSql(relation.model.name, join.relationAlias, relation.relationIdColumn, this.alias, relation.modelIdColumn, join.left ? 'LEFT JOIN' : 'JOIN') )
    }
}
525780
def compile(self):
        
        params = self.column_params + self.join_params + self.params
        if self.limit and self.limit >= 0:
            self.sql_limit = 'LIMIT ?'
            params += [self.limit]
        return (self.sql, params, self.keys)
395925
public QueryBuilder<T, ID> join(String localColumnName, String joinedColumnName,
			QueryBuilder<?, ?> joinedQueryBuilder, JoinType type, JoinWhereOperation operation) throws SQLException {
		addJoinInfo(type, localColumnName, joinedColumnName, joinedQueryBuilder, operation);
		return this;
	}
696005
def apply_mapping(raw_row, mapping):
    '''
    
    '''
    row = {target: mapping_func(raw_row[source_key])
           for target, (mapping_func, source_key)
           in mapping.fget().items()}
    return row
627994
def build(self, search, raw_query):
        
        unmatched_items = {}
        for expression, value in raw_query.items():
            # Parse query expression into tokens.
            tokens = expression.split(TOKEN_SEPARATOR)

            field = tokens[0]
            tail = tokens[1:]

            if field not in self.fields:
                unmatched_items[expression] = value
                continue

            # Map field alias to final field.
            field = self.fields_map.get(field, field)

            # Parse lookup expression. Currently only no token or a single token is allowed.
            if tail:
                if len(tail) > 1:
                    raise NotImplementedError("Nested lookup expressions are not supported")

                lookup = self.get_lookup(tail[0])
                search = lookup.apply(search, field, value)
            else:
                # Default lookup.
                custom_filter = getattr(self.custom_filter_object, 'custom_filter_{}'.format(field), None)
                if custom_filter is not None:
                    search = custom_filter(value, search)
                elif isinstance(value, list):
                    # Default is 'should' between matches. If you need anything else,
                    # a custom filter for this field should be implemented.
                    filters = [Q('match', **{field: item}) for item in value]
                    search = search.query('bool', should=filters)
                else:
                    search = search.query('match', **{field: {'query': value, 'operator': 'and'}})

        return (search, unmatched_items)
219421
protected function addSearchJoin(Builder $query, $joining_table, $foreign_key, $related_key, $alias)
    {
        // We need to join to the intermediate table
        $local_table = $this->getModel()->getTable();

        // Set the way the table will be join, with an alias or without
        $table = $alias ? "{$joining_table} as {$alias}" : $joining_table;

        // Create an alias for the join
        $alias = $alias ?: $joining_table;

        // Create the join
        $query->join($table, "{$alias}.{$foreign_key}", "{$local_table}.{$related_key}");

        return $alias;
    }