Skip to content

flip off the "hashable" flag for PG unhashable types: JSON, JSONB (already has it), ARRAY. also NULLTYPE, add/test type_coerce as well as cast() to indexed access #3499

Closed

Description

@sqlalchemy-bot

Migrated issue, originally created by Joey Pereira (@legojoey17)

There is an exception while doing a query on a declarative base model where you add a column that evaluates to a JSON value and you have used deferred loading

The following code

from sqlalchemy.dialects.postgresql import JSONB, BIGINT
base = declarative_base()
class ModelA(base):
    id = Column(BIGINT, primary_key=True)

class ModelB(base):
    id = Column(BIGINT, primary_key=True)
    jsoncol = Column(JSONB)

session.query(ModelA) \
.filter(ModelA.id.in_(ids)) \
.options(Load(ModelA).load_only("id")) \
.join(ModelB, ModelB.id == ModelA.id) \
.add_columns([ModelB.jsoncol['jsonfield'].label('jsonfield')]) \
.all()

ModelB will look something like

id = 1
jsoncol = {
  'jsonfield': {
    'k1': 1,
    'k2': 2
  }
}

# in this case
ModelB.jsoncol['jsonfield']
=>  {
  'k1': 1,
  'k2': 2
}

Causes the exception

  File "/home/piinpoint/.virtualenv/piinpoint/lib/python2.7/site-packages/sqlalchemy/orm/query.py", line 2399, in all
    return list(self)
  File "/home/piinpoint/.virtualenv/piinpoint/lib/python2.7/site-packages/sqlalchemy/orm/loading.py", line 84, in instances
    util.raise_from_cause(err)
  File "/home/piinpoint/.virtualenv/piinpoint/lib/python2.7/site-packages/sqlalchemy/util/compat.py", line 199, in raise_from_cause
    reraise(type(exception), exception, tb=exc_tb)
  File "/home/piinpoint/.virtualenv/piinpoint/lib/python2.7/site-packages/sqlalchemy/orm/loading.py", line 75, in instances
    rows = util.unique_list(rows, filter_fn)
  File "/home/piinpoint/.virtualenv/piinpoint/lib/python2.7/site-packages/sqlalchemy/util/_collections.py", line 756, in unique_list
    if hashfunc(x) not in seen
TypeError: unhashable type: 'dict'
x
=> sqlalchemy.util._collections.result((<ModelA object at 0x7f8088868710>, {u'19': 100935, u'24': 103674, u'14': 98276}))
hashfunc(x)
=> (140190023059216, {u'19': 100935, u'24': 103674, u'14': 98276})

Currently my workaround is to do cast(jsonexpression, TEXT)

Activity

  1. sqlalchemy-bot commented on Jul 24, 2015

    @sqlalchemy-bot
    CollaboratorAuthor

    Changes by Joey Pereira (@legojoey17):

    • edited description
  2. sqlalchemy-bot commented on Jul 24, 2015

    @sqlalchemy-bot
    CollaboratorAuthor

    Changes by Joey Pereira (@legojoey17):

    • edited description
  3. sqlalchemy-bot commented on Jul 24, 2015

    @sqlalchemy-bot
    CollaboratorAuthor

    Changes by Joey Pereira (@legojoey17):

    • edited description
  4. sqlalchemy-bot commented on Jul 24, 2015

    @sqlalchemy-bot
    CollaboratorAuthor

    Michael Bayer (@zzzeek) wrote:

    let me make that simpler. any query of the form query(Entity, Entity.some_unhashable_type) is going to cause this:

    from sqlalchemy import *
    from sqlalchemy.orm import *
    from sqlalchemy.ext.declarative import declarative_base
    from sqlalchemy.dialects.postgresql import JSON
    
    Base = declarative_base()
    
    
    class A(Base):
        __tablename__ = 'a'
        id = Column(Integer, primary_key=True)
        data = Column(JSON)
    
    e = create_engine("postgresql://scott:tiger@localhost/test", echo=True)
    Base.metadata.drop_all(e)
    Base.metadata.create_all(e)
    
    
    s = Session(e)
    s.add(A(data={"x": "y"}))
    s.commit()
    
    print s.query(A, A.data).first()
    

    this is why the PG ARRAY type has an argument as_tuple to deal with this.

    There's also a "hashable" flag that we should be using here (and for ARRAY) so I think we should just flip that on.

    For now here is your workaround:

    json_type = JSONB()
    json_type.hashable = False
    
    class ModelB(base):
        id = Column(BIGINT, primary_key=True)
        jsoncol = Column(json_type)
    
    
  5. sqlalchemy-bot commented on Jul 24, 2015

    @sqlalchemy-bot
    CollaboratorAuthor

    Changes by Michael Bayer (@zzzeek):

    • changed title from "Deffered load with PostgreSQL JSON col causes "unh" to "flip off the "hashable" flag for PG unhashable typ"
  6. sqlalchemy-bot commented on Jul 24, 2015

    @sqlalchemy-bot
    CollaboratorAuthor

    Changes by Michael Bayer (@zzzeek):

    • set milestone to "1.1"
  7. sqlalchemy-bot commented on Jul 24, 2015

    @sqlalchemy-bot
    CollaboratorAuthor

    Michael Bayer (@zzzeek) wrote:

    ah. you need more of a workaround, one moment

  8. sqlalchemy-bot commented on Jul 24, 2015

    @sqlalchemy-bot
    CollaboratorAuthor

    Michael Bayer (@zzzeek) wrote:

    so the return value of the indexed thing is NullType. We don't know what the index of a JSON type returns. As part of this issue we will add hashable=False to NULLTYPE as well. For now you need to type_coerce:

    type_coerce(A.data['something'], json_type)
    

    the JSONB type apparently already has the "hashable=False" flag, and JSON does not. It's pretty broken.

  9. sqlalchemy-bot commented on Jul 24, 2015

    @sqlalchemy-bot
    CollaboratorAuthor

    Changes by Michael Bayer (@zzzeek):

    • changed title from "flip off the "hashable" flag for PG unhashable typ" to "flip off the "hashable" flag for PG unhashable typ"
  10. sqlalchemy-bot commented on Jul 24, 2015

    @sqlalchemy-bot
    CollaboratorAuthor

    Changes by Michael Bayer (@zzzeek):

    • removed labels: postgres
    • added labels: orm
  11. sqlalchemy-bot commented on Jul 24, 2015

    @sqlalchemy-bot
    CollaboratorAuthor

    Joey Pereira (@legojoey17) wrote:

    Ah thanks so much! type_coerce is exactly what I was looking for as I tried to get your previous workaround to work for this case :)

    I'll be sure to try to make some PR's for the JSON class soon :)!

    Notably the ColumnClause returned from the JSON types __getitem__ needs to always have type_coerce correct?

    (with respect to https://github.com/zzzeek/sqlalchemy/blob/master/lib/sqlalchemy/dialects/postgresql/json.py#L188 )

  12. sqlalchemy-bot commented on Jul 24, 2015

    @sqlalchemy-bot
    CollaboratorAuthor
  13. sqlalchemy-bot commented on Jul 24, 2015

    @sqlalchemy-bot
    CollaboratorAuthor

    Michael Bayer (@zzzeek) wrote:

    with these PG types there's the whole issue of not just the type itself, but what does someobject['foo']['bar'] return. In #3487, we sort of know it for an ARRAY type. But for a JSON, we don't. There's a "cast" operator though directly on that object for this purpose, I'd propose adding a type_coerce also...so! right now you can also do: A.data['something'].cast(json_type).

  14. sqlalchemy-bot commented on Jul 24, 2015

    @sqlalchemy-bot
    CollaboratorAuthor

    Changes by Michael Bayer (@zzzeek):

    • changed title from "flip off the "hashable" flag for PG unhashable typ" to "flip off the "hashable" flag for PG unhashable typ"
  15. sqlalchemy-bot commented on Jul 25, 2015

    @sqlalchemy-bot
    CollaboratorAuthor

    Joey Pereira (@legojoey17) wrote:

    You also mentioned NULLTYPE. By that do you mean to add hashable=False also to NULLTYPE? I've changed the rest in a PR

    What do you mean by test type_coerce and indexed access? So far what I've done in a PR( https://bitbucket.org/zzzeek/sqlalchemy/pull-request/57/postgresql-json-and-array-modifications/diff ) is make it so someobject['foo']['bar'] works as a return_type is passed all the way through to BinaryExpression so I think that will work just fine :)

  16. sqlalchemy-bot commented on Aug 11, 2015

    @sqlalchemy-bot
    CollaboratorAuthor

    Michael Bayer (@zzzeek) wrote:

    in https://bitbucket.org/zzzeek/sqlalchemy/src/39adada25d71ac33d2a468cc19eb61c0fdfa9280/?at=ticket_3499 this is ready to go, my understanding of PG JSON has improved such that I now know that all return values from a JSON are still JSON, or TEXT if you use the ->> operator, even if you access a single scalar value. so we do know the type in all cases, it's JSON or TEXT and that's it.

  17. sqlalchemy-bot commented on Aug 11, 2015

    @sqlalchemy-bot
    CollaboratorAuthor
  18. sqlalchemy-bot commented on Aug 17, 2015

    @sqlalchemy-bot
    CollaboratorAuthor

    Michael Bayer (@zzzeek) wrote:

    → ceeb033

  19. sqlalchemy-bot commented on Aug 17, 2015

    @sqlalchemy-bot
    CollaboratorAuthor

    Changes by Michael Bayer (@zzzeek):

    • changed status to closed
  20. added
    bug
    on Nov 27, 2018
  21. added this to the 1.1 milestone on Nov 27, 2018
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugorm

    Type

    No type

    Projects

    No projects

      Milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions