[sqlalchemy] Howto identify connection which has not been returned back to the pool?
Dear All, Having a logging functionality to trace creation, checkout, and checkin connection from pool is very helpfull. however is there a way to identify connection which has not been returned back to the pool for a period of time? I suspect I had a stale connection object which does not returned back to the pool in my code but i cannot sure, I just get the database server run out of bufferpool stating i have too many uncommitted rowset after running for few days. I don't understand, i did commit/rollback consistently for every, mostly probably, data manipulation routine in my code. And at final execution i did recheck any active transaction left and do rollback before returning the session back to the pool. Lastly, the pool has also been configured to recycle connection after 2 minutes to ensure no pending transaction left. However, i might be missed here. sqlalchemy.pool.QueuePool.0x...0x2:Connection exceeded timeout; recycling sqlalchemy.pool.QueuePool.0x...0x2:Closing connection sqlalchemy.pool.QueuePool.0x...0x2:Created new connection sqlalchemy.pool.QueuePool.0x...0x2:Connection checked out from pool sqlalchemy.pool.QueuePool.0x...0x2:Connection being returned to pool -- Salam, -Jaimy Azle -- You received this message because you are subscribed to the Google Groups "sqlalchemy" group. To post to this group, send email to sqlalchemy@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] ResourceClosedError with large Text columns
On Mar 17, 2011, at 9:11 PM, Martin wrote: > I have a table with a Text column, which i manually set up as a > MEDIUMTEXT type in MySQL (5.0), since MySQL's 2**16 character limit is > not enough for my application. Now when I store large chunks of text > in that column, and try to get it back, SQLAlchemy raises an > ResourceClosedError, saying that my result object does not return any > rows, example: > res=engine.execute('select id from mytable where length(text)>100') res.fetchall() > [('1a9008a84520dc6ec5e4d6607174291d6b10efa3',), > ('9781c913a78e90587af24706cb96bdbbc5e71a30',)] res = engine.execute('select * from mytable where length(text) > 100') res.fetchall() It means the MySQLdb cursor object does not have a .description attribute, indicating that its not a row-returning construct. That would appear to be the wrong answer from MySQLdb. Construct a MySQLdb test case for this one to see if this is an error on their end: import MySQLdb connection = MySQLdb.connect(user='', passwd='', host='', dbname='') cursor = connection.cursor() cursor.execute('select * from table where length(text) > 100') assert cursor.description print cursor.fetchall() > Traceback (most recent call last): > File "", line 1, in > File "/foobar/lib/python2.6/site-packages/SQLAlchemy-0.6.6-py2.6.egg/ > sqlalchemy/engine/base.py", line 2498, in fetchall >l = self.process_rows(self._fetchall_impl()) > File "/foobar/lib/python2.6/site-packages/SQLAlchemy-0.6.6-py2.6.egg/ > sqlalchemy/engine/base.py", line 2467, in _fetchall_impl >self._non_result() > File "/foobar/lib/python2.6/site-packages/SQLAlchemy-0.6.6-py2.6.egg/ > sqlalchemy/engine/base.py", line 2472, in _non_result >"This result object does not return rows. " > sqlalchemy.exc.ResourceClosedError: This result object does not return > rows. It has been closed automatically. > > I googled for the exception type and description, but nothing useful > came up. Does anyone have an idea what's going wrong here? > > Cheers, > Martin > > -- > You received this message because you are subscribed to the Google Groups > "sqlalchemy" group. > To post to this group, send email to sqlalchemy@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 sqlalchemy@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] ResourceClosedError with large Text columns
I have a table with a Text column, which i manually set up as a MEDIUMTEXT type in MySQL (5.0), since MySQL's 2**16 character limit is not enough for my application. Now when I store large chunks of text in that column, and try to get it back, SQLAlchemy raises an ResourceClosedError, saying that my result object does not return any rows, example: >>> res=engine.execute('select id from mytable where length(text)>100') >>> res.fetchall() [('1a9008a84520dc6ec5e4d6607174291d6b10efa3',), ('9781c913a78e90587af24706cb96bdbbc5e71a30',)] >>> res = engine.execute('select * from mytable where length(text) > 100') >>> res.fetchall() Traceback (most recent call last): File "", line 1, in File "/foobar/lib/python2.6/site-packages/SQLAlchemy-0.6.6-py2.6.egg/ sqlalchemy/engine/base.py", line 2498, in fetchall l = self.process_rows(self._fetchall_impl()) File "/foobar/lib/python2.6/site-packages/SQLAlchemy-0.6.6-py2.6.egg/ sqlalchemy/engine/base.py", line 2467, in _fetchall_impl self._non_result() File "/foobar/lib/python2.6/site-packages/SQLAlchemy-0.6.6-py2.6.egg/ sqlalchemy/engine/base.py", line 2472, in _non_result "This result object does not return rows. " sqlalchemy.exc.ResourceClosedError: This result object does not return rows. It has been closed automatically. I googled for the exception type and description, but nothing useful came up. Does anyone have an idea what's going wrong here? Cheers, Martin -- You received this message because you are subscribed to the Google Groups "sqlalchemy" group. To post to this group, send email to sqlalchemy@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] Re: Getting instances that contains other instances in an N:M relationship
Got it: query = session.query(Store.Store) query = query.join('userGroups', 'users') query = query.filter(User.User.id == int(userId)) print str(query.all()) >From the examples inside the sqlalchemy egg (http://prdownloads.sourceforge.net/sqlalchemy/SQLAlchemy-0.6.6.tar.gz?download) In the examples/association/basic_association.py file. Nice!. P.S.: Now I'm a little bit down, because I've spent one whole day figuring out something that is explained inside a file called "basic_association"... :-D What will be an "advanced_association"?? 2011/3/16 Hector Blanco : > Hello everyone! > > I am reopening that because now I want to go an step further... And > I'm having troubles. > > Let's say I have an Store class that has a relationship pointing to > UserGroup that has a relationship pointing to Users. > > I'm trying to create a method getStoresByUserId(parameterUserId) that, > if I pass a numeric user id as a parameter, would give me a list of > the stores that said user "can see". I have modeled it like: > > class Store(declarativeBase): > __tablename__ = "stores" > > _name = Column("name", String(50)) > > _userGroups = relationship("UserGroup", secondary=user_group_store, > order_by=lambda:UserGroup.name, > primaryjoin=lambda: Store.id == user_group_store.c.store_id, > secondaryjoin=lambda: UserGroup.id == > user_group_store.c.user_group_id, > collection_class=set > ) > > class UserGroup(declarativeBase): > __tablename__ = "user_groups" > > _name = Column("name", String(50)) > #_users: Backref from User > > class User(declarativeBase): > __tablename__ = "users" > > _firstName = Column("first_name", String(50)) > _lastName = Column("last_name", String(50)) > _userName = Column("user_name", String(50), unique=True, > nullable=False) > _password = Column("password", String(64), nullable=False) > > _userGroupId = Column("user_group_id", Integer, > ForeignKey("user_groups.id")) > _userGroup = relationship("UserGroup", uselist=False, > backref=backref("_users", > collection_class=set > )) > > So, in the method I want to create, > (getStoresByUserId(parameterUserId) or something like that) I > understand that I have to load the Store.userGroups, then load the > users of the UserGroup(s) and then check that that User.id == > parameterId > > I have tried: > query = query.select_from(join(Store.Store.userGroups, > UserGroup.UserGroup, UserGroup.UserGroup.users, > User.User).filter(User.User.id == int(parameterId))) > > ...and... erm... several other thousands of combinations like that... > Without luck. With that, I get: > AttributeError: Neither 'property' object nor 'function' object has an > attribute 'corresponding_column' > > In some other cases I get "Store"s (instances) but they are not > properly filtered. It looks like it's getting all the stores assigned > to any userGroup, without filtering by the user id... > > Now I'm kind of lost. > > Thank you in advance! > > 2011/3/16 Hector Blanco : >> Hello everyone! >> >> In my application I have a class "Store" that can contain several >> "UserGroup"s (for permission purposes) and one "UserGroup" can belong >> to several "Stores". >> >> I want to get the "Stores" that contain a certain "UserGroup" (instance): >> >> I have it modeled like this: >> >> class Store(declarativeBase): >> __tablename__ = "stores" >> >> _id = Column("id", Integer, primary_key=True) >> _name = Column("name", String(50)) >> _number = Column("number", Integer) >> >> _storeGroupId = Column("store_group_id", Integer, >> ForeignKey("store_groups.id")) >> >> >> # _devices: Backref from Device >> >> _userGroups = relationship("UserGroup", secondary=user_group_store, >> order_by=lambda:UserGroup.UserGroup.name, >> primaryjoin=lambda: Store.id == user_group_store.c.store_id, >> secondaryjoin=lambda: UserGroup.UserGroup.id == >> user_group_store.c.user_group_id, >> collection_class=set >> ) >> >> And: >> >> class UserGroup(declarativeBase): >> __tablename__ = "user_groups" >> >> _id = Column("id", Integer, primary_key=True) >> _name = Column("name", String(50)) >> #_users: Backref from User >> >> I want to create a method (something like >> getStoresByUserGroup(userGroup) ) that accepts a userGroup instance >> (or id) and returns only the stores that contain that "userGroup". >> >> That should allow me to "hide" certain stores for certain user groups. >> The use case is: The user who is currently logged into my application >> will belong to a certain user group. If he wants to access the >> "stores" stored in the database, he will only see the ones that have >> that user's userGroup among the Store._userGroups set. >> >> I'm trying to join the Store with the
Re: [sqlalchemy] Re: subquery as a mapper property
On Mar 17, 2011, at 11:05 AM, hoesley wrote: > Awesome, thank you much. It is correlated to the parent. The query- > enabled properties section looks interesting to me. Will there be a > significant performance difference between the two approaches? I want > this to be lazily evaluated, so that this information is never fetched > unless we actually request that attribute. then the simplest approach is the query-enabled property. It is no more than having a method on your object that emits a SELECT statement when called upon. The value can also be cached on "self' once created the first time, if that's appropriate. > > On Mar 16, 3:44 pm, Michael Bayer wrote: >> this kind of pattern is usually handled by column_property(), assuming you >> can correlate your subquery to the parent within the WHERE clause such that >> the return value is a scalar. >> >> Below if you really just wanted "the first row" you'd want to say >> "limit(1)". If you really want that exact same first row of the table >> every time, it would be better as just an additional method or descriptor on >> your OrderChain object, (or even if not) perhaps even as a class method if >> the value truly has no correlation to the identity of the parent (which >> seems unlikely). >> >> Two different strategies at: >> >> http://www.sqlalchemy.org/docs/orm/mapper_config.html#sql-expressions... >> >> http://www.sqlalchemy.org/docs/orm/relationships.html#building-query-...- >> specific to relationship(), but the same idea could be applied to columns >> too. >> >> On Mar 16, 2011, at 10:23 AM, hoesley wrote: >> >> >> >> >> >> >> >>> I am trying to create a property on a mapped class which basically >>> executes a subquery. Here is what I'm trying to do in non-working >>> pseudo code: >> >>> mapper(OrderChain, Table('order_chains',self.meta, >>> autoload=True), >>>properties={'entries': relation(OrderChainEntry, >>> order_by=Column('timestamp')), >>>'first_cancel': >>> select(OrderChainEntry).filter('type'='new').first() >>> }) >> >>> Is something like this possible? Or what's the best way to approach >>> it? >> >>> Also, if I've mangled terminology and/or written something that makes >>> no sense, please let me know - I'm very new to this package! >> >>> Cheers, >>> Andrew >> >>> -- >>> You received this message because you are subscribed to the Google Groups >>> "sqlalchemy" group. >>> To post to this group, send email to sqlalchemy@googlegroups.com. >>> To unsubscribe from this group, send email to >>> sqlalchemy+unsubscr...@googlegroups.com. >>> For more options, visit this group >>> athttp://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 sqlalchemy@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 sqlalchemy@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] Re: attribute not updating
You need to create a single file Python script, which creates a CoverBatchStackItem class with just two columns - "id" and "qty".Then, it inserts one row into a local sqlite database, then loads, updates qty in the manner in which you describe, and commits. Use the examples in the object relational tutorial as a guide to conventions. When that works as expected, that is the test case you start with. If it does not work as expected, send it to me and I can tell you what's wrong with it.But assuming it works, the job is then to slowly work along each element of your actual application to determine what about your app is different from the working specimen. Add new elements to your specimen corresponding to your application one at a time, to determine the trigger that causes the problem. This is a very pedantic way of going about things, but the excerpts you've given me are extremely simple and no such issue should be occurring. So the issue most likely lies within subtle artifacts of your actual code. On Mar 17, 2011, at 10:20 AM, writeson wrote: > Michael, > > I tried creating a simple standalone example using our data, but the > table relations complexity would make the example fairly huge. So > unfortunately that means I didn't get one working. > > In my Pylons applications the sequence of events are as follows: > > get a session > create a new item > add the item to the session > session commit > // sometime later > get a session > get an item from the session with a query > modify the qty value of the item > session commit > > I have resolved the issue by hacking my code to do the following: > > session = Session() > session.query(CoverBatchStackItem) \ > .filter((CoverBatchStackItem.cover_batch_id==cover_batch_id) and > (CoverBatchStackItem.order_id==foid)) \ > .update({CoverBatchStackItem.qty: qty}) > session.commit() > > where qty is passed into the method that executes this code. Here I'm > querying for the item and updating it in one long statement. This > works but looks ugly compared to the original code. > > Thanks! > Doug > > -- > You received this message because you are subscribed to the Google Groups > "sqlalchemy" group. > To post to this group, send email to sqlalchemy@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 sqlalchemy@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] trouble with metaclass
On 16/03/2011 21:01, farcat wrote: I have an error i cant figure out (likely a beginners error): Beginners should not be using metaclasses. What's your use case here? 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 sqlalchemy@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] In-memory object duplication
> -Original Message- > From: sqlalchemy@googlegroups.com [mailto:sqlalchemy@googlegroups.com] > On Behalf Of Jacques Naude > Sent: 17 March 2011 12:32 > To: sqlalchemy@googlegroups.com > Subject: Re: [sqlalchemy] In-memory object duplication > > Hi, Simon > > Thanks for the quick response. > > Elixir doesn't use __init__ - there's something automatic going on > there. My create(), in essence, does the job of __init__, which means > you might still be hitting the nail on the head. I haven't had the > time to test it out yet, but I will. (Why, though, would the double > entry not be persisted to the database too?) > The entry only appears once in the database because SQAlchemy works hard to ensure that a single object instance corresponds to a single row in the database. It doesn't really make sense (in the standard one-to-many model) for a particular child to appear more than once in a parent-child relationship. By default, SA uses a list as the collection implementation for relationships, and doesn't care if you add the same instance more than once. If it bothers you, you could use a set instead: http://www.sqlalchemy.org/docs/orm/collections.html#customizing-collecti on-access Simon -- You received this message because you are subscribed to the Google Groups "sqlalchemy" group. To post to this group, send email to sqlalchemy@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] Re: subquery as a mapper property
Awesome, thank you much. It is correlated to the parent. The query- enabled properties section looks interesting to me. Will there be a significant performance difference between the two approaches? I want this to be lazily evaluated, so that this information is never fetched unless we actually request that attribute. On Mar 16, 3:44 pm, Michael Bayer wrote: > this kind of pattern is usually handled by column_property(), assuming you > can correlate your subquery to the parent within the WHERE clause such that > the return value is a scalar. > > Below if you really just wanted "the first row" you'd want to say "limit(1)". > If you really want that exact same first row of the table every time, it > would be better as just an additional method or descriptor on your OrderChain > object, (or even if not) perhaps even as a class method if the value truly > has no correlation to the identity of the parent (which seems unlikely). > > Two different strategies at: > > http://www.sqlalchemy.org/docs/orm/mapper_config.html#sql-expressions... > > http://www.sqlalchemy.org/docs/orm/relationships.html#building-query-...- > specific to relationship(), but the same idea could be applied to columns too. > > On Mar 16, 2011, at 10:23 AM, hoesley wrote: > > > > > > > > > I am trying to create a property on a mapped class which basically > > executes a subquery. Here is what I'm trying to do in non-working > > pseudo code: > > > mapper(OrderChain, Table('order_chains', self.meta, > > autoload=True), > > properties={'entries': relation(OrderChainEntry, > > order_by=Column('timestamp')), > > 'first_cancel': > > select(OrderChainEntry).filter('type'='new').first() > > }) > > > Is something like this possible? Or what's the best way to approach > > it? > > > Also, if I've mangled terminology and/or written something that makes > > no sense, please let me know - I'm very new to this package! > > > Cheers, > > Andrew > > > -- > > You received this message because you are subscribed to the Google Groups > > "sqlalchemy" group. > > To post to this group, send email to sqlalchemy@googlegroups.com. > > To unsubscribe from this group, send email to > > sqlalchemy+unsubscr...@googlegroups.com. > > For more options, visit this group > > athttp://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 sqlalchemy@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] Re: Association proxy like for integer/string/types list
Thanks ! To respond to my needs, it becomes : class NodeAttribute(Base): __tablename__ = 'node_attribute' node_id = Column('n_id', Integer, ForeignKey('node.n_id'), primary_key=True) attribute = Column('na_id', String, primary_key=True) def __init__(self, attribute): self.attribute = attribute class Node(Base): __tablename__ = 'node' id = Column('n_id', Integer, primary_key=True) node_attributes = relationship(NodeAttribute, cascade="all, delete-orphan", lazy='joined', collection_class=list) attributes = AssociationProxy('node_attributes', 'attribute') On Mar 17, 1:57 am, Michael Bayer wrote: > On Mar 16, 2011, at 8:12 PM, zaza witch wrote: > > > Hi everyone, > > > I am currently in work experience ... > > > The first step of my work was to build a small application using > > sqlalchemy. > > > Association proxy seems to allow to simplify many-to-many > > relationships management. > > Can i use it to store define a class with an attribute which is a list > > of string (or integers ...) ? > > I recently put up an example of this which deals with lists of dicts of > integers, it can be adapted to do lists of strings: > > http://groups.google.com/group/sqlalchemy/msg/342a8c4d814d520a > > > Let me explain: > > > With association proxy, i can do something like: > > > class Service(Base): > > __tablename__ = 'service' > > id = Column('s_id', Integer, primary_key=True) > > name = Column('s_name', String(63), unique=True) > > class NodeService(Base): > > __tablename__ = 'node_service' > > node_id = Column('n_id', Integer, ForeignKey('node.n_id'), > > primary_key=True) > > service_id = Column('s_id', Integer, ForeignKey('service.s_id'), > > primary_key=True) > > service = relationship(Service lazy='joined') > > class Node(Base): > > __tablename__ = 'node' > > id = Column('n_id', Integer, primary_key=True) > > node_services = relationship(NodeService, cascade="all, delete- > > orphan", lazy='joined') > > services = AssociationProxy('nodes_services', 'service', lambda > > service: NodeService(service=service)) > > ... > > mynode = Node() > > mynode.services.append(Service("myservice")) > > # instead of > > mynode.node_services.append(NodeService(service=Service("myservice") > > session.add(mynode) > > > Is there a way to suppress the Service class in order to handle a list > > of string (from python point of view) and have something like: > > > class NodeAttribute(Base): > > __tablename__ = 'node_attribute' > > node_id = Column('n_id', Integer, ForeignKey('node.n_id'), > > primary_key=True) > > attribute = Column('na_id', String, primary_key=True) > > class Node(Base): > > __tablename__ = 'node' > > id = Column('n_id', Integer, primary_key=True) > > node_services = relationship(NodeService, cascade="all, delete- > > orphan", lazy='joined') > > node_attributes = relationship(NodeAttribute cascade="all, delete- > > orphan", lazy='joined') > > services = AssociationProxy('nodes_services', 'service', lambda > > service: NodeService(service=service)) > > attributes = AssociationProxyLike('node_attributes', ?, ?) > > > mynode = Node() > > mynode.attributes.append("myattribute") > > # instead of > > mynode.node_attributes.append(NodeAttribute("myattribute")) > > # attributes look like a list of string (with append/del functions) > > session.add(mynode) > > > The second step is to replace sqlalchemy+database by something > > else ... i will make an other message on the topic > > > -- > > You received this message because you are subscribed to the Google Groups > > "sqlalchemy" group. > > To post to this group, send email to sqlalchemy@googlegroups.com. > > To unsubscribe from this group, send email to > > sqlalchemy+unsubscr...@googlegroups.com. > > For more options, visit this group > > athttp://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 sqlalchemy@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] Re: attribute not updating
Michael, I tried creating a simple standalone example using our data, but the table relations complexity would make the example fairly huge. So unfortunately that means I didn't get one working. In my Pylons applications the sequence of events are as follows: get a session create a new item add the item to the session session commit // sometime later get a session get an item from the session with a query modify the qty value of the item session commit I have resolved the issue by hacking my code to do the following: session = Session() session.query(CoverBatchStackItem) \ .filter((CoverBatchStackItem.cover_batch_id==cover_batch_id) and (CoverBatchStackItem.order_id==foid)) \ .update({CoverBatchStackItem.qty: qty}) session.commit() where qty is passed into the method that executes this code. Here I'm querying for the item and updating it in one long statement. This works but looks ugly compared to the original code. Thanks! Doug -- You received this message because you are subscribed to the Google Groups "sqlalchemy" group. To post to this group, send email to sqlalchemy@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] In-memory object duplication
Hi, Simon Thanks for the quick response. Elixir doesn't use __init__ - there's something automatic going on there. My create(), in essence, does the job of __init__, which means you might still be hitting the nail on the head. I haven't had the time to test it out yet, but I will. (Why, though, would the double entry not be persisted to the database too?) Thanks you very much for your response and proposed solution. Will keep you posted. (I was rather hoping for more people to offer guidance in this matter, but there you have it.) Regards Jacques On 15 March 2011 18:51, King Simon-NFHD78 wrote: > > -Original Message- > > From: sqlalchemy@googlegroups.com [mailto:sqlalchemy@googlegroups.com] > > On Behalf Of jln > > Sent: 15 March 2011 16:37 > > To: sqlalchemy > > Subject: [sqlalchemy] In-memory object duplication > > > > [SNIP] > > > statuses = OneToMany('DocumentStatus', inverse='doc', cascade='all, > > delete-orphan', order_by=['timestamp']) > > > > So, when I create a new DocumentStatus object, Document.statuses > > lists > > two of them, but not actually persisted to the database. In other > > words, leaving my Python shell, and starting the model from scratch, > > there actually is only one child object (corroborated by squizzing > > the > > database directly). Here's my DocumentStatus.create() class method: > > > > @classmethod > > @logged_in > > @log_input > > def create(cls, doc, status, person=None, date=None): > > person=validate_person(person) > > if person: > > status = DocumentStatus(doc=doc, status=status, > > person=person, date=resolve_datetime(date)) > > if status: > > doc.statuses.append(status) > > doc.flush() > > out = 'Document status created' > > success = True > > else: > > out = 'Document status not created' > > success = False > > else: > > out = 'Person does not exist' > > success = False > > log_output(out) > > return success > > > > I simply don't know why this is happening or, as I said, how to > > search, intelligently, for an answer. > > I don't know Elixir, but I assume that the "inverse='doc'" line in the > relationship sets up an SQLAlchemy backref. If so, then setting > status.doc (presumably done in DocumentStatus.__init__) will > automatically populate doc.statuses at the same time. > > So when you do doc.statuses.append(status) a bit later on, you're adding > it to the list a second time. > > Hope that helps, > > Simon > > -- > You received this message because you are subscribed to the Google Groups > "sqlalchemy" group. > To post to this group, send email to sqlalchemy@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 sqlalchemy@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] trouble with metaclass
> -Original Message- > From: sqlalchemy@googlegroups.com [mailto:sqlalchemy@googlegroups.com] > On Behalf Of farcat > Sent: 16 March 2011 21:01 > To: sqlalchemy > Subject: [sqlalchemy] trouble with metaclass > > I have an error i cant figure out (likely a beginners error): > > # > Base = declarative_base() > > class tablemeta(DeclarativeMeta): > def __new__(mcls, name): > return DeclarativeMeta.__new__(mcls, name, (Base,), {}) > def _init__(cls, name): > temp = dict() > temp["__tablename__"] = "_" + name > temp["id"] = Column(Integer, primary_key = True) > temp["text"] = Column(String(120)) > DeclarativeMeta.__init__(cls, name, (Base,), temp) > > > if __name__ == "__main__": > engine = create_engine('sqlite:///:memory:', echo=True) > Base.metadata.drop_all(engine) > Base.metadata.create_all(engine) > Session = sessionmaker(bind=engine) > session = Session() > table1 = tablemeta("table1") #=> ERROR > row1 = table1(text = "detextenzo") > row2 = table1(text = "detextenzoennogeenbeetje") > session.commit() > list = session.query(table1).all() > for l in list: > print str(l) > print "done" > > # > the error is: > # > Traceback (most recent call last): > File "D:\Documents\Code\NetBeans\test\temp\src\temp.py", line 33, > in > > table1 = tablemeta("table1") > TypeError: __init__() takes exactly 4 arguments (2 given) > # > > I do not understand what __init__ i am miscalling: I call > tablemeta.__init__ with 2 (1 implicit) as defined and > DeclarativeMeta.__init__ with 4 as defined? > > please help ... > I'm not sure if it's the cause of your problem, but you have a typo in tablemeta - your __init__ only has 1 underscore at the beginning... Hope that helps, Simon -- You received this message because you are subscribed to the Google Groups "sqlalchemy" group. To post to this group, send email to sqlalchemy@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.