Python sqlalchemy.sql.null() Examples

The following are 14 code examples of sqlalchemy.sql.null(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module sqlalchemy.sql , or try the search function .
Example #1
Source File: backend.py    From blitzdb with MIT License 6 votes vote down vote up
def _serialize_and_update_indexes(self,obj,collection,d,for_update = False):

        pk_type = self._index_fields[collection]['pk']['type']

        for index_field,index_params in self._index_fields[collection].items():
            try:
                if for_update:
                    value = obj[index_field]
                else:
                    value = get_value(obj,index_field)
                if value is None:
                    if not index_params['field'].nullable:
                        raise ValueError("Value for %s is `None`, but this is a mandatory field!" % index_field)
                    d[index_params['column']] = null()
                else:
                    d[index_params['column']] = expression.cast(value,index_params['type'])
            except KeyError:
                if for_update:
                    continue
                if index_params['field'].default is not None:
                    d[index_params['column']] = index_params['field'].default
                elif not index_params['field'].nullable:
                    raise ValueError("No value for %s given, but this is a mandatory field!" % index_field)
                else:
                    d[index_params['column']] = null() 
Example #2
Source File: update_match.py    From oslo.db with Apache License 2.0 6 votes vote down vote up
def _sql_crit(expression, value):
    """Produce an equality expression against the given value.

    This takes into account a value that is actually a collection
    of values, as well as a value of None or collection that contains
    None.

    """

    values = utils.to_list(value, default=(None, ))
    if len(values) == 1:
        if values[0] is None:
            return expression == sql.null()
        else:
            return expression == values[0]
    elif _none_set.intersection(values):
        return sql.or_(
            expression == sql.null(),
            _sql_crit(expression, set(values).difference(_none_set))
        )
    else:
        return expression.in_(values) 
Example #3
Source File: api.py    From coriolis with GNU Affero General Public License v3.0 6 votes vote down vote up
def _get_replica_schedules_filter(context, replica_id=None,
                                  schedule_id=None, expired=True):
    now = timeutils.utcnow()
    q = _soft_delete_aware_query(context, models.ReplicaSchedule)
    q = q.join(models.Replica)
    sched_filter = q.filter()
    if is_user_context(context):
        sched_filter = sched_filter.filter(
            models.Replica.project_id == context.tenant)

    if replica_id:
        sched_filter = sched_filter.filter(
            models.Replica.id == replica_id)
    if schedule_id:
        sched_filter = sched_filter.filter(
            models.ReplicaSchedule.id == schedule_id)
    if not expired:
        sched_filter = sched_filter.filter(
            or_(models.ReplicaSchedule.expiration_date == null(),
                models.ReplicaSchedule.expiration_date > now))
    return sched_filter 
Example #4
Source File: test_auth.py    From flask-resty with MIT License 5 votes vote down vote up
def auth():
    class FakeAuthentication(AuthenticationBase):
        def get_request_credentials(self):
            return flask.request.args.get("user_id")

    class UserAuthorization(
        AuthorizeModifyMixin, HasCredentialsAuthorizationBase
    ):
        def filter_query(self, query, view):
            return query.filter(
                (view.model.owner_id == self.get_request_credentials())
                | (view.model.owner_id == sql.null())
            )

        def authorize_create_item(self, item):
            super().authorize_create_item(item)

            if item.name == "Updated":
                raise ApiError(403, {"code": "invalid_name"})

        def authorize_modify_item(self, item, action):
            if item.owner_id != self.get_request_credentials():
                raise ApiError(403, {"code": "invalid_user"})

    authorization = UserAuthorization()
    authorization.authorize_modify_item = Mock(
        wraps=authorization.authorize_modify_item, autospec=True
    )

    class BearerWithFallbackAuthentication(HeaderAuthentication):
        credentials_arg = "secret"

    return {
        "authentication": FakeAuthentication(),
        "authorization": authorization,
        "bearer_with_fallback_authentication": (
            BearerWithFallbackAuthentication()
        ),
    } 
Example #5
Source File: test_types.py    From sqlalchemy with MIT License 5 votes vote down vote up
def test_bind_serialize_None(self):
        proc = self.test_table.c.test_column.type._cached_bind_processor(
            self.dialect
        )
        eq_(proc(None), "null") 
Example #6
Source File: test_types.py    From sqlalchemy with MIT License 5 votes vote down vote up
def test_bind_serialize_none_as_null(self):
        proc = JSON(none_as_null=True)._cached_bind_processor(self.dialect)
        eq_(proc(None), None)
        eq_(proc(null()), None) 
Example #7
Source File: test_types.py    From sqlalchemy with MIT License 5 votes vote down vote up
def test_bind_serialize_null(self):
        proc = self.test_table.c.test_column.type._cached_bind_processor(
            self.dialect
        )
        eq_(proc(null()), None) 
Example #8
Source File: test_types.py    From sqlalchemy with MIT License 5 votes vote down vote up
def test_result_deserialize_null(self):
        proc = self.test_table.c.test_column.type._cached_result_processor(
            self.dialect, None
        )
        eq_(proc("null"), None) 
Example #9
Source File: test_operators.py    From sqlalchemy with MIT License 5 votes vote down vote up
def test_fourteen(self):
        x = column("x")
        self.assert_compile(
            select([x]).where(~null()), "SELECT x WHERE NOT NULL"
        ) 
Example #10
Source File: test_operators.py    From sqlalchemy with MIT License 5 votes vote down vote up
def test_constant_render_distinct(self):
        self.assert_compile(
            select([null(), null()]), "SELECT NULL AS anon_1, NULL AS anon__1"
        )
        self.assert_compile(
            select([true(), true()]), "SELECT true AS anon_1, true AS anon__1"
        )
        self.assert_compile(
            select([false(), false()]),
            "SELECT false AS anon_1, false AS anon__1",
        ) 
Example #11
Source File: test_operators.py    From sqlalchemy with MIT License 5 votes vote down vote up
def test_constant_render_distinct_use_labels(self):
        self.assert_compile(
            select([null(), null()]).apply_labels(),
            "SELECT NULL AS anon_1, NULL AS anon__1",
        )
        self.assert_compile(
            select([true(), true()]).apply_labels(),
            "SELECT true AS anon_1, true AS anon__1",
        )
        self.assert_compile(
            select([false(), false()]).apply_labels(),
            "SELECT false AS anon_1, false AS anon__1",
        ) 
Example #12
Source File: test_operators.py    From sqlalchemy with MIT License 5 votes vote down vote up
def test_is_eq_precedence_flat(self):
        self.assert_compile(
            (self.table1.c.name == null())
            != (self.table1.c.description == null()),
            "(mytable.name IS NULL) != (mytable.description IS NULL)",
        ) 
Example #13
Source File: d2e48801c8ef_introducing_node_state_attribute.py    From ironic-inspector with Apache License 2.0 5 votes vote down vote up
def upgrade():
    state_enum = sa.Enum(*istate.States.all(), name='node_state')
    state_enum.create(op.get_bind())

    op.add_column('nodes', sa.Column('version_id', sa.String(36),
                                     server_default=''))
    op.add_column('nodes', sa.Column('state', state_enum,
                                     nullable=False,
                                     default=istate.States.finished,
                                     server_default=istate.States.finished))
    # correct the state: finished -> error if Node.error is not null
    stmt = Node.update().where(Node.c.error != sql.null()).values(
        {'state': op.inline_literal(istate.States.error)})
    op.execute(stmt) 
Example #14
Source File: backend.py    From blitzdb with MIT License 4 votes vote down vote up
def _serialize_and_update_relations(self,obj,collection,d,deletes,inserts,autosave_dependent = True,for_update = False, save_cache=None):

        pk_type = self._index_fields[collection]['pk']['type']

        for related_field,relation_params in self._related_fields[collection].items():

            #we skip back-references...
            if relation_params.get('is_backref',None):
                continue

            try:
                if for_update:
                    value = obj[related_field]
                else:
                    value = get_value(obj,related_field)
                if isinstance(relation_params['field'],ManyToManyField):
                    if isinstance(value,ManyToManyProxy):
                        continue
                    relationship_table = self._relationship_tables[collection][related_field]
                    deletes.append(relationship_table.delete().where(relationship_table.c[relation_params['pk_field_name']] == expression.cast(obj['pk'],pk_type)))
                    for element in value:
                        if not isinstance(element,Document):
                            raise AttributeError("ManyToMany field %s contains an invalid value!" % related_field)
                        if autosave_dependent and element.pk is None:
                            self.save(element, save_cache=save_cache)
                        if element.pk is None:
                            raise AttributeError("Related document in field %s has no primary key!" % related_field)
                        ed = {
                            relation_params['pk_field_name'] : obj['pk'],
                            relation_params['related_pk_field_name'] : element.pk,
                        }
                        inserts.append(relationship_table.insert().values(**ed))
                elif isinstance(relation_params['field'],ForeignKeyField):
                    if value is None:
                        if not relation_params['field'].nullable:
                            raise AttributeError("Field %s cannot be None!" % related_field)
                        d[relation_params['column']] = null()
                    elif not isinstance(value,Document):
                        raise AttributeError("Field %s must be a document!" % related_field)
                    else:
                        if autosave_dependent and value.pk is None:
                            self.save(value, save_cache=save_cache)
                        if value.pk is None:
                            raise AttributeError("Related document in field %s has no primary key!" % related_field)
                        d[relation_params['column']] = expression.cast(value.pk,relation_params['type'])

            except KeyError:
                if for_update:
                    continue
                if isinstance(relation_params['field'],ForeignKeyField):
                    if not relation_params['field'].nullable:
                        raise ValueError("No value for %s given, but this is a mandatory field!" % relation_params['key'])
                    d[relation_params['column']] = null()