Python sqlalchemy.null() Examples

The following are 28 code examples of sqlalchemy.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 , or try the search function .
Example #1
Source File: sqltypes.py    From pyRevit with GNU General Public License v3.0 6 votes vote down vote up
def __init__(self, none_as_null=False):
        """Construct a :class:`.types.JSON` type.

        :param none_as_null=False: if True, persist the value ``None`` as a
         SQL NULL value, not the JSON encoding of ``null``.   Note that
         when this flag is False, the :func:`.null` construct can still
         be used to persist a NULL value::

             from sqlalchemy import null
             conn.execute(table.insert(), data=null())

         .. note::

              :paramref:`.JSON.none_as_null` does **not** apply to the
              values passed to :paramref:`.Column.default` and
              :paramref:`.Column.server_default`; a value of ``None`` passed for
              these parameters means "no default present".

         .. seealso::

              :attr:`.types.JSON.NULL`

         """
        self.none_as_null = none_as_null 
Example #2
Source File: test_compiler.py    From sqlalchemy with MIT License 6 votes vote down vote up
def test_do_update_set_clause_literal(self):
        i = insert(self.table_with_metadata).values(myid=1, name="foo")
        i = i.on_conflict_do_update(
            index_elements=["myid"],
            set_=OrderedDict(
                [("name", "I'm a name"), ("description", null())]
            ),
        )
        self.assert_compile(
            i,
            "INSERT INTO mytable (myid, name) VALUES "
            "(%(myid)s, %(name)s) ON CONFLICT (myid) "
            "DO UPDATE SET name = %(param_1)s, "
            "description = NULL",
            {"myid": 1, "name": "foo", "param_1": "I'm a name"},
        ) 
Example #3
Source File: json.py    From jbox with MIT License 6 votes vote down vote up
def __init__(self, none_as_null=False):
        """Construct a :class:`.JSON` type.

        :param none_as_null: if True, persist the value ``None`` as a
         SQL NULL value, not the JSON encoding of ``null``.   Note that
         when this flag is False, the :func:`.null` construct can still
         be used to persist a NULL value::

             from sqlalchemy import null
             conn.execute(table.insert(), data=null())

         .. versionchanged:: 0.9.8 - Added ``none_as_null``, and :func:`.null`
            is now supported in order to persist a NULL value.

         """
        self.none_as_null = none_as_null 
Example #4
Source File: sqltypes.py    From sqlalchemy with MIT License 6 votes vote down vote up
def __init__(self, none_as_null=False):
        """Construct a :class:`_types.JSON` type.

        :param none_as_null=False: if True, persist the value ``None`` as a
         SQL NULL value, not the JSON encoding of ``null``.   Note that
         when this flag is False, the :func:`.null` construct can still
         be used to persist a NULL value::

             from sqlalchemy import null
             conn.execute(table.insert(), data=null())

         .. note::

              :paramref:`_types.JSON.none_as_null` does **not** apply to the
              values passed to :paramref:`_schema.Column.default` and
              :paramref:`_schema.Column.server_default`; a value of ``None``
              passed for these parameters means "no default present".

         .. seealso::

              :attr:`.types.JSON.NULL`

         """
        self.none_as_null = none_as_null 
Example #5
Source File: alarm_definitions_repository.py    From monasca-api with Apache License 2.0 6 votes vote down vote up
def _get_alarm_definition(self, conn, tenant_id, _id):
        ad = self.ad_s
        query = (self.base_query
                 .select_from(self.base_query_from)
                 .where(ad.c.tenant_id == bindparam('b_tenant_id'))
                 .where(ad.c.id == bindparam('b_id'))
                 .where(ad.c.deleted_at == null()))

        row = conn.execute(query,
                           b_tenant_id=tenant_id,
                           b_id=_id).fetchone()

        if row is not None:
            return dict(row)
        else:
            raise exceptions.DoesNotExistException 
Example #6
Source File: json.py    From stdm with GNU General Public License v2.0 6 votes vote down vote up
def __init__(self, none_as_null=False):
        """Construct a :class:`.JSON` type.

        :param none_as_null: if True, persist the value ``None`` as a
         SQL NULL value, not the JSON encoding of ``null``.   Note that
         when this flag is False, the :func:`.null` construct can still
         be used to persist a NULL value::

             from sqlalchemy import null
             conn.execute(table.insert(), data=null())

         .. versionchanged:: 0.9.8 - Added ``none_as_null``, and :func:`.null`
            is now supported in order to persist a NULL value.

         """
        self.none_as_null = none_as_null 
Example #7
Source File: test_query.py    From sqlalchemy with MIT License 6 votes vote down vote up
def test_filter_by(self):
        User, Address = self.classes.User, self.classes.Address

        sess = create_session()
        user = sess.query(User).get(8)
        assert [Address(id=2), Address(id=3), Address(id=4)] == sess.query(
            Address
        ).filter_by(user=user).all()

        # many to one generates IS NULL
        assert [] == sess.query(Address).filter_by(user=None).all()
        assert [] == sess.query(Address).filter_by(user=null()).all()

        # one to many generates WHERE NOT EXISTS
        assert [User(name="chuck")] == sess.query(User).filter_by(
            addresses=None
        ).all()
        assert [User(name="chuck")] == sess.query(User).filter_by(
            addresses=null()
        ).all() 
Example #8
Source File: sqltypes.py    From planespotter with MIT License 6 votes vote down vote up
def __init__(self, none_as_null=False):
        """Construct a :class:`.types.JSON` type.

        :param none_as_null=False: if True, persist the value ``None`` as a
         SQL NULL value, not the JSON encoding of ``null``.   Note that
         when this flag is False, the :func:`.null` construct can still
         be used to persist a NULL value::

             from sqlalchemy import null
             conn.execute(table.insert(), data=null())

         .. note::

              :paramref:`.JSON.none_as_null` does **not** apply to the
              values passed to :paramref:`.Column.default` and
              :paramref:`.Column.server_default`; a value of ``None`` passed for
              these parameters means "no default present".

         .. seealso::

              :attr:`.types.JSON.NULL`

         """
        self.none_as_null = none_as_null 
Example #9
Source File: sqltypes.py    From jarvis with GNU General Public License v2.0 6 votes vote down vote up
def __init__(self, none_as_null=False):
        """Construct a :class:`.types.JSON` type.

        :param none_as_null=False: if True, persist the value ``None`` as a
         SQL NULL value, not the JSON encoding of ``null``.   Note that
         when this flag is False, the :func:`.null` construct can still
         be used to persist a NULL value::

             from sqlalchemy import null
             conn.execute(table.insert(), data=null())

         .. note::

              :paramref:`.JSON.none_as_null` does **not** apply to the
              values passed to :paramref:`.Column.default` and
              :paramref:`.Column.server_default`; a value of ``None`` passed for
              these parameters means "no default present".

         .. seealso::

              :attr:`.types.JSON.NULL`

         """
        self.none_as_null = none_as_null 
Example #10
Source File: sqltypes.py    From android_universal with MIT License 6 votes vote down vote up
def __init__(self, none_as_null=False):
        """Construct a :class:`.types.JSON` type.

        :param none_as_null=False: if True, persist the value ``None`` as a
         SQL NULL value, not the JSON encoding of ``null``.   Note that
         when this flag is False, the :func:`.null` construct can still
         be used to persist a NULL value::

             from sqlalchemy import null
             conn.execute(table.insert(), data=null())

         .. note::

              :paramref:`.JSON.none_as_null` does **not** apply to the
              values passed to :paramref:`.Column.default` and
              :paramref:`.Column.server_default`; a value of ``None`` passed for
              these parameters means "no default present".

         .. seealso::

              :attr:`.types.JSON.NULL`

         """
        self.none_as_null = none_as_null 
Example #11
Source File: test_types.py    From sqlalchemy with MIT License 5 votes vote down vote up
def _assert_column_is_JSON_NULL(self, conn, column="data"):
        col = self.tables.data_table.c[column]
        data = conn.execute(
            select([col]).where(cast(col, String) == "null")
        ).fetchall()
        eq_([d for d, in data], [None]) 
Example #12
Source File: d00d6e3f38c4_change_created_finished_at_type.py    From ironic-inspector with Apache License 2.0 5 votes vote down vote up
def upgrade():
    started_at = sa.Column('started_at', sa.types.Float, nullable=True)
    finished_at = sa.Column('finished_at', sa.types.Float, nullable=True)
    temp_started_at = sa.Column("temp_started_at", sa.types.DateTime,
                                nullable=True)
    temp_finished_at = sa.Column("temp_finished_at", sa.types.DateTime,
                                 nullable=True)
    uuid = sa.Column("uuid", sa.String(36), primary_key=True)

    op.add_column("nodes", temp_started_at)
    op.add_column("nodes", temp_finished_at)

    t = sa.table('nodes', started_at, finished_at,
                 temp_started_at, temp_finished_at, uuid)

    conn = op.get_bind()
    rows = conn.execute(sa.select([t.c.started_at, t.c.finished_at, t.c.uuid]))
    for row in rows:
        temp_started = datetime.datetime.utcfromtimestamp(row['started_at'])
        temp_finished = row['finished_at']
        # Note(milan) this is just a precaution; sa.null shouldn't happen here
        if temp_finished is not None:
            temp_finished = datetime.datetime.utcfromtimestamp(temp_finished)
        conn.execute(t.update().where(t.c.uuid == row.uuid).values(
            temp_started_at=temp_started, temp_finished_at=temp_finished))

    with op.batch_alter_table('nodes') as batch_op:
        batch_op.drop_column('started_at')
        batch_op.drop_column('finished_at')
        batch_op.alter_column('temp_started_at',
                              existing_type=sa.types.DateTime,
                              nullable=True,
                              new_column_name='started_at')
        batch_op.alter_column('temp_finished_at',
                              existing_type=sa.types.DateTime,
                              nullable=True,
                              new_column_name='finished_at') 
Example #13
Source File: json.py    From jarvis with GNU General Public License v2.0 5 votes vote down vote up
def __init__(self, none_as_null=False, astext_type=None):
        """Construct a :class:`.JSON` type.

        :param none_as_null: if True, persist the value ``None`` as a
         SQL NULL value, not the JSON encoding of ``null``.   Note that
         when this flag is False, the :func:`.null` construct can still
         be used to persist a NULL value::

             from sqlalchemy import null
             conn.execute(table.insert(), data=null())

         .. versionchanged:: 0.9.8 - Added ``none_as_null``, and :func:`.null`
            is now supported in order to persist a NULL value.

         .. seealso::

              :attr:`.JSON.NULL`

        :param astext_type: the type to use for the
         :attr:`.JSON.Comparator.astext`
         accessor on indexed attributes.  Defaults to :class:`.types.Text`.

         .. versionadded:: 1.1

         """
        super(JSON, self).__init__(none_as_null=none_as_null)
        if astext_type is not None:
            self.astext_type = astext_type 
Example #14
Source File: test_selectable.py    From sqlalchemy with MIT License 5 votes vote down vote up
def test_union_against_join(self):

        # same as testunion, except its an alias of the union

        u = (
            select(
                [
                    table1.c.col1,
                    table1.c.col2,
                    table1.c.col3,
                    table1.c.colx,
                    null().label("coly"),
                ]
            )
            .union(
                select(
                    [
                        table2.c.col1,
                        table2.c.col2,
                        table2.c.col3,
                        null().label("colx"),
                        table2.c.coly,
                    ]
                )
            )
            .alias("analias")
        )
        j1 = table1.join(table2)
        assert u.corresponding_column(j1.c.table1_colx) is u.c.colx
        assert j1.corresponding_column(u.c.colx) is j1.c.table1_colx 
Example #15
Source File: test_selectable.py    From sqlalchemy with MIT License 5 votes vote down vote up
def test_select_union(self):

        # like testaliasunion, but off a Select off the union.

        u = (
            select(
                [
                    table1.c.col1,
                    table1.c.col2,
                    table1.c.col3,
                    table1.c.colx,
                    null().label("coly"),
                ]
            )
            .union(
                select(
                    [
                        table2.c.col1,
                        table2.c.col2,
                        table2.c.col3,
                        null().label("colx"),
                        table2.c.coly,
                    ]
                )
            )
            .alias("analias")
        )
        s = select([u]).subquery()
        s1 = table1.select(use_labels=True).subquery()
        s2 = table2.select(use_labels=True).subquery()
        assert s.corresponding_column(s1.c.table1_col2) is s.c.col2
        assert s.corresponding_column(s2.c.table2_col2) is s.c.col2 
Example #16
Source File: json.py    From android_universal with MIT License 5 votes vote down vote up
def __init__(self, none_as_null=False, astext_type=None):
        """Construct a :class:`.JSON` type.

        :param none_as_null: if True, persist the value ``None`` as a
         SQL NULL value, not the JSON encoding of ``null``.   Note that
         when this flag is False, the :func:`.null` construct can still
         be used to persist a NULL value::

             from sqlalchemy import null
             conn.execute(table.insert(), data=null())

         .. versionchanged:: 0.9.8 - Added ``none_as_null``, and :func:`.null`
            is now supported in order to persist a NULL value.

         .. seealso::

              :attr:`.JSON.NULL`

        :param astext_type: the type to use for the
         :attr:`.JSON.Comparator.astext`
         accessor on indexed attributes.  Defaults to :class:`.types.Text`.

         .. versionadded:: 1.1

         """
        super(JSON, self).__init__(none_as_null=none_as_null)
        if astext_type is not None:
            self.astext_type = astext_type 
Example #17
Source File: test_selectable.py    From sqlalchemy with MIT License 5 votes vote down vote up
def test_alias_union(self):

        # same as testunion, except its an alias of the union

        u = (
            select(
                [
                    table1.c.col1,
                    table1.c.col2,
                    table1.c.col3,
                    table1.c.colx,
                    null().label("coly"),
                ]
            )
            .union(
                select(
                    [
                        table2.c.col1,
                        table2.c.col2,
                        table2.c.col3,
                        null().label("colx"),
                        table2.c.coly,
                    ]
                )
            )
            .alias("analias")
        )
        s1 = table1.select(use_labels=True).subquery()
        s2 = table2.select(use_labels=True).subquery()
        assert u.corresponding_column(s1.c.table1_col2) is u.c.col2
        assert u.corresponding_column(s2.c.table2_col2) is u.c.col2
        assert u.corresponding_column(s2.c.table2_coly) is u.c.coly
        assert s2.corresponding_column(u.c.coly) is s2.c.table2_coly 
Example #18
Source File: test_types.py    From sqlalchemy with MIT License 5 votes vote down vote up
def _test_insert_nulls(self, engine):
        with engine.connect() as conn:
            conn.execute(
                self.tables.data_table.insert(), {"name": "r1", "data": null()}
            )
            self._assert_data([None], conn) 
Example #19
Source File: test_types.py    From sqlalchemy with MIT License 5 votes vote down vote up
def _assert_column_is_NULL(self, conn, column="data"):
        col = self.tables.data_table.c[column]
        data = conn.execute(select([col]).where(col.is_(null()))).fetchall()
        eq_([d for d, in data], [None]) 
Example #20
Source File: json.py    From sqlalchemy with MIT License 5 votes vote down vote up
def __init__(self, none_as_null=False, astext_type=None):
        """Construct a :class:`_types.JSON` type.

        :param none_as_null: if True, persist the value ``None`` as a
         SQL NULL value, not the JSON encoding of ``null``.   Note that
         when this flag is False, the :func:`.null` construct can still
         be used to persist a NULL value::

             from sqlalchemy import null
             conn.execute(table.insert(), data=null())

         .. versionchanged:: 0.9.8 - Added ``none_as_null``, and :func:`.null`
            is now supported in order to persist a NULL value.

         .. seealso::

              :attr:`_types.JSON.NULL`

        :param astext_type: the type to use for the
         :attr:`.JSON.Comparator.astext`
         accessor on indexed attributes.  Defaults to :class:`_types.Text`.

         .. versionadded:: 1.1

         """
        super(JSON, self).__init__(none_as_null=none_as_null)
        if astext_type is not None:
            self.astext_type = astext_type 
Example #21
Source File: json.py    From pyRevit with GNU General Public License v3.0 5 votes vote down vote up
def __init__(self, none_as_null=False, astext_type=None):
        """Construct a :class:`.JSON` type.

        :param none_as_null: if True, persist the value ``None`` as a
         SQL NULL value, not the JSON encoding of ``null``.   Note that
         when this flag is False, the :func:`.null` construct can still
         be used to persist a NULL value::

             from sqlalchemy import null
             conn.execute(table.insert(), data=null())

         .. versionchanged:: 0.9.8 - Added ``none_as_null``, and :func:`.null`
            is now supported in order to persist a NULL value.

         .. seealso::

              :attr:`.JSON.NULL`

        :param astext_type: the type to use for the
         :attr:`.JSON.Comparator.astext`
         accessor on indexed attributes.  Defaults to :class:`.types.Text`.

         .. versionadded:: 1.1

         """
        super(JSON, self).__init__(none_as_null=none_as_null)
        if astext_type is not None:
            self.astext_type = astext_type 
Example #22
Source File: json.py    From planespotter with MIT License 5 votes vote down vote up
def __init__(self, none_as_null=False, astext_type=None):
        """Construct a :class:`.JSON` type.

        :param none_as_null: if True, persist the value ``None`` as a
         SQL NULL value, not the JSON encoding of ``null``.   Note that
         when this flag is False, the :func:`.null` construct can still
         be used to persist a NULL value::

             from sqlalchemy import null
             conn.execute(table.insert(), data=null())

         .. versionchanged:: 0.9.8 - Added ``none_as_null``, and :func:`.null`
            is now supported in order to persist a NULL value.

         .. seealso::

              :attr:`.JSON.NULL`

        :param astext_type: the type to use for the
         :attr:`.JSON.Comparator.astext`
         accessor on indexed attributes.  Defaults to :class:`.types.Text`.

         .. versionadded:: 1.1

         """
        super(JSON, self).__init__(none_as_null=none_as_null)
        if astext_type is not None:
            self.astext_type = astext_type 
Example #23
Source File: json.py    From Fluid-Designer with GNU General Public License v3.0 5 votes vote down vote up
def __init__(self, none_as_null=False):
        """Construct a :class:`.JSON` type.

        :param none_as_null: if True, persist the value ``None`` as a
         SQL NULL value, not the JSON encoding of ``null``.   Note that
         when this flag is False, the :func:`.null` construct can still
         be used to persist a NULL value::

             from sqlalchemy import null
             conn.execute(table.insert(), data=null())

         .. versionchanged:: 0.9.8 - Added ``none_as_null``, and :func:`.null`
            is now supported in order to persist a NULL value.

         """
        self.none_as_null = none_as_null 
Example #24
Source File: 0277_consent_to_research_null.py    From notifications-api with MIT License 5 votes vote down vote up
def upgrade():
    op.alter_column(
        'services',
        'consent_to_research',
        existing_type=sa.BOOLEAN(),
        nullable=True,
        server_default=sa.null(),
    )
    op.alter_column(
        'services_history',
        'consent_to_research',
        existing_type=sa.BOOLEAN(),
        nullable=True,
        server_default=sa.null(),
    )
    op.execute("""
        UPDATE
            services
        SET
            consent_to_research = null
    """)
    op.execute("""
        UPDATE
            services_history
        SET
            consent_to_research = null
    """) 
Example #25
Source File: alchemy.py    From ibis with Apache License 2.0 5 votes vote down vote up
def _not_null(t, expr):
    arg = t.translate(expr.op().args[0])
    return arg.isnot(sa.null()) 
Example #26
Source File: alchemy.py    From ibis with Apache License 2.0 5 votes vote down vote up
def _is_null(t, expr):
    arg = t.translate(expr.op().args[0])
    return arg.is_(sa.null()) 
Example #27
Source File: test_selectable.py    From sqlalchemy with MIT License 4 votes vote down vote up
def test_union_correspondence(self):

        # tests that we can correspond a column in a Select statement
        # with a certain Table, against a column in a Union where one of
        # its underlying Selects matches to that same Table

        u = select(
            [
                table1.c.col1,
                table1.c.col2,
                table1.c.col3,
                table1.c.colx,
                null().label("coly"),
            ]
        ).union(
            select(
                [
                    table2.c.col1,
                    table2.c.col2,
                    table2.c.col3,
                    null().label("colx"),
                    table2.c.coly,
                ]
            )
        )
        s1 = table1.select(use_labels=True)
        s2 = table2.select(use_labels=True)

        assert (
            u.corresponding_column(s1.selected_columns.table1_col2)
            is u.selected_columns.col2
        )

        # right now, the "selected_columns" of a union are those of the
        # first selectable.  so without using a subquery that represents
        # all the SELECTs in the union, we can't do corresponding column
        # like this.  perhaps compoundselect shouldn't even implement
        # .corresponding_column directly
        assert (
            u.corresponding_column(s2.selected_columns.table2_col2) is None
        )  # really? u.selected_columns.col2

        usub = u.subquery()
        assert (
            usub.corresponding_column(s1.selected_columns.table1_col2)
            is usub.c.col2
        )
        assert (
            usub.corresponding_column(s2.selected_columns.table2_col2)
            is usub.c.col2
        )

        s1sub = s1.subquery()
        s2sub = s2.subquery()
        assert usub.corresponding_column(s1sub.c.table1_col2) is usub.c.col2
        assert usub.corresponding_column(s2sub.c.table2_col2) is usub.c.col2 
Example #28
Source File: test_query.py    From sqlalchemy with MIT License 4 votes vote down vote up
def test_object_comparison(self):
        """test scalar comparison to an object instance"""

        Item, Order, Dingaling, User, Address = (
            self.classes.Item,
            self.classes.Order,
            self.classes.Dingaling,
            self.classes.User,
            self.classes.Address,
        )

        sess = create_session()
        user = sess.query(User).get(8)
        assert [Address(id=2), Address(id=3), Address(id=4)] == sess.query(
            Address
        ).filter(Address.user == user).all()

        assert [Address(id=1), Address(id=5)] == sess.query(Address).filter(
            Address.user != user
        ).all()

        # generates an IS NULL
        assert (
            [] == sess.query(Address).filter(Address.user == None).all()
        )  # noqa
        assert [] == sess.query(Address).filter(Address.user == null()).all()

        assert [Order(id=5)] == sess.query(Order).filter(
            Order.address == None
        ).all()  # noqa

        # o2o
        dingaling = sess.query(Dingaling).get(2)
        assert [Address(id=5)] == sess.query(Address).filter(
            Address.dingaling == dingaling
        ).all()

        # m2m
        eq_(
            sess.query(Item)
            .filter(Item.keywords == None)
            .order_by(Item.id)  # noqa
            .all(),
            [Item(id=4), Item(id=5)],
        )
        eq_(
            sess.query(Item)
            .filter(Item.keywords != None)
            .order_by(Item.id)  # noqa
            .all(),
            [Item(id=1), Item(id=2), Item(id=3)],
        )