Re: [sqlalchemy] Checking the availablity of a booked Item
For outer joins you need a where clause on the joined tables. http://www.codinghorror.com/blog/2007/10/a-visual-explanation-of-sql-joins.html Using a full outer join should return the expected results. -- Thadeus On Tue, Oct 12, 2010 at 1:41 PM, chaouche yacine yacinechaou...@yahoo.comwrote: Hello, Here's my simple model (For simplification, consider Face as a Billboard) : +-+ +---+ +--+ |Face |.. |Campaign | ...|TimePeriod| +-+ . +---+ . +--+ |code | . |time_period| |start_time| +-+ . +---+ +--+ |faces | |end_time | +---+ +--+ One way to read this model is : A campaign can book multiple faces during a certain period of time. What I want to do is get all the available Faces for a given period of time, to see what faces can I book for a new campaign that longs for that particular period of time. I would typically have a Face.get_available(time_period) class method that does the job. This method would look for all the faces that don't have an ongoing booking. My question is : how to write such a method ? Here's how I figured it out (couldn't get it to work) : class Face(Entity): using_options(tablename=faces) @classmethod def get_available(self,time_period): Return faces that are not booked (not in any campaign) during the given time_period. # start_date_cond = TimePeriod.start_date time_period.end_date # end_date_cond = TimePeriod.end_date time_period.start_date # available_periods = Campaign.time_period.has(or_(start_date_cond,end_date_cond)) # unavailable_periods = not(available_periods) # I am pretty sure that the time conditions are good. # Here's a good way to convince yourself (read from bottom to top) : # L1 0--- # L2 --| # L3 0[]-- # L3 represents the desired period (passed as argument) going from [ to ] # place the start date of the booked face anywhere on L2 # place the end date of the booked face anywhere on L1 # of course, end date must be after start date... # Anyway you do it, your face isn't available for the period of time in L3. start_date_cond = TimePeriod.start_date = time_period.end_date end_date_cond = TimePeriod.end_date = time_period.start_date unavailable_periods = Campaign.time_period.has(and_(start_date_cond,end_date_cond)) # I am not sure about what follows... filter_cond = not_(unavailable_periods) join_clause = Campaign.faces return Face.query.filter(filter_cond).outerjoin(join_clause).all() This code returns only faces that have already been booked before or have a future booking, and are free for the moment. But faces with no bookings at all are not returned. This may be due to an incorrect outerjoin ? (I also tried a simple join with no success) Here's the generated sql for one query : 2010-10-12 19:34:22,837 INFO sqlalchemy.engine.base.Engine.0x...f4ec SELECT faces.id AS faces_id FROM campaigns LEFT OUTER JOIN campaigns_faces__faces AS campaigns_faces__faces_1 ON campaigns.id = campaigns_faces__faces_1.campaigns_id LEFT OUTER JOIN faces ON faces.id = campaigns_faces__faces_1.faces_id WHERE NOT (EXISTS (SELECT 1 FROM time_periods WHERE campaigns.time_period_id = time_periods.id AND time_periods.start_date = %(start_date_1)s AND time_periods.end_date = %(end_date_1)s)) 2010-10-12 19:34:22,837 INFO sqlalchemy.engine.base.Engine.0x...f4ec {'start_date_1': datetime.date(2010, 10, 30), 'end_date_1': datetime.date(2010, 10, 20)} [Face id=1 at 0x932218c ] Any help would be very appreciated. Y.Chaouche PS : and please, don't give me that lame it's elixir excuse. The question is about how to construct the proper query for the desired operation in a sqlalchemy way. Elixir is only another Declarative approach + mapping, that's it. -- You received this message because you are subscribed to the Google Groups sqlalchemy group. To post to this group, send email to sqlalch...@googlegroups.com. To unsubscribe from this group, send email to sqlalchemy+unsubscr...@googlegroups.comsqlalchemy%2bunsubscr...@googlegroups.com . For more options, visit this group at http://groups.google.com/group/sqlalchemy?hl=en. -- You received this message because you are subscribed to the Google Groups sqlalchemy group. To post to this group, send email to sqlalch...@googlegroups.com. To unsubscribe from this group, send email to sqlalchemy+unsubscr...@googlegroups.com.
[sqlalchemy] Fwd: [Gnukhata-devel] Error installing gnukhata
Don't know why this might be happening on an Ubuntu 10.04 machine? Can some one help solve this? happy hacking. Krishnakant. Original Message Subject:[Gnukhata-devel] Error installing gnukhata Date: Wed, 13 Oct 2010 11:06:00 +0400 From: pooja bakshi pooja.dbak...@gmail.com To: gnukhata-de...@cis-india.org This is the error while installing GNUkhataserver/. Pls help. po...@pooja-desktop:~$ cd GNUKhataServer/ po...@pooja-desktop:~/GNUKhataServer$ cd gnukhata-server/ po...@pooja-desktop:~/GNUKhataServer/gnukhata-server$ cd GNUKhata-ApplicationServer/ po...@pooja-desktop:~/GNUKhataServer/gnukhata-server/GNUKhata-ApplicationServer$ python rpc_main.py /var/lib/python-support/python2.6/sqlalchemy/util.py:7: DeprecationWarning: the sets module is deprecated import inspect, itertools, new, operator, sets, sys, warnings, weakref Traceback (most recent call last): File rpc_main.py, line 45, in module import rpc_groups File /home/pooja/GNUKhataServer/gnukhata-server/GNUKhata-ApplicationServer/rpc_groups.py, line 31, in module from sqlalchemy.orm import join ImportError: cannot import name join po...@pooja-desktop:~/GNUKhataServer/gnukhata-server/GNUKhata-ApplicationServer$ sudo su postgres [sudo] password for pooja: postg...@pooja-desktop:/home/pooja/GNUKhataServer/gnukhata-server/GNUKhata-ApplicationServer$ python rpc_main.py /var/lib/python-support/python2.6/sqlalchemy/util.py:7: DeprecationWarning: the sets module is deprecated import inspect, itertools, new, operator, sets, sys, warnings, weakref Traceback (most recent call last): File rpc_main.py, line 45, in module import rpc_groups File /home/pooja/GNUKhataServer/gnukhata-server/GNUKhata-ApplicationServer/rpc_groups.py, line 31, in module from sqlalchemy.orm import join ImportError: cannot import name join postg...@pooja-desktop:/home/pooja/GNUKhataServer/gnukhata-server/GNUKhata-ApplicationServer$ -- Regards, Pooja Bakshi -- You received this message because you are subscribed to the Google Groups sqlalchemy group. To post to this group, send email to sqlalch...@googlegroups.com. To unsubscribe from this group, send email to sqlalchemy+unsubscr...@googlegroups.com. For more options, visit this group at http://groups.google.com/group/sqlalchemy?hl=en. ___ Gnukhata-devel mailing list gnukhata-de...@cis-india.org http://lists.cis-india.org/mailman/listinfo/gnukhata-devel
Re: [sqlalchemy] Fwd: [Gnukhata-devel] Error installing gnukhata
On 13/10/2010 08:29, Krishnakant Mane wrote: Don't know why this might be happening on an Ubuntu 10.04 machine? Can some one help solve this? How were any of the involved packages installed? Chris -- Simplistix - Content Management, Batch Processing Python Consulting - http://www.simplistix.co.uk -- You received this message because you are subscribed to the Google Groups sqlalchemy group. To post to this group, send email to sqlalch...@googlegroups.com. To unsubscribe from this group, send email to sqlalchemy+unsubscr...@googlegroups.com. For more options, visit this group at http://groups.google.com/group/sqlalchemy?hl=en.
Re: [sqlalchemy] Dynamic query
On 10/12/2010 18:05, Julien Cigar wrote: On 10/12/2010 17:09, Michael Bayer wrote: On Oct 12, 2010, at 7:39 AM, Julien Cigar wrote: Hello, any idea why with # Query class BaseQuery(orm.Query): @dynamic def method_a(self): ... def method_b(self): ... class FooQuery(BaseQuery): ... class BarQuery(FooQuery): @dynamic def method_c(self): ... # Models class BaseModel(object): query = Session.query_property(BaseQuery) # myQuery = type('PolymorphicQuery, (content.BaseQuery, ), func_list)(BaseModel) where func_list containing all the functions decorated by @dynamic the following fail? : - myQuery.get(45) fails with: AttributeError: 'NoneType' object has no attribute 'identity_map' - myQuery.method_a().all() fails with: AttributeError: 'NoneType' object has no attribute '_autoflush' - etc OK I think I found a solution, I need to pass session=Session.registry() to my custom query: model.content.ContentQuery.__mro__ (class 'amnesia.model.content.ContentQuery', class 'amnesia.model.root.RootQuery', class 'sqlalchemy.orm.query.Query', type 'object') PolymorphicQuery = type('PolymorphicQuery', (model.content.ContentQuery, ), {}) q1 = PolymorphicQuery(model.Content) q1.get(25) Traceback (most recent call last): File console, line 1, in module File /home/jcigar/venvs/pylons0.9.7/lib/python2.5/site-packages/SQLAlchemy-0.6.4-py2.5.egg/sqlalchemy/orm/query.py, line 595, in get return self._get(key, ident) File /home/jcigar/venvs/pylons0.9.7/lib/python2.5/site-packages/SQLAlchemy-0.6.4-py2.5.egg/sqlalchemy/orm/query.py, line 1803, in _get instance = self.session.identity_map.get(key) AttributeError: 'NoneType' object has no attribute 'identity_map' q2 = PolymorphicQuery(model.Content, session=meta.Session.registry()) q2.get(25) amnesia.model.event.Event object at 0x939046c I hope I'm not doing something wrong :p My goal is to be able to build a custom Query object to use with the .with_polymorphic() function .. I've just grepped through all the source, examples and tests plus the wiki trying to find what @dynamic is. Seems like something I'd have come up with in the past but I've no clue at the moment what that is. Sorry, I forgot to mention that it's just a custom decorator of mine which add the function name to a list ... forget about it, it's just to build the third argument of type() (func_list in my case) -- No trees were killed in the creation of this message. However, many electrons were terribly inconvenienced. -- You received this message because you are subscribed to the Google Groups sqlalchemy group. To post to this group, send email to sqlalch...@googlegroups.com. To unsubscribe from this group, send email to sqlalchemy+unsubscr...@googlegroups.com. For more options, visit this group at http://groups.google.com/group/sqlalchemy?hl=en. attachment: jcigar.vcf
Re: [sqlalchemy] Checking the availablity of a booked Item
Thank you Thadeus, I believe Face.query.filter(filter_cond).outerjoin(join_clause).all() does a full outerjoin, or is there another way to do it ? Y.Chaouche --- On Wed, 10/13/10, Thadeus Burgess thade...@thadeusb.com wrote: From: Thadeus Burgess thade...@thadeusb.com Subject: Re: [sqlalchemy] Checking the availablity of a booked Item To: sqlalchemy@googlegroups.com Date: Wednesday, October 13, 2010, 12:04 AM For outer joins you need a where clause on the joined tables. http://www.codinghorror.com/blog/2007/10/a-visual-explanation-of-sql-joins.html Using a full outer join should return the expected results. -- Thadeus On Tue, Oct 12, 2010 at 1:41 PM, chaouche yacine yacinechaou...@yahoo.com wrote: Hello, Here's my simple model (For simplification, consider Face as a Billboard) : +-+ +---+ +--+ |Face |.. |Campaign | ...|TimePeriod| +-+ . +---+ . +--+ |code | . |time_period| |start_time| +-+ . +---+ +--+ |faces | |end_time | +---+ +--+ One way to read this model is : A campaign can book multiple faces during a certain period of time. What I want to do is get all the available Faces for a given period of time, to see what faces can I book for a new campaign that longs for that particular period of time. I would typically have a Face.get_available(time_period) class method that does the job. This method would look for all the faces that don't have an ongoing booking. My question is : how to write such a method ? Here's how I figured it out (couldn't get it to work) : class Face(Entity): using_options(tablename=faces) �...@classmethod def get_available(self,time_period): Return faces that are not booked (not in any campaign) during the given time_period. # start_date_cond = TimePeriod.start_date time_period.end_date # end_date_cond = TimePeriod.end_date time_period.start_date # available_periods = Campaign.time_period.has(or_(start_date_cond,end_date_cond)) # unavailable_periods = not(available_periods) # I am pretty sure that the time conditions are good. # Here's a good way to convince yourself (read from bottom to top) : # L1 0--- # L2 --| # L3 0[]-- # L3 represents the desired period (passed as argument) going from [ to ] # place the start date of the booked face anywhere on L2 # place the end date of the booked face anywhere on L1 # of course, end date must be after start date... # Anyway you do it, your face isn't available for the period of time in L3. start_date_cond = TimePeriod.start_date = time_period.end_date end_date_cond = TimePeriod.end_date = time_period.start_date unavailable_periods = Campaign.time_period.has(and_(start_date_cond,end_date_cond)) # I am not sure about what follows... filter_cond = not_(unavailable_periods) join_clause = Campaign.faces return Face.query.filter(filter_cond).outerjoin(join_clause).all() This code returns only faces that have already been booked before or have a future booking, and are free for the moment. But faces with no bookings at all are not returned. This may be due to an incorrect outerjoin ? (I also tried a simple join with no success) Here's the generated sql for one query : 2010-10-12 19:34:22,837 INFO sqlalchemy.engine.base.Engine.0x...f4ec SELECT faces.id AS faces_id FROM campaigns LEFT OUTER JOIN campaigns_faces__faces AS campaigns_faces__faces_1 ON campaigns.id = campaigns_faces__faces_1.campaigns_id LEFT OUTER JOIN faces ON faces.id = campaigns_faces__faces_1.faces_id WHERE NOT (EXISTS (SELECT 1 FROM time_periods WHERE campaigns.time_period_id = time_periods.id AND time_periods.start_date = %(start_date_1)s AND time_periods.end_date = %(end_date_1)s)) 2010-10-12 19:34:22,837 INFO sqlalchemy.engine.base.Engine.0x...f4ec {'start_date_1': datetime.date(2010, 10, 30), 'end_date_1': datetime.date(2010, 10, 20)} [Face id=1 at 0x932218c ] Any help would be very appreciated. Y.Chaouche PS : and please, don't give me that lame it's elixir excuse. The question is about how to construct the proper query for the desired operation in a sqlalchemy way. Elixir is only another Declarative approach + mapping, that's it. -- You received this message because you are subscribed to the Google Groups sqlalchemy group. To post to this group, send
[sqlalchemy] Altering schema for tables at runtime
Hello! I have a couple of models that I use with a MySQL database. For testing purposes I would like to set up in-memory fixtures for these models using SQLite. Unfortunately the models are declared with different schemas. Since SQLite doesn't seem to support schemas I'd like to somehow normalize them to not use any particular schema. The following is a simple outline of what I'm trying to do: class A(Base): __tablename__ = 'table_a' __table_args__ = {'schema':'schema_a'} id = Column(Integer, primary_key=True) class B(Base): __tablename__ = 'table_b' __table_args__ = {'schema':'schema_b'} id = Column('ID', Integer, primary_key=True) a_id = Column('A_ID', Integer, ForeignKey('schema_a.table_a.id')) c_id = Column('C_ID', Integer, ForeignKey('schema_c.table_c.id')) a = relation(A, backref=backref('bs')) b = relation(C) class C(Base): __tablename__ = 'table_c' __table_args__ = {'schema': 'schema_c'} id = Column(Integer, primary_key=True) def do_business_logic(): # A bunch of logic that will use A, B and C. def run_functional_test(): # First, set up an in memory DB fixture engine = create_engine('sqlite://', echo=True) NewBase = declarative_base() strip_schema_from_model(NewBase) NewBase.metadata.create_all(engine) # Now populate it with instances of A, B and C ... # Run test logic, which at some point calls do_business_logic ... # Tear down the fixture ... def strip_schema_from_models(decl_base): ''' Redefine A, B and C so that: 1. They all belong to the same schema (the default schema: None or similar.) 2. They are constructed in the same way, ie A() will be used to create a tweaked instance of A 3. All logic involving instances of A, B and C should also be valid for instances of the redefined classes ''' Is it possible to implement strip_schema_from_model so that all my criteria are met? One way that comes to mind is to use tometadata to copy the table information for each model, create new model classes using this information and override globals() for A, B and C with these new classes. The really tricky part seems to be to get the mapper rules to work properly. Another would be to load the source file for the model declarations into a string, use string operations to remove all schema information and eval the result. Maybe this could work but it's not really tempting. I would be very thankful for any help on this matter. -- You received this message because you are subscribed to the Google Groups sqlalchemy group. To post to this group, send email to sqlalch...@googlegroups.com. To unsubscribe from this group, send email to sqlalchemy+unsubscr...@googlegroups.com. For more options, visit this group at http://groups.google.com/group/sqlalchemy?hl=en.
Re: [sqlalchemy] Altering schema for tables at runtime
On Oct 13, 2010, at 3:59 AM, Eskil Andréen wrote: Hello! class A(Base): __tablename__ = 'table_a' __table_args__ = {'schema':'schema_a'} id = Column(Integer, primary_key=True) class B(Base): __tablename__ = 'table_b' __table_args__ = {'schema':'schema_b'} id = Column('ID', Integer, primary_key=True) a_id = Column('A_ID', Integer, ForeignKey('schema_a.table_a.id')) c_id = Column('C_ID', Integer, ForeignKey('schema_c.table_c.id')) a = relation(A, backref=backref('bs')) b = relation(C) class C(Base): __tablename__ = 'table_c' __table_args__ = {'schema': 'schema_c'} id = Column(Integer, primary_key=True) def do_business_logic(): # A bunch of logic that will use A, B and C. def run_functional_test(): # First, set up an in memory DB fixture engine = create_engine('sqlite://', echo=True) NewBase = declarative_base() strip_schema_from_model(NewBase) NewBase.metadata.create_all(engine) If it were me I'd probably have the declaratives set up entirely after some global variable has been declared, so that all the constructs that call upon schema like ForeginKey and __table_args__ can check this first (and I would make a ForeignKey wrapper that does this automatically, as well as a declarative base that handles __table_args__). The usual way of running unittest or nose makes this possible since the test classes are imported first. Otherwise, the ForeignKey presence makes everything tricky here. I'd probably try to surgically alter all the Table objects, actually. But I'd never be comfortable with it. Rewriting the whole model as you're considering is sort of an option, though i think ultimately has some major roadblocks...you don't want to regenerate your classes entirely, you'd want to use the same class so that all your methods and non-orm attributes are preserved, and at that point you run into the declarative munging of columns and classes and such, all of which is why the classical approach of mapper(), or using declarative with __table__, still has its advantages (I've been using the approach at http://www.sqlalchemy.org/trac/wiki/UsageRecipes/NamingConventions , which seems to be the perfect blend). -- You received this message because you are subscribed to the Google Groups sqlalchemy group. To post to this group, send email to sqlalch...@googlegroups.com. To unsubscribe from this group, send email to sqlalchemy+unsubscr...@googlegroups.com. For more options, visit this group at http://groups.google.com/group/sqlalchemy?hl=en.
[sqlalchemy] getting floats instead of decimals from session.execute
Hi All, If I'm doing: session.execute('select some_numeric from some_table') ...how do I get floats back in the result instead of decimals? Chris -- You received this message because you are subscribed to the Google Groups sqlalchemy group. To post to this group, send email to sqlalch...@googlegroups.com. To unsubscribe from this group, send email to sqlalchemy+unsubscr...@googlegroups.com. For more options, visit this group at http://groups.google.com/group/sqlalchemy?hl=en.
[sqlalchemy] MapperExtension.[before|after]_update problem
Hi all, I am running into an issue with MapperExtension.[before|after]_update. Context --- SQLAlchemy 0.5.8 TurboGears 1.1.1 Description --- I will attempt a simple description first, as I don't think my actual code will help (I know it is not a thing to say, but really). We have 2 mapped classes, Parent and Child. Child is mapped this way : mapper(Child, child_table, properties={ parent=relation(Parent, backref='children') }) And parent has a mapperextension that defines a after_update : def after_update(self, mapper, connection, instance): for child in instance.children: child.name = 'another name' If I do 2 session flush() after modifying a Parent instance, the modifications on the children should be reflected to the database. It is the case in my unit tests if I use directly the DBSession and manipulate the objects 'myself'. BUT, if I go through the complete TG stack, in the unittests or in real-life, the modifications done on child are never sent to the database. One subtle thing though : if, before the first flush(), I access the children attribute, the problem goes away. Example : parent = DBSession.query(Parent).get('myid') parent.name = 'test' # parent.children # Un-commenting this line solve the issue, but of # course it is not an acceptable solution DBSession.flush() DBSession.flush() I could not reproduce in a simpler context, and don't know how to go further in my investigation. Help ? Thanks Christophe -- You received this message because you are subscribed to the Google Groups sqlalchemy group. To post to this group, send email to sqlalch...@googlegroups.com. To unsubscribe from this group, send email to sqlalchemy+unsubscr...@googlegroups.com. For more options, visit this group at http://groups.google.com/group/sqlalchemy?hl=en.
Re: [sqlalchemy] MapperExtension.[before|after]_update problem
On 10/13/2010 10:55 AM, Christophe de Vienne wrote: Hi all, I am running into an issue with MapperExtension.[before|after]_update. Context --- SQLAlchemy 0.5.8 TurboGears 1.1.1 Description --- I will attempt a simple description first, as I don't think my actual code will help (I know it is not a thing to say, but really). We have 2 mapped classes, Parent and Child. Child is mapped this way : mapper(Child, child_table, properties={ parent=relation(Parent, backref='children') }) And parent has a mapperextension that defines a after_update : def after_update(self, mapper, connection, instance): for child in instance.children: child.name = 'another name' If I do 2 session flush() after modifying a Parent instance, the modifications on the children should be reflected to the database. It is the case in my unit tests if I use directly the DBSession and manipulate the objects 'myself'. BUT, if I go through the complete TG stack, in the unittests or in real-life, the modifications done on child are never sent to the database. One subtle thing though : if, before the first flush(), I access the children attribute, the problem goes away. Example : parent = DBSession.query(Parent).get('myid') parent.name = 'test' # parent.children # Un-commenting this line solve the issue, but of # course it is not an acceptable solution DBSession.flush() DBSession.flush() I could not reproduce in a simpler context, and don't know how to go further in my investigation. Help ? Thanks Christophe AFAIK SQLAlchemy does not support the following in MapperExtensions: * lazy-loading related objects (maybe?) * changing the flush plan, which I believe means changing which objects are considered new, dirty, or deleted Your code is possibly trying to do both. You need to instead create a SessionExtension and override before_flush, which allows you to modify the session however you want, e.g. (untested): class MySessionExtension(object): def before_flush(self, session, flush_context, instances): for obj in session.dirty: if isinstance(obj, Parent): for child in obj.children: child.name = 'another name' -Conor -- You received this message because you are subscribed to the Google Groups sqlalchemy group. To post to this group, send email to sqlalch...@googlegroups.com. To unsubscribe from this group, send email to sqlalchemy+unsubscr...@googlegroups.com. For more options, visit this group at http://groups.google.com/group/sqlalchemy?hl=en.
[sqlalchemy] Cannot retrieve PostgreSQL array column with session.query() : TypeError: unhashable type: 'list'
Hello, The problem I'm seeing is illustrated by the code below. I tried a workaround using TypeDecorator with process_result_value returning a tuple rather than a list, to no avail. Any help will be greatly appreciated. Regards. Traceback : Traceback (most recent call last): File satest2.py, line 23, in module session.query(Foo, 'col').from_statement(SELECT 55 AS foo_bar, '{1,2,3}'::integer[] AS col;).first() File /home/user/programs/env/lib/python2.6/site-packages/sqlalchemy/ orm/query.py, line 1494, in first ret = list(self)[0:1] File /home/user/programs/env/lib/python2.6/site-packages/sqlalchemy/ orm/query.py, line 1682, in instances rows = filter(rows) File /home/jdemoor/programs/km/lib/python2.6/site-packages/ sqlalchemy/util.py, line 1193, in unique_list return [x for x in seq if x not in seen and not seen.add(x)] TypeError: unhashable type: 'list' Full code : import os from sqlalchemy import create_engine, Table, Integer, MetaData, Column from sqlalchemy.orm import create_session, mapper sa_engine = create_engine(os.environ['TEST_DSN']) session = create_session(sa_engine, autoflush=True, expire_on_commit=True, autocommit=False) metadata = MetaData() foo = Table('foo', metadata, Column('bar', Integer, primary_key=True)) class Foo(object): pass mapper(Foo, foo) # This works assert session.query('col').from_statement(SELECT 'abc' AS col;).first() == ('abc',) assert session.query('col').from_statement(SELECT '{1,2,3}'::integer[] AS col;).first() == ([1,2,3],) assert session.query('col1', 'col2').from_statement(SELECT '{1,2,3}'::integer[] AS col1, 'abc' AS col2;).first() == ([1,2,3], 'abc') foo_obj = session.query(Foo).from_statement(SELECT 1 AS foo_bar;).first() assert foo_obj.bar == 1 try: # This fails session.query(Foo, 'col').from_statement(SELECT 55 AS foo_bar, '{1,2,3}'::integer[] AS col;).first() except TypeError, e: print e from sqlalchemy.dialects.postgresql.base import ARRAY col = Column('col', ARRAY(Integer, mutable=False)) try: # This fails too session.query(Foo, col).from_statement(SELECT 55 AS foo_bar, '{1,2,3}'::integer[] AS col;).first() except TypeError, e: print e -- You received this message because you are subscribed to the Google Groups sqlalchemy group. To post to this group, send email to sqlalch...@googlegroups.com. To unsubscribe from this group, send email to sqlalchemy+unsubscr...@googlegroups.com. For more options, visit this group at http://groups.google.com/group/sqlalchemy?hl=en.
Re: [sqlalchemy] Cannot retrieve PostgreSQL array column with session.query() : TypeError: unhashable type: 'list'
The Query runs the result through unique_list() anytime there are mapped entities in the columns list. The ARRAY result, returning a Python list [], isn't hashable, so thats that. If you only queried for columns, it wouldn't be running through unique_list(). I suppose we'd modify ARRAY to return tuples if it's mutable flag isn't set. that could only be in 0.7, though. Let me know if that works for you, we'll add a ticket (hard for me to say since I never use the ARRAY type). On Oct 13, 2010, at 2:22 PM, Julien Demoor wrote: Hello, The problem I'm seeing is illustrated by the code below. I tried a workaround using TypeDecorator with process_result_value returning a tuple rather than a list, to no avail. Any help will be greatly appreciated. Regards. Traceback : Traceback (most recent call last): File satest2.py, line 23, in module session.query(Foo, 'col').from_statement(SELECT 55 AS foo_bar, '{1,2,3}'::integer[] AS col;).first() File /home/user/programs/env/lib/python2.6/site-packages/sqlalchemy/ orm/query.py, line 1494, in first ret = list(self)[0:1] File /home/user/programs/env/lib/python2.6/site-packages/sqlalchemy/ orm/query.py, line 1682, in instances rows = filter(rows) File /home/jdemoor/programs/km/lib/python2.6/site-packages/ sqlalchemy/util.py, line 1193, in unique_list return [x for x in seq if x not in seen and not seen.add(x)] TypeError: unhashable type: 'list' Full code : import os from sqlalchemy import create_engine, Table, Integer, MetaData, Column from sqlalchemy.orm import create_session, mapper sa_engine = create_engine(os.environ['TEST_DSN']) session = create_session(sa_engine, autoflush=True, expire_on_commit=True, autocommit=False) metadata = MetaData() foo = Table('foo', metadata, Column('bar', Integer, primary_key=True)) class Foo(object): pass mapper(Foo, foo) # This works assert session.query('col').from_statement(SELECT 'abc' AS col;).first() == ('abc',) assert session.query('col').from_statement(SELECT '{1,2,3}'::integer[] AS col;).first() == ([1,2,3],) assert session.query('col1', 'col2').from_statement(SELECT '{1,2,3}'::integer[] AS col1, 'abc' AS col2;).first() == ([1,2,3], 'abc') foo_obj = session.query(Foo).from_statement(SELECT 1 AS foo_bar;).first() assert foo_obj.bar == 1 try: # This fails session.query(Foo, 'col').from_statement(SELECT 55 AS foo_bar, '{1,2,3}'::integer[] AS col;).first() except TypeError, e: print e from sqlalchemy.dialects.postgresql.base import ARRAY col = Column('col', ARRAY(Integer, mutable=False)) try: # This fails too session.query(Foo, col).from_statement(SELECT 55 AS foo_bar, '{1,2,3}'::integer[] AS col;).first() except TypeError, e: print e -- You received this message because you are subscribed to the Google Groups sqlalchemy group. To post to this group, send email to sqlalch...@googlegroups.com. To unsubscribe from this group, send email to sqlalchemy+unsubscr...@googlegroups.com. For more options, visit this group at http://groups.google.com/group/sqlalchemy?hl=en. -- You received this message because you are subscribed to the Google Groups sqlalchemy group. To post to this group, send email to sqlalch...@googlegroups.com. To unsubscribe from this group, send email to sqlalchemy+unsubscr...@googlegroups.com. For more options, visit this group at http://groups.google.com/group/sqlalchemy?hl=en.
Re: [sqlalchemy] getting floats instead of decimals from session.execute
use text() with Numeric(as_decimal=False) On Oct 13, 2010, at 10:01 AM, Chris Withers wrote: Hi All, If I'm doing: session.execute('select some_numeric from some_table') ...how do I get floats back in the result instead of decimals? Chris -- You received this message because you are subscribed to the Google Groups sqlalchemy group. To post to this group, send email to sqlalch...@googlegroups.com. To unsubscribe from this group, send email to sqlalchemy+unsubscr...@googlegroups.com. For more options, visit this group at http://groups.google.com/group/sqlalchemy?hl=en. -- You received this message because you are subscribed to the Google Groups sqlalchemy group. To post to this group, send email to sqlalch...@googlegroups.com. To unsubscribe from this group, send email to sqlalchemy+unsubscr...@googlegroups.com. For more options, visit this group at http://groups.google.com/group/sqlalchemy?hl=en.
Re: [sqlalchemy] getting floats instead of decimals from session.execute
On 13/10/2010 22:37, Michael Bayer wrote: use text() with Numeric(as_decimal=False) I can't quite join the dots on this one... I get passed a bunch of sql to execute, I don't have control over that. Where do I wire in Numeric(as_decimal=False) and how do I tell where I need to given an arbitrary select as a string of sql? cheers, Chris -- Simplistix - Content Management, Batch Processing Python Consulting - http://www.simplistix.co.uk -- You received this message because you are subscribed to the Google Groups sqlalchemy group. To post to this group, send email to sqlalch...@googlegroups.com. To unsubscribe from this group, send email to sqlalchemy+unsubscr...@googlegroups.com. For more options, visit this group at http://groups.google.com/group/sqlalchemy?hl=en.