Пример #1
0
    def as_sql(self):
        # We don't need quote_name_unless_alias() here, since these are all
        # going to be column names (so we can avoid the extra overhead).
        qn = self.connection.ops.quote_name
        opts = self.query.get_meta()
        result = [
            'INSERT INTO %s' %
            qn(connection.get_schemaed_db_table(opts.db_table))
        ]

        has_fields = bool(self.query.fields)
        fields = self.query.fields if has_fields else [opts.pk]
        result.append('(%s)' % ', '.join(qn(f.column) for f in fields))

        if has_fields:
            value_rows = [[
                self.prepare_value(field, self.pre_save_val(field, obj))
                for field in fields
            ] for obj in self.query.objs]
        else:
            # An empty object.
            value_rows = [[self.connection.ops.pk_default_value()]
                          for _ in self.query.objs]
            fields = [None]

        # Currently the backends just accept values when generating bulk
        # queries and generate their own placeholders. Doing that isn't
        # necessary and it should be possible to use placeholders and
        # expressions in bulk inserts too.
        can_bulk = (not self.return_id
                    and self.connection.features.has_bulk_insert)

        placeholder_rows, param_rows = self.assemble_as_sql(fields, value_rows)

        if self.return_id and self.connection.features.can_return_id_from_insert:
            params = param_rows[0]
            # gkiwi no need ??
            col = "%s.%s" % (qn(connection.get_schemaed_db_table(
                opts.db_table)), qn(opts.pk.column))
            result.append("VALUES (%s)" % ", ".join(placeholder_rows[0]))
            r_fmt, r_params = self.connection.ops.return_insert_id()
            # Skip empty r_fmt to allow subclasses to customize behavior for
            # 3rd party backends. Refs #19096.
            if r_fmt:
                result.append(r_fmt % col)
                params += r_params
            return [(" ".join(result), tuple(params))]

        if can_bulk:
            result.append(
                self.connection.ops.bulk_insert_sql(fields, placeholder_rows))
            return [(" ".join(result), tuple(p for ps in param_rows
                                             for p in ps))]
        else:
            return [(" ".join(result + ["VALUES (%s)" % ", ".join(p)]), vals)
                    for p, vals in zip(placeholder_rows, param_rows)]
Пример #2
0
 def wrapper(*args, **kwargs):
     schema_name_prefix = connection.schema_name_prefix
     for arg in args:
         if isinstance(arg, ModelBase):
             db_table = arg._meta.db_table
             arg._meta.db_table = connection.get_schemaed_db_table(
                 db_table)
     for (k, v) in kwargs.items():
         if isinstance(v, ModelBase):
             db_table = v._meta.db_table
             v._meta.db_table = connection.get_schemaed_db_table(
                 db_table)
     return func(*args, **kwargs)
 def as_sql(self, compiler, connection):
     alias_str = ' %s' % self.table_alias
     table_name = self.table_name
     if hasattr(connection, 'get_schemaed_db_table'):
         table_name = connection.get_schemaed_db_table(self.table_name)
     base_sql = compiler.quote_name_unless_alias(table_name)
     return base_sql + alias_str, []
Пример #4
0
    def _create_fk_sql(self, model, field, suffix):
        from_table = model._meta.db_table
        from_column = field.column
        to_table = connection.get_schemaed_db_table(field.target_field.model._meta.db_table)
        to_column = field.target_field.column
        suffix = suffix % {
            "to_table": to_table,
            "to_column": to_column,
        }

        return self.sql_create_fk % {
            "table": self.quote_name(from_table),
            "name": self.quote_name(self._create_index_name(model, [from_column], suffix=suffix)),
            "column": self.quote_name(from_column),
            "to_table": self.quote_name(to_table),
            "to_column": self.quote_name(to_column),
        }
Пример #5
0
 def as_sql(self):
     """
     Creates the SQL for this query. Returns the SQL string and list of
     parameters.
     """
     assert len([t for t in self.query.tables if self.query.alias_refcount[t] > 0]) == 1, \
         "Can only delete from one table at a time."
     qn = self.quote_name_unless_alias
     db_table = self.query.tables[0]
     schemaed_db_table = connection.get_schemaed_db_table(db_table)
     result = [
         'DELETE {db_table} FROM {schemaed_db_table} {db_table}'.format(
             schemaed_db_table=qn(schemaed_db_table), db_table=qn(db_table))
     ]
     where, params = self.compile(self.query.where)
     if where:
         result.append('WHERE %s' % where)
     return ' '.join(result), tuple(params)
    def as_sql(self, compiler, connection):
        """
        Generates the full
           LEFT OUTER JOIN sometable ON sometable.somecol = othertable.othercol, params
        clause for this join.
        """
        join_conditions = []
        params = []
        qn = compiler.quote_name_unless_alias
        qn2 = connection.ops.quote_name

        # Add a join condition for each pair of joining columns.
        for index, (lhs_col, rhs_col) in enumerate(self.join_cols):
            join_conditions.append('%s.%s = %s.%s' % (
                qn(self.parent_alias),
                qn2(lhs_col),
                qn(self.table_alias),
                qn2(rhs_col),
            ))

        # Add a single condition inside parentheses for whatever
        # get_extra_restriction() returns.
        extra_cond = self.join_field.get_extra_restriction(
            compiler.query.where_class, self.table_alias, self.parent_alias)
        if extra_cond:
            extra_sql, extra_params = compiler.compile(extra_cond)
            join_conditions.append('(%s)' % extra_sql)
            params.extend(extra_params)

        if not join_conditions:
            # This might be a rel on the other end of an actual declared field.
            declared_field = getattr(self.join_field, 'field', self.join_field)
            raise ValueError(
                "Join generated an empty ON clause. %s did not yield either "
                "joining columns or extra restrictions." % declared_field.__class__
            )
        on_clause_sql = ' AND '.join(join_conditions)
        #gkiwi
        alias_str = ' %s' % self.table_alias
        sql = '%s %s%s ON (%s)' % (self.join_type, qn(connection.get_schemaed_db_table(self.table_name)), alias_str, on_clause_sql)
        return sql, params
Пример #7
0
    def ensure_schema(self):
        """
        Ensures the table exists and has the correct schema.
        """
        # If the table's there, that's fine - we've never changed its schema
        # in the codebase.

        # gkiwi #TOPATCH
        from django.db import connection
        db_table = connection.get_schemaed_db_table(
            self.Migration._meta.db_table)
        # end

        if db_table in self.connection.introspection.table_names(
                self.connection.cursor()):
            return
        # Make the table
        try:
            with self.connection.schema_editor() as editor:
                editor.create_model(self.Migration)
        except DatabaseError as exc:
            raise MigrationSchemaMissing(
                "Unable to create the django_migrations table (%s)" % exc)
Пример #8
0
    def as_sql(self):
        """
        Creates the SQL for this query. Returns the SQL string and list of
        parameters.
        """
        self.pre_sql_setup()
        if not self.query.values:
            return '', ()
        qn = self.quote_name_unless_alias
        db_table = self.query.tables[0]
        schemaed_db_table = connection.get_schemaed_db_table(db_table)
        result = [
            'UPDATE {schemaed_db_table} {db_table}'.format(
                schemaed_db_table=qn(schemaed_db_table), db_table=qn(db_table))
        ]
        result.append('SET')
        values, update_params = [], []
        for field, model, val in self.query.values:
            if hasattr(val, 'resolve_expression'):
                val = val.resolve_expression(self.query,
                                             allow_joins=False,
                                             for_save=True)
                if val.contains_aggregate:
                    raise FieldError(
                        "Aggregate functions are not allowed in this query")
            elif hasattr(val, 'prepare_database_save'):
                if field.remote_field:
                    val = field.get_db_prep_save(
                        val.prepare_database_save(field),
                        connection=self.connection,
                    )
                else:
                    raise TypeError(
                        "Tried to update field %s with a model instance, %r. "
                        "Use a value compatible with %s." %
                        (field, val, field.__class__.__name__))
            else:
                val = field.get_db_prep_save(val, connection=self.connection)

            # Getting the placeholder for the field.
            if hasattr(field, 'get_placeholder'):
                placeholder = field.get_placeholder(val, self, self.connection)
            else:
                placeholder = '%s'
            name = field.column
            if hasattr(val, 'as_sql'):
                sql, params = self.compile(val)
                values.append('%s = %s' % (qn(name), sql))
                update_params.extend(params)
            elif val is not None:
                values.append('%s = %s' % (qn(name), placeholder))
                update_params.append(val)
            else:
                values.append('%s = NULL' % qn(name))
        if not values:
            return '', ()
        result.append(', '.join(values))
        where, params = self.compile(self.query.where)
        if where:
            result.append('WHERE %s' % where)
        return ' '.join(result), tuple(update_params + params)