[sqlalchemy] Re: ProgrammingError and Catching an Exception

2008-09-11 Thread Barry Hart
I don't know of a way to do what you're asking. However, you could simply 
create your own constructor for MyDBLog which truncates the string if it is too 
long.


Barry


- Original Message 
From: Eoghan Murray [EMAIL PROTECTED]
To: sqlalchemy sqlalchemy@googlegroups.com
Sent: Thursday, September 11, 2008 7:21:39 AM
Subject: [sqlalchemy] ProgrammingError and Catching an Exception


Hi,

I've the following which generates an insert:

try:
MyDBLog(
myfield='A too long string '
)
except Exception, e:
log.error(Exception occurred with database logging: %s % e)


Unfortunately, 'myfield' is (for example) a string of only length 10,
so the session fails with
ProgrammingError: (ProgrammingError) value too long for type
character varying(10)

This error occurs at session commit time, so my 'except' clause above
is useless.

As 'MyDBLog' is not critical, I want to be able to ignore/log any kind
of Exception which the 'try' block above ultimately generates.  Is
there a way to do this?

Thanks!

Eoghan


  
--~--~-~--~~~---~--~~
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 [EMAIL PROTECTED]
For more options, visit this group at 
http://groups.google.com/group/sqlalchemy?hl=en
-~--~~~~--~~--~--~---



[sqlalchemy] Re: Pickling/unpickling mapped class

2008-06-27 Thread Barry Hart
I use Gnosis Utils for a similar purpose. The API is similar to pickle, but if 
you need to control the details of the serialization (which fields get 
serialized and how), then that is quite different. Gnosis has a concept called 
mutators for this.

Barry


- Original Message 
From: Michael Bayer [EMAIL PROTECTED]
To: sqlalchemy@googlegroups.com
Sent: Friday, June 27, 2008 9:56:59 AM
Subject: [sqlalchemy] Re: Pickling/unpickling mapped class



On Jun 27, 2008, at 3:25 AM, Nabla wrote:


 Is there some easy solution of this problem?

yes, the receiving application needs to have the same mapper() setup  
as the sender.   If you use the declarative extension to setup your  
classes, this task is made easier.


 And additional question - is there some simple way how to
 convert (marshal, serialize) reflected sqlalchemy class to human-
 readable XML?

we dont have an XML serializer but there might be something on Pypi  
for that.



  
--~--~-~--~~~---~--~~
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 [EMAIL PROTECTED]
For more options, visit this group at 
http://groups.google.com/group/sqlalchemy?hl=en
-~--~~~~--~~--~--~---



[sqlalchemy] Re: Multiple SQLAlchemy DB usage in TurboGears

2008-05-08 Thread Barry Hart
The identity and visit stuff is pluggable, i.e. you can replace the existing 
components without hackery; just write your own and specify which one to use in 
the application .cfg file. This probably sounds more intimidating than it is; 
the code is really pretty straightforward and you can use their implementations 
as a starting point.

You might consider using a single (separate) database to store all visit 
information for *all* the customers combined. Your visit schema could have an 
additional 'customer' column to distinguish which database to use for 
everything else.

Barry


- Original Message 
From: Michael Bayer [EMAIL PROTECTED]
To: sqlalchemy@googlegroups.com
Sent: Thursday, May 8, 2008 5:05:22 PM
Subject: [sqlalchemy] Re: Multiple SQLAlchemy DB usage in TurboGears



On May 8, 2008, at 11:15 AM, Bobby Impollonia wrote:


 I'd try bypassing their SQLA integration altogether if thats possible

 It isn't possible if you are relying on the turbogears identity system
 (cookie-based visitor tracking and access control).

that sounds like a particular set of mappings and classes.  theres no  
issue using those; I was talking about their Session integration.




  

Be a better friend, newshound, and 
know-it-all with Yahoo! Mobile.  Try it now.  
http://mobile.yahoo.com/;_ylt=Ahu06i62sR8HDtDypao8Wcj9tAcJ
--~--~-~--~~~---~--~~
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 [EMAIL PROTECTED]
For more options, visit this group at 
http://groups.google.com/group/sqlalchemy?hl=en
-~--~~~~--~~--~--~---



[sqlalchemy] Re: Duplication of rows in many-to-many relationship

2008-05-04 Thread Barry Hart
By chance, in your mappers, are you declaring two relationships instead of one 
relation with a backref?

As a side note, once you straighten this out, you may want to declare the 
composite (a_id, b_id) as a unique key on the relation table.

Barry


- Original Message 
From: Karlo Lozovina [EMAIL PROTECTED]
To: sqlalchemy sqlalchemy@googlegroups.com
Sent: Sunday, May 4, 2008 4:31:55 PM
Subject: [sqlalchemy] Duplication of rows in many-to-many relationship


Let's say I have two classes A and B, and I want instances of both
classes, to have a list of each other, that is, many-to-many
relationship. For a shorthand, a means instance of A, and b is an
instance of B.

For example: a.bs is a list, full of instances of class B.
Similarly, b.as is a list, full of instances of class A. In
modelling that relationship I use three tables, one for As, one for
Bs, and one for their relationship. If I only append instances of B to
some a.bs, then save all those objects, everything works fine. But
if I append instances of A and B, both to a.bs and b.as, then
save, I get double rows in the third table. Is there a way around
that?

P.S.
In a very likely case I haven't been completely understood, I'll
attach some code to demonstrate my point ;).

Thanks all.


  

Be a better friend, newshound, and 
know-it-all with Yahoo! Mobile.  Try it now.  
http://mobile.yahoo.com/;_ylt=Ahu06i62sR8HDtDypao8Wcj9tAcJ
--~--~-~--~~~---~--~~
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 [EMAIL PROTECTED]
For more options, visit this group at 
http://groups.google.com/group/sqlalchemy?hl=en
-~--~~~~--~~--~--~---



[sqlalchemy] Re: Duplication of rows in many-to-many relationship

2008-05-04 Thread Barry Hart
With a backref, both ends of the relationship are aware of each other -- if you 
append object b1 to the collection a.b, then a backref b1.a will be updated 
immediately. If you had two different relationships, you wouldn't see an update 
to b1.a until you reload the object.

It seems like it'd be nice if they worked the same -- perhaps there's a good 
reason it doesn't.

I think 0.4 has an error check for some cases of mutual relationships (A-B, 
B-A). Maybe the check is not in place for M:N relationships?

Barry


- Original Message 
From: Bobby Impollonia [EMAIL PROTECTED]
To: sqlalchemy@googlegroups.com
Sent: Sunday, May 4, 2008 5:28:56 PM
Subject: [sqlalchemy] Re: Duplication of rows in many-to-many relationship


I thought that defining relation with a backref was just a convenient
shorthand for defining two relations. This makes it sound like are
practical differences between the two techniques. Is this true? What
are the differences?

Also, does having the unique key that you recommend stop SA from
trying to add the duplicate? Or will it try anyway and then get a SQL
exception due to the violated constraint?
I am often doing
if a not in b.as:
b.as.append(a)
and I have been wondering if there is a way to just do:
b.as.append(a)
and have SA automatically check if it was already in collection and
shouldn't be added again.

On Sun, May 4, 2008 at 4:40 PM, Barry Hart [EMAIL PROTECTED] wrote:

 By chance, in your mappers, are you declaring two relationships instead of
 one relation with a backref?

 As a side note, once you straighten this out, you may want to declare the
 composite (a_id, b_id) as a unique key on the relation table.

 Barry


 - Original Message 
 From: Karlo Lozovina [EMAIL PROTECTED]
 To: sqlalchemy sqlalchemy@googlegroups.com
 Sent: Sunday, May 4, 2008 4:31:55 PM
 Subject: [sqlalchemy] Duplication of rows in many-to-many relationship


 Let's say I have two classes A and B, and I want instances of both
 classes, to have a list of each other, that is, many-to-many
 relationship. For a shorthand, a means instance of A, and b is an
 instance of B.

 For example: a.bs is a list, full of instances of class B.
 Similarly, b.as is a list, full of instances of class A. In
 modelling that relationship I use three tables, one for As, one for
 Bs, and one for their relationship. If I only append instances of B to
 some a.bs, then save all those objects, everything works fine. But
 if I append instances of A and B, both to a.bs and b.as, then
 save, I get double rows in the third table. Is there a way around
 that?

 P.S.
 In a very likely case I haven't been completely understood, I'll
 attach some code to demonstrate my point ;).

 Thanks all.

 
 Be a better friend, newshound, and know-it-all with Yahoo! Mobile. Try it
 now.

  




  

Be a better friend, newshound, and 
know-it-all with Yahoo! Mobile.  Try it now.  
http://mobile.yahoo.com/;_ylt=Ahu06i62sR8HDtDypao8Wcj9tAcJ
--~--~-~--~~~---~--~~
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 [EMAIL PROTECTED]
For more options, visit this group at 
http://groups.google.com/group/sqlalchemy?hl=en
-~--~~~~--~~--~--~---



[sqlalchemy] Re: Duplication of rows in many-to-many relationship

2008-05-04 Thread Barry Hart
My fault - when I said there was an error check, it was for the case where you 
declare relationships A-B and B-A both with backrefs. Here's the thread from 
about six months ago:

http://groups.google.com/group/sqlalchemy/browse_thread/thread/420b7de79119ad4d/8e8311bfd18d05e2?lnk=gstq=barry+hart#8e8311bfd18d05e2).

Barry


- Original Message 
From: Michael Bayer [EMAIL PROTECTED]
To: sqlalchemy@googlegroups.com
Sent: Sunday, May 4, 2008 10:31:10 PM
Subject: [sqlalchemy] Re: Duplication of rows in many-to-many relationship



On May 4, 2008, at 8:59 PM, Barry Hart wrote:

With a backref, both ends of the relationship are aware of each other -- if you 
append object b1 to the collection a.b, then a backref b1.a will be updated 
immediately. If you had two different relationships, you wouldn't see an update 
to b1.a until you reload the object.

It seems like it'd be nice if they worked the same -- perhaps there's a good 
reason it doesn't.

I think 0.4 has an error check for some cases of mutual relationships (A-B, 
B-A). Maybe the check is not in place for M:N relationships?

we dont really have any check of A-B / B-A being present without  a backref.  
the backref is technically not needed for a bidirectional o2m/m2o relationship, 
unless the post_update option is being used.  

for the m2m, its explicitly needed since only one side needs to handle the 
association table, and the other side needs to be made aware of that.

we've yet to try working up some alarms for this sort of thingits 
probably not that hard to do so (for every secondary table, look it up in a 
registry, see if its mapped, etc).



  

Be a better friend, newshound, and 
know-it-all with Yahoo! Mobile.  Try it now.  
http://mobile.yahoo.com/;_ylt=Ahu06i62sR8HDtDypao8Wcj9tAcJ
--~--~-~--~~~---~--~~
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 [EMAIL PROTECTED]
For more options, visit this group at 
http://groups.google.com/group/sqlalchemy?hl=en
-~--~~~~--~~--~--~---



[sqlalchemy] Re: VIEW names?

2008-01-25 Thread Barry Hart
SA to be (i.e. would View act read-only, etc..  though I guess VIEWs  
aren't necessarily purely read-only in some cases ?).

Right. For example, I think SQL Server views are updateable to some extent 
(depending on whether there's a table primary key in the column list, whether 
there are joins, etc.) The rules for this are almost certainly DB-specific, too.

Barry

- Original Message 
From: Michael Bayer [EMAIL PROTECTED]
To: sqlalchemy@googlegroups.com
Sent: Friday, January 25, 2008 7:42:10 PM
Subject: [sqlalchemy] Re: VIEW names?




On Jan 25, 2008, at 7:25 PM, Martin wrote:


 Hello,

 since I didn't find a direct way to create a VIEW within SQLalchemy
 v0.4, I use the
 text-feature to do that with a SQL/DDL statement, which is maybe
 not
 elegant, but works...

 Is there a way to get information about Views? (Which Views exist and
 which columns do they provide?)

we dont provide a function for this currently.

adding reflection for views is not a big deal, but the decision to be  
made is how it would be expressed in the API, either as Table(,  
view=True), or View(...).   we'd have to decide how view-aware we want
  
SA to be (i.e. would View act read-only, etc..  though I guess VIEWs  
aren't necessarily purely read-only in some cases ?).









  

Looking for last minute shopping deals?  
Find them fast with Yahoo! Search.  
http://tools.search.yahoo.com/newsearch/category.php?category=shopping
--~--~-~--~~~---~--~~
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 [EMAIL PROTECTED]
For more options, visit this group at 
http://groups.google.com/group/sqlalchemy?hl=en
-~--~~~~--~~--~--~---



[sqlalchemy] Re: Select entire column

2007-11-07 Thread Barry Hart
Is this what you want?

select([my_table.c.my_column], distinct=True)

Barry

- Original Message 
From: JamesT [EMAIL PROTECTED]
To: sqlalchemy sqlalchemy@googlegroups.com
Sent: Wednesday, November 7, 2007 2:05:13 AM
Subject: [sqlalchemy] Select entire column



I am looking to filter specific columns in a table, but I cannot find
how to do this. I can filter by setting these columns to a value, but
not just grabbing the entire column. In SQL, I want to do this:
SELECT artist FROM artist_table, where the only column kept is
artist. The reason I want to do this is so that I can run a distinct()
on the Query object returned to get the distinct artists and also
distinct genres. Here is a sample of what I am doing now without
filtering to get the data I need:

tuples = Session.query(Albums).add_entity(Songs).join('songs').all()








__
Do You Yahoo!?
Tired of spam?  Yahoo! Mail has the best spam protection around 
http://mail.yahoo.com 
--~--~-~--~~~---~--~~
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 [EMAIL PROTECTED]
For more options, visit this group at 
http://groups.google.com/group/sqlalchemy?hl=en
-~--~~~~--~~--~--~---



[sqlalchemy] Re: associative table with extra field

2007-10-27 Thread Barry Hart
I would've declared the relation from Country to CountryLanguage, not vice 
versa, but I doubt that is the reason for your error.


Can you provide a full example which reproduces the error?

Barry

- Original Message 
From: mmstud [EMAIL PROTECTED]
To: sqlalchemy sqlalchemy@googlegroups.com
Sent: Saturday, October 27, 2007 8:02:38 AM
Subject: [sqlalchemy] associative table with extra field



I'm trying to implement associative table with extra field on join
table, but faced problems... what is it, that im doing wrong here,
because i get python error:

.
.
.
2007-10-27 14:58:26,816 INFO sqlalchemy.engine.base.Engine.0x..d0 {}
2007-10-27 14:58:26,816 INFO sqlalchemy.engine.base.Engine.0x..d0
COMMIT
ERROR: Internal Python error in the inspect module.
Below is the traceback from this internal error.

Traceback (most recent call last):
  File /usr/lib/python2.4/site-packages/IPython/ultraTB.py, line
462, in text
records = _fixed_getinnerframes(etb, context,self.tb_offset)
  File /usr/lib/python2.4/site-packages/IPython/ultraTB.py, line
118, in _fixed_getinnerframes
records  = inspect.getinnerframes(etb, context)
  File inspect.py, line 804, in getinnerframes
framelist.append((tb.tb_frame,) + getframeinfo(tb, context))
  File inspect.py, line 768, in getframeinfo
lines, lnum = findsource(frame)
  File inspect.py, line 437, in findsource
if pat.match(lines[lnum]): break
IndexError: list index out of range

Unfortunately, your original traceback can not be constructed.

*

countries_table = Table(countries, metadata,
Column(id, Integer, primary_key=True),
Column(alpha2, String(2)),
Column(alpha3, String(3)),
Column(name, Unicode(100)),
)

# association table with additional field
countries_languages = Table(countries_languages, metadata,
Column(country_id, Integer, ForeignKey('countries.id')),
Column(language_id, Integer, ForeignKey('languages.id')),
Column(is_primary, Boolean, default=False), # only one can be
default at time
)

languages_table = Table(languages, metadata,
Column(id, Integer, primary_key=True),
Column(alpha2, String(2)),
Column(name, Unicode(100)),
)


class BaseObject(object):
def __init__(self):
self._repr_ = []

def __repr__(self):
from string import join
str = ', '.join('%s' % (self.__dict__[v]) for v in
self._repr_)
return %s(%s) % (self.__class__, str)

class NameObject(BaseObject):
def __init__(self, name):
self.name = name
BaseObject.__init__(self)

def __repr__(self):
self._repr_ = [name]
return BaseObject.__repr__(self)

class Country(NameObject):
def __init__(self, alpha2, alpha3, name):
NameObject.__init__(self, name)
self.alpha2 = alpha2
self.alpha3 = alpha3

class CountryLanguage(object):
def __init__(self, is_primary = False):
self.is_primary = is_primary

class Language(NameObject):
def __init__(self, alpha2, name):
NameObject.__init__(self, name)
self.alpha2 = alpha2



mapper(Country, countries_table, properties={
'post_offices':relation(PostOffice, backref='country'), # one to
many
'languages':relation(CountryLanguage, backref='country'), # many
to many
}
)

mapper(CountryLanguage, countries_languages, properties={
'language':relation(Language, backref=countries)
}
)

mapper(Language, languages_table)








__
Do You Yahoo!?
Tired of spam?  Yahoo! Mail has the best spam protection around 
http://mail.yahoo.com 
--~--~-~--~~~---~--~~
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 [EMAIL PROTECTED]
For more options, visit this group at 
http://groups.google.com/group/sqlalchemy?hl=en
-~--~~~~--~~--~--~---



[sqlalchemy] Re: associative table with extra field

2007-10-27 Thread Barry Hart
You need to add an ID column to your countries_languages table, like this:

Column(id, Integer, primary_key=True),

Alternatively you could declare the combination country_id and language_id as 
your primary key.

Barry

- Original Message 
From: mmstud [EMAIL PROTECTED]
To: sqlalchemy sqlalchemy@googlegroups.com
Sent: Saturday, October 27, 2007 3:53:47 PM
Subject: [sqlalchemy] Re: associative table with extra field



That was a good tip. Now i get:

2007-10-27 22:49:25,454 INFO sqlalchemy.engine.base.Engine.0x..90 {}
2007-10-27 22:49:25,455 INFO sqlalchemy.engine.base.Engine.0x..90
COMMIT
Traceback (most recent call last):
  File stdin, line 1, in ?
  File fixtures.py, line 4, in ?
from mappers import *
  File mappers.py, line 39, in ?
mapper(CountryLanguage, countries_languages, properties={
  File build/bdist.linux-x86_64/egg/sqlalchemy/orm/__init__.py, line
516, in mapper
  File build/bdist.linux-x86_64/egg/sqlalchemy/orm/mapper.py, line
152, in __init__
  File build/bdist.linux-x86_64/egg/sqlalchemy/orm/mapper.py, line
414, in _compile_tables
sqlalchemy.exceptions.ArgumentError: Could not assemble any primary
key columns for mapped table 'countries_languages'

I'll provide more full example tomorrow...

Thanks.

On Oct 27, 6:44 pm, Michael Bayer [EMAIL PROTECTED] wrote:
 On Oct 27, 2007, at 8:02 AM, mmstud wrote:



  I'm trying to implement associative table with extra field on join
  table, but faced problems... what is it, that im doing wrong here,
  because i get python error:

 try not using IPython.  shells like IDLE etc. always seem to corrupt
  
 things.  at the very least, youll get a real stack trace.








__
Do You Yahoo!?
Tired of spam?  Yahoo! Mail has the best spam protection around 
http://mail.yahoo.com 
--~--~-~--~~~---~--~~
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 [EMAIL PROTECTED]
For more options, visit this group at 
http://groups.google.com/group/sqlalchemy?hl=en
-~--~~~~--~~--~--~---



[sqlalchemy] Re: In a many to many relationship how to access some properties of that relationship

2007-10-25 Thread Barry Hart
No, the association proxy would be used if you want to let users directly 
access movies or vice versa. To get the score, you can define a mapper for 
movie_vote table and define relationships between it and users and movies.

Barry

- Original Message 
From: Jason [EMAIL PROTECTED]
To: sqlalchemy sqlalchemy@googlegroups.com
Sent: Tuesday, October 23, 2007 7:10:15 PM
Subject: [sqlalchemy] In a many to many relationship how to access some 
properties of that relationship



Greetings,

for my model I have this:

user_table=Table(users, metadata,
Column(id, Integer, primary_key=True),
Column(gender, Unicode),
Column(age, Integer, ForeignKey(ages.id)),
Column(occupation, Integer, ForeignKey(occupations.id)),
Column(zipCode, Integer(5))
)

movie_table=Table(movies, metadata,
Column(id, Integer, primary_key=True),
Column(title, Unicode)
)

movie_vote_table=Table(movie_votes, metadata,
Column(id, Integer, primary_key=True),
Column(user, Integer, ForeignKey(users.id)),
Column(movie, Integer, ForeignKey(movies.id)),
Column(score, Float)
)

I've of course left out some of the other tables that weren't needed
for this question

so I of course a many to many relationship between the users and the
movies they have rated. but the only problem is how do I access that
score?

It would be cool to have something like User.movies[0].score,
User.movies[1].score .. etc.
is this something I would want to use the association proxy for?
-Jason








__
Do You Yahoo!?
Tired of spam?  Yahoo! Mail has the best spam protection around 
http://mail.yahoo.com 
--~--~-~--~~~---~--~~
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 [EMAIL PROTECTED]
For more options, visit this group at 
http://groups.google.com/group/sqlalchemy?hl=en
-~--~~~~--~~--~--~---



[sqlalchemy] Re: Problem when slicing a relation list

2007-10-25 Thread Barry Hart
Here is a test case for the bug. The bug only manifests itself if the 
transaction that slices the list also modifies all the remaining objects in the 
list.

Barry

- Original Message 
From: Michael Bayer [EMAIL PROTECTED]
To: sqlalchemy@googlegroups.com
Sent: Wednesday, October 24, 2007 5:01:43 PM
Subject: [sqlalchemy] Re: Problem when slicing a relation list


hey Barry -

again, can you please attach a working test case for this one ?  attached is 
mine, which tests this exact operation for four diferent kinds of relation()s - 
one-to-many and many to many, with and without delete cascade on the relation.  
passes for 0.3 (including 0.3.10) and 0.4.





-Inline Attachment Follows-

from sqlalchemy import *

from sqlalchemy.orm import *



def test(m2m=False, cascade=False, useclear=False):

engine = create_engine('sqlite://', echo=True)



meta = MetaData(engine)



a = Table('a', meta, Column('id', Integer, primary_key=True), Column('foo', 
String(30)))



if m2m:

b = Table('b', meta, Column('id', Integer, primary_key=True), 
Column('foo', String(30)))

else:

b = Table('b', meta, Column('id', Integer, primary_key=True), 
Column('foo', String(30)), Column('a_id', Integer, ForeignKey('a.id')))



if m2m:

atob = Table('atob', meta, Column('a_id', Integer, ForeignKey('a.id')), 
Column('b_id', Integer, ForeignKey('b.id')), )

else:

atob = None



class A(object):

def __init__(self, foo):

self.foo = foo

class B(object):

def __init__(self, foo):

self.foo = foo



if cascade:

use_cascade = all, delete-orphan

else:

use_cascade = save-update



mapper(A, a, properties={

'bs':relation(B, secondary=atob, cascade=use_cascade)

})

mapper(B, b)



meta.create_all()



a1 = A('a1')

a1.bs.append(B('b1'))

a1.bs.append(B('b2'))

a1.bs.append(B('b3'))



sess = create_session()

sess.save(a1)

sess.flush()



if m2m:

assert atob.count().scalar() == 3

else:

assert b.count(b.c.a_id == None).scalar() == 0



assert b.count().scalar() == 3



if useclear:

sess.clear()



a1 = sess.query(A).get(a1.id)

assert len(a1.bs) == 3

a1.bs = a1.bs[1:]

sess.flush()



if m2m:

assert atob.count().scalar() == 2

else:

assert b.count(b.c.a_id != None).scalar() == 2



if cascade:

assert b.count().scalar() == 2

else:

assert b.count().scalar() == 3



if useclear:

sess.clear()



a1 = sess.query(A).get(a1.id)

assert len(a1.bs) == 2



for m2m in (True, False):

for cascade in (True, False):

for useclear in (True, False):

test(m2m, cascade, useclear)




On Oct 24, 2007, at 4:18 PM, Barry Hart wrote:

I found a problem in SqlAlchemy 0.3.10 this week: slicing a list property 
caused the whole association list to be deleted. For example, suppose I want to 
remove the first 3 items from a list of related items:

my_obj.related = my_obj.related[3:]

When these changes were saved , my_obj.related was empty the next time it 
loaded. This code, however, worked correctly:

for i in range(0, 3):
del my_obj.related[0]

Barry


__
Do You Yahoo!?
Tired of spam? Yahoo! Mail has the best spam protection around 
http://mail.yahoo.com 









__
Do You Yahoo!?
Tired of spam?  Yahoo! Mail has the best spam protection around 
http://mail.yahoo.com 
--~--~-~--~~~---~--~~
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 [EMAIL PROTECTED]
For more options, visit this group at 
http://groups.google.com/group/sqlalchemy?hl=en
-~--~~~~--~~--~--~---

from sqlalchemy import *
from sqlalchemy.ext.assignmapper import assign_mapper

import sqlalchemy
from sqlalchemy.ext import activemapper, sessioncontext

import datetime

engine = None

def create_engine():
global engine
engine = sqlalchemy.create_engine('sqlite://')
#engine = sqlalchemy.create_engine('postgres://postgres:[EMAIL 
PROTECTED]:5432/testdb')
metadata.connect(engine)

def create_session():
return sqlalchemy.create_session(bind_to=engine)

def fuzzy_search(column, value):
Case insensitive search allowing partial string matches.
return func.lower(column).like('%%%s%%' % value.lower())

metadata = activemapper.metadata
create_engine()
session = activemapper.Objectstore(create_session)
activemapper.objectstore = session

g_count = 10
##
# Classes

[sqlalchemy] Re: Problem when slicing a relation list

2007-10-25 Thread Barry Hart
Credit for this one goes to my colleague Greg Hunt. All I did was tell him to 
write a test case. :-)

Barry

- Original Message 
From: Michael Bayer [EMAIL PROTECTED]
To: sqlalchemy@googlegroups.com
Sent: Thursday, October 25, 2007 6:16:24 PM
Subject: [sqlalchemy] Re: Problem when slicing a relation list




On Oct 25, 2007, at 3:58 PM, Barry Hart wrote:

 Here is a test case for the bug. The bug only manifests itself if  
 the transaction that slices the list also modifies all the  
 remaining objects in the list.


hi barry -

nice job again.  we've narrowed down the specific mechanism in this  
in ticket #834.  thanks !







__
Do You Yahoo!?
Tired of spam?  Yahoo! Mail has the best spam protection around 
http://mail.yahoo.com 
--~--~-~--~~~---~--~~
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 [EMAIL PROTECTED]
For more options, visit this group at 
http://groups.google.com/group/sqlalchemy?hl=en
-~--~~~~--~~--~--~---



[sqlalchemy] Declaring a relationship twice - could SqlAlchemy auto-detect problems like this?

2007-10-24 Thread Barry Hart
This subject came up on the TurboGears list and someone suggested I post here.

I noticed a while back that in SqlAlchemy 0.3.x, if you have two mapped classes 
A and B, and you define the same relationship (with a backref) on both classes, 
you won't get an error message but the two relationships interfere with each 
other. For example, you might set the value of the relationship and it won't be 
saved to the database. Would it be possible to detect and flag this as an error 
at model compilation time?

Perhaps there are other model problems like this which could be detected 
automatically. If so, I think it would really flatten the learning curve for 
SqlAlchemy newbies.

Barry





__
Do You Yahoo!?
Tired of spam?  Yahoo! Mail has the best spam protection around 
http://mail.yahoo.com 
--~--~-~--~~~---~--~~
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 [EMAIL PROTECTED]
For more options, visit this group at 
http://groups.google.com/group/sqlalchemy?hl=en
-~--~~~~--~~--~--~---



[sqlalchemy] Problem when slicing a relation list

2007-10-24 Thread Barry Hart
I found a problem in SqlAlchemy 0.3.10 this week: slicing a list
property caused the whole association list to be deleted. For example,
suppose I want to remove the first 3 items from a list of related items:



my_obj.related = my_obj.related[3:]



When these changes were saved , my_obj.related was empty the next time it 
loaded. This code, however, worked correctly:



for i in range(0, 3):

del my_obj.related[0]


Barry


__
Do You Yahoo!?
Tired of spam?  Yahoo! Mail has the best spam protection around 
http://mail.yahoo.com 
--~--~-~--~~~---~--~~
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 [EMAIL PROTECTED]
For more options, visit this group at 
http://groups.google.com/group/sqlalchemy?hl=en
-~--~~~~--~~--~--~---



[sqlalchemy] Re: Declaring a relationship twice - could SqlAlchemy auto-detect problems like this?

2007-10-24 Thread Barry Hart
Here's what I had in mind. This set of mappings compiles without errors in 
0.3.11:

from sqlalchemy import *
from sqlalchemy.orm import *

engine = create_engine('sqlite://')
meta = MetaData(engine)

a = Table('a', meta, Column('id', Integer, primary_key=True))
b = Table('b', meta, Column('id', Integer, primary_key=True), Column('a_id', 
Integer, ForeignKey('a.id')))

class A(object):pass
class B(object):pass
class C(object):pass

mapper(A, a, properties={
'b':relation(B, backref='a')
})
mapper(B, b, properties={
'a':relation(A, backref='b')
})

compile_mappers()

Barry

- Original Message 
From: Michael Bayer [EMAIL PROTECTED]
To: sqlalchemy@googlegroups.com
Sent: Wednesday, October 24, 2007 4:41:46 PM
Subject: [sqlalchemy] Re: Declaring a relationship twice - could SqlAlchemy 
auto-detect problems like this?



On Oct 24, 2007, at 4:16 PM, Barry Hart wrote:

This subject came up on the TurboGears list and someone suggested I post here.

I noticed a while back that in SqlAlchemy 0.3.x, if you have two mapped classes 
A and B, and you define the same relationship (with a backref) on both classes, 
you won't get an error message but the two relationships interfere with each 
other. For example, you might set the value of the relationship and it won't be 
saved to the database. Would it be possible to detect and flag this as an error 
at model compilation time?





hey Barry -


that would be a bug, and I cant reproduce it, at least the bug i think youre 
describing, in neither 0.3 nor 0.4:


from sqlalchemy import *
from sqlalchemy.orm import *


engine = create_engine('sqlite://')
meta = MetaData(engine)


a = Table('a', meta, Column('id', Integer, primary_key=True))
b = Table('b', meta, Column('id', Integer, primary_key=True), Column('a_id', 
Integer, ForeignKey('a.id')))
c = Table('c', meta, Column('id', Integer, primary_key=True), Column('a_id', 
Integer, ForeignKey('a.id')))


class A(object):pass
class B(object):pass
class C(object):pass


mapper(A, a)
mapper(B, b, properties={
'a':relation(A, backref='thebackref')
})
mapper(C, c, properties={
'a':relation(A, backref='thebackref')
})


compile_mappers()


output:


stack trace
sqlalchemy.exceptions.ArgumentError: Backrefs do not match:  backref 
'thebackref' expects to connect to class '__main__.C', but found a backref 
already connected to class '__main__.B'




can you produce a test case ?

















__
Do You Yahoo!?
Tired of spam?  Yahoo! Mail has the best spam protection around 
http://mail.yahoo.com 
--~--~-~--~~~---~--~~
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 [EMAIL PROTECTED]
For more options, visit this group at 
http://groups.google.com/group/sqlalchemy?hl=en
-~--~~~~--~~--~--~---



[sqlalchemy] Re: Declaring a relationship twice - could SqlAlchemy auto-detect problems like this?

2007-10-24 Thread Barry Hart
That is awesome -- thanks. I would've reported it sooner, but I thought maybe I 
was the only one silly enough to make these mistakes in my mappers. :-)

Barry

- Original Message 
From: Michael Bayer [EMAIL PROTECTED]
To: sqlalchemy@googlegroups.com
Sent: Wednesday, October 24, 2007 7:26:39 PM
Subject: [sqlalchemy] Re: Declaring a relationship twice - could SqlAlchemy 
auto-detect problems like this?



On Oct 24, 2007, at 5:02 PM, Barry Hart wrote:

Here's what I had in mind. This set of mappings compiles without errors in 
0.3.11:

from sqlalchemy import *





OK, thanks very much for pointing this one out, as it came across a big heap of 
egregious cruft in the backref code which I graciously flattened (it even 
included the phrase if not x is not None...so embarrassing...).  It also 
raised a few surprises as there were a very small number of unit tests that 
were actually defining conflicting properties in this manner...so when people 
upgrade to 0.4.1 some people might get a few surprises (that alone makes it 
more controversial of a candidate for the 0.3 series, which is in maintenance 
mode).  changeset is rev 3660.














__
Do You Yahoo!?
Tired of spam?  Yahoo! Mail has the best spam protection around 
http://mail.yahoo.com 
--~--~-~--~~~---~--~~
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 [EMAIL PROTECTED]
For more options, visit this group at 
http://groups.google.com/group/sqlalchemy?hl=en
-~--~~~~--~~--~--~---



[sqlalchemy] Re: multiple inserts of sqlalchemy instances?

2007-10-22 Thread Barry Hart
I've written code similar to this with no problems.

Are you using assign_mapper? If so, the save() call is unnecessary.

Do you get this error on the first object or on some subsequent object?

Barry

- Original Message 
From: Lukasz Szybalski [EMAIL PROTECTED]
To: sqlalchemy@googlegroups.com
Sent: Monday, October 22, 2007 3:54:03 PM
Subject: [sqlalchemy] multiple inserts of sqlalchemy instances?



Hello,
I need to save data multiple times in a for loop.

I was trying to do something like this:

You are able to select which group you want to be in: A,B,C,D

for record in userchoice:
new=model.User()
#set some variables
   if record.group=='A':
  #set some more fields
  new.save()
  new.flush()
   elif record.group=='B':
  #set some more fields
  new.save()
  new.flush()

If I do that I get:

File /usr/lib/python2.4/site-packages/sqlalchemy/orm/mapper.py, line
838, in save_obj
raise exceptions.FlushError(New instance %s with identity key %s
conflicts with persistent instance %s %
(mapperutil.instance_str(obj), str(instance_key),
mapperutil.instance_str(existing)))
FlushError: New instance [EMAIL PROTECTED] with identity key (class
'XXX.model.User', (19527, None), None) conflicts with persistent
instance [EMAIL PROTECTED]

Is there a way to do multiple inserts with sqlalchemy?

Lucas


-- 
-- 
Vim auto completion for python
http://lucasmanual.com/mywiki/FrontPage#head-8ce19b13e89893059e126b719bebe4ee32fe103c
TurboGears from start to finish:
http://www.lucasmanual.com/mywiki/TurboGears







__
Do You Yahoo!?
Tired of spam?  Yahoo! Mail has the best spam protection around 
http://mail.yahoo.com 
--~--~-~--~~~---~--~~
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 [EMAIL PROTECTED]
For more options, visit this group at 
http://groups.google.com/group/sqlalchemy?hl=en
-~--~~~~--~~--~--~---



[sqlalchemy] Re: Advice on complicated (?) SQL query

2007-10-20 Thread Barry Hart
Try this for the outer query:

s =
 select([repetition_table.c.grade],(repetition_table.c.rep_number==2)  
(repetition_table.c.card_key.in_(s_inner)) )

Barry

- Original Message 
From: pbienst [EMAIL PROTECTED]
To: sqlalchemy sqlalchemy@googlegroups.com
Sent: Saturday, October 20, 2007 6:55:56 AM
Subject: [sqlalchemy] Re: Advice on complicated (?) SQL query



Thanks! Based on your suggestion, I tried the following:

The inner query goes like this:

repetition_table_2 = repetition_table.alias()
s_inner = select([repetition_table_2.c.card_key],
(repetition_table_2.c.rep_number==5)  \
(repetition_table_2.c.grade==2)).limit(10)
print db_session.execute(s_inner).fetchall()

[(3,), (8,), (16,), (34,), (27,), (42,), (33,), (32,), (37,), (36,)]

Now for the outer query:

s =
 select([repetition_table.c.grade],(repetition_table.c.rep_number==2)  
(repetition_table.c.card_key==s_inner) )
print db_session.execute(s).fetchall()

[(0,)]

I seem to be missing 9 entries...

I also tried the following trivial outer query, which I suppose should
give me back the results of my inner query:

s =
 select([repetition_table.c.card_key],(repetition_table.c.card_key==s_inner) )
print db_session.execute(s).fetchall()

[(3,), (3,), (3,), (3,), (3,), (3,), (3,), (3,)]

Obviously, I'm still missing something...

Peter








__
Do You Yahoo!?
Tired of spam?  Yahoo! Mail has the best spam protection around 
http://mail.yahoo.com 
--~--~-~--~~~---~--~~
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 [EMAIL PROTECTED]
For more options, visit this group at 
http://groups.google.com/group/sqlalchemy?hl=en
-~--~~~~--~~--~--~---



[sqlalchemy] Re: Advice on complicated (?) SQL query

2007-10-18 Thread Barry Hart
I think you want the final SQL query to look something like this:

select * from
card_table
join repetition_table on repetition_table.card_key = card_table.id
where repetition_table.rep_number = 1 and repetition_table.rep_number = 4 and 
card_table.id in
 (select ct2.id from card_table AS ct2
  join repetition_table AS rt2 on rt2.card_key = ct2.id
  AND YOUR CUSTOM CONDITIONS HERE)

The main difference is that I'm doing a join between card and repetition on 
both the outer and inner queries. This lets me constrain the join and avoid 
getting the Cartesian product.

Barry

- Original Message 
From: pbienst [EMAIL PROTECTED]
To: sqlalchemy sqlalchemy@googlegroups.com
Sent: Thursday, October 18, 2007 7:48:36 AM
Subject: [sqlalchemy] Advice on complicated (?) SQL query



Hi,

I have a query which works fine through the ORM, albeit a bit slow, so
I want to drop down to the SQL layer to speed things up. However,
being an SQL novice, I can't seem to figure out how to get it to work.

I have a database containing the history of repetitions with a flash
card program. I have a table containing the flash cards, and a second
table containing the details of all the repetitions for all the
flashcards. I want to look at all cards where repetition 5 obeys
certain criteria, and then for these cards look at repetitions 1 to 4.
Using the ORM, that's easy enough:

repetitions =
db_session.query(Repetition).filter((Repetition.rep_number==5) \
  
(Repetition.grade==2))

for r in repetitions:
for index in range(4):
print index, r.card.repetitions[index].grade

After browsing through the documentation, I have the impression that
using aliases could be the way to go. I tried the following code
(which would only give me repetition 1 instead of 1 to 4, but a loop
is easily made):

repetition_table_2 = repetition_table.alias()

s = select([repetition_table.c.grade],
(repetition_table.c.rep_number==1)  \
 
(repetition_table.c.card_key==repetition_table_2.c.card_key)  \
(repetition_table_2.c.rep_number==5)  \
(repetition_table_2.c.grade==2))

However, this runs forever, so I'm guessing it escapes into the
wonderful world of Cartesian products.

Can anybody help me contruct the proper SQL query or otherwise speed
up the ORM version?

Thanks!

Peter









   

Take the Internet to Go: Yahoo!Go puts the Internet in your pocket: mail, news, 
photos  more. 
http://mobile.yahoo.com/go?refer=1GNXIC
--~--~-~--~~~---~--~~
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 [EMAIL PROTECTED]
For more options, visit this group at 
http://groups.google.com/group/sqlalchemy?hl=en
-~--~~~~--~~--~--~---



[sqlalchemy] Re: Error combining DISTINCT and ORDER BY in an ORM query on PostgreSQL

2007-09-22 Thread Barry Hart
why would you be calling add_column() in this case (besides the PG bug 
workaround) ?

We might call it for certain cases when we're building a report/data screen. 
But 95% of the time we just want normal objects.

slice calls instances() yes.
Thanks, I'll keep instances() in mind as a possible workaround. Currently we 
are just encapsulating the TurboGears @paginate decorator. This is not as 
generic but works reasonable well.

Barry






   

Yahoo! oneSearch: Finally, mobile search 
that gives answers, not web links. 
http://mobile.yahoo.com/mobileweb/onesearch?refer=1ONXIC
--~--~-~--~~~---~--~~
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 [EMAIL PROTECTED]
For more options, visit this group at 
http://groups.google.com/group/sqlalchemy?hl=en
-~--~~~~--~~--~--~---



[sqlalchemy] Re: Error combining DISTINCT and ORDER BY in an ORM query on PostgreSQL

2007-09-17 Thread Barry Hart
I've started using add_column() as needed to work around this. Our application 
tends to have a single, fairly generic filter_sort function for each class. 
Some use cases of this function require add_column() and some don't. From the 
caller's perspective, the filter_sort() function is poorly encapsulated because 
sometimes it sometimes returns objects and sometimes tuples.

It'd be very helpful if the add_column() function took an optional parameter 
'omit_from_results' telling whether the column should be included in the 
results, then our filter_sort() functions could always return objects.

Barry

- Original Message 
From: Barry Hart [EMAIL PROTECTED]
To: sqlalchemy@googlegroups.com
Sent: Thursday, September 6, 2007 1:55:14 PM
Subject: Re: [sqlalchemy] Re: Error combining DISTINCT and ORDER BY in an ORM 
query on PostgreSQL

add_column() worked great, thanks!

Barry

- Original Message 
From: Michael Bayer [EMAIL PROTECTED]
To: sqlalchemy@googlegroups.com
Sent: Thursday, September 6, 2007 10:18:58 AM
Subject: [sqlalchemy] Re: Error combining DISTINCT and ORDER BY in an ORM query 
on PostgreSQL

the two immediate ways to do this with ORM are to use add_column() on Query, or 
to query from a fully constructed select() statement.  The former will have the 
effect of returning tuples containing the instance as well as the additional 
columns, the latter doesnt play as nicely with eager loading.add_column() 
is probably the better
 option here.
On Sep 6, 2007, at 9:09 AM, Barry Hart wrote:

My application has the following data model:

A promotion has 1 mechanic.
A promotion has 0 or more products.

I want to query for a list of promotions containing products whose name matches 
a pattern, and I want the resulting list to be sorted by a property on the 
promotion's mechanic.

This query does not work with SQLAlchemy 0.3.10 on PostgreSQL 8.1. It's because 
of the combination of using DISTINCT and ORDER BY on an table external to the 
main table for the object. (The use of DISTINCT is necessary because joining 
with the products table creates duplicate records. I'm
 showing the query results in a web application with 'n' records per page. 
Without DISTINCT, the ORM mapper will ignore the duplicates, but the record 
count for the query no longer reflects the actual number of objects to be 
returned, making it impractical to page through the data.)

The error is the following:

sqlalchemy.exceptions.SQLError: (ProgrammingError) for SELECT DISTINCT, ORDER BY
 expressions must appear in select list
 'SELECT DISTINCT promo_promotion.mechanic_id AS promo_promotion_mechanic_id, pr
omo_promotion.id AS promo_promotion_id, promo_promotion.name AS promo_promotion_
name \nFROM promo_promotion JOIN prod_product ON promo_promotion.id = prod_produ
ct.promotion_id JOIN promo_mechanic ON promo_mechanic.id = promo_promotion.mecha
nic_id \nWHERE
 lower(prod_product.name) LIKE %(lower)s ORDER BY promo_mechanic.n
ame ASC' {'lower': '%1%'}

The same program works fine on SQLite.

I could write a similar query at the relational level that explicitly includes 
the sort field, but I'd prefer to work at the ORM level. Is there a way to do 
this?

My
 test case is below.

Barry H.

--

from sqlalchemy import *
from sqlalchemy.ext.assignmapper import assign_mapper

import sqlalchemy
from sqlalchemy.ext import activemapper, sessioncontext

engine = None

def create_engine():
global engine
#engine = sqlalchemy.create_engine('sqlite://')
engine = sqlalchemy.create_engine('postgres://postgres:[EMAIL 
PROTECTED]:5432/testdb')
metadata.connect(engine)

def create_session():
return sqlalchemy.create_session(bind_to=engine)

def fuzzy_search(column,
 value):
Case insensitive search allowing partial string matches.
return func.lower(column).like('%%%s%%' % value.lower())

metadata = activemapper.metadata
create_engine()
session = activemapper.Objectstore(create_session)
activemapper.objectstore = session

##
# Classes
##

class Mechanic(object): pass
class Promotion(object):
def __repr__(self):
  return 'Promotion: %s, mechanic=%s' % (self.name, self.mechanic.name)

class Product(object): pass

##
# Tables
##

mechanic_table = Table(
'promo_mechanic', metadata,
Column('id', Integer, primary_key=True),
Column('name', Unicode, unique=True))

promotion_table = Table(
'promo_promotion', metadata,
Column('id', Integer, primary_key=True),
Column('name', Unicode, unique=True),
Column('mechanic_id', Integer, ForeignKey('promo_mechanic.id')))

product_table = Table(
'prod_product', metadata,
Column('id', Integer, primary_key=True), 
Column('name',
 Unicode

[sqlalchemy] Does the SQL construction language support 'INSERT INTO' from a SELECT?

2007-08-16 Thread Barry Hart
I have an insert query in SQL where the records to be inserted are computed 
from a SELECT. Can I build this query in the SqlAlchemy query construction 
language?

INSERT INTO product_current_promotion (promotion_id, product_id)
SELECT promo_promotion.id, promo_promotion_items.product_id
FROM promo_promotion_items, promo_promotion
WHERE promo_promotion.id = promo_promotion_items.promotion_id AND 
promo_promotion.week_id = 3

One thought is to build the SELECT in SqlAlchemy, loop over that in Python and 
insert the records that way, but I'd like to make the database do all the work.

Barry




   

Be a better Heartthrob. Get better relationship answers from someone who knows. 
Yahoo! Answers - Check it out. 
http://answers.yahoo.com/dir/?link=listsid=396545433
--~--~-~--~~~---~--~~
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 [EMAIL PROTECTED]
For more options, visit this group at 
http://groups.google.com/group/sqlalchemy?hl=en
-~--~~~~--~~--~--~---



[sqlalchemy] Re: how to retrieve/update data from/on multiple databases

2007-05-30 Thread Barry Hart
SQLite supports an ATTACH command where multiple databases may be accessed 
seamlessly using a single connection. Does PostgreSQL have something similar? 
If so, then perhaps all you'd need is to add a few extra steps when you connect 
to the database.

Barry

- Original Message 
From: Alchemist [EMAIL PROTECTED]
To: sqlalchemy sqlalchemy@googlegroups.com
Sent: Wednesday, May 30, 2007 9:19:09 AM
Subject: [sqlalchemy] how to retrieve/update data from/on multiple databases


Working with:
Python 2.4
SQLAlchemy 0.3.7
Postgresql 8.2 database servers

I am working in a multidatabase environment.  I need to perform a
query over multiple databases, then manipulate the obtained results
and commit my changes in different tables in different databases.

How can I query from multiple databases?
How can INSERTs/UPDATEs be performed on different tables in different
databases?

Thank you.










  

Park yourself in front of a world of choices in alternative vehicles. Visit the 
Yahoo! Auto Green Center.
http://autos.yahoo.com/green_center/ 
--~--~-~--~~~---~--~~
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 [EMAIL PROTECTED]
For more options, visit this group at 
http://groups.google.com/group/sqlalchemy?hl=en
-~--~~~~--~~--~--~---



[sqlalchemy] Re: Modifying __dict__ doesn't dirty an instance

2007-05-17 Thread Barry Hart
Note that not all object 'fields' are present in the dictionary. For example, 
in our app we may have a SQLAlchemy property '_foo' which is exposed as a 
Python property 'foo'. In this case I believe '_foo' will be in the dictionary, 
but your app should probably be working with 'foo'.

Barry

- Original Message 
From: Michael Bayer [EMAIL PROTECTED]
To: sqlalchemy@googlegroups.com
Sent: Thursday, May 17, 2007 6:55:31 PM
Subject: [sqlalchemy] Re: Modifying __dict__ doesn't dirty an instance



On May 17, 2007, at 5:31 PM, Catherine wrote:


 I noticed an issue that - well, I honestly don't know whether to call
 it a bug or not.  I need to talk it out with somebody who
 understands SQLA better.

 When I retrieve an instance, then alter its attributes by manipulating
 its __dict__, the instance doesn't get dirtied, and the changes
 won't be sent to the database when I flush the session.

a lot more than that breaks, in fact.


 I can work around the problem pretty easily, like this:
 exec(operation, employee.__dict__)
 employee._state['modified'] = True

 That change to ._state normally happens in
 InstrumentedAttribute.__set__ in sqlalchemy/orm/attributes.py (line
 263), which gets called for instance.attribute = newvalue, but not
 for instance.__dict__['attribute'] = newvalue.

well _state is a private attribute which isnt guaranteed to stay that  
way in future versions.


 I'm wondering if I should just sit on this workaround personally, or
 dig into figuring out how to modify SQLA so it will always work for
 __dict__ manipulation.

 So - is direct manipulation of the __dict__ something that SQLA should
 support, or would that fall in the realm of you are getting weird on
 us, you're on your own?  I guess that double-underscore sort of
 implies you're on your own, but __dict__ manipulation doesn't seem
 overly exotic in practice.

the entire method of attribute instrumentation is via property  
objects added to your classes (in fact they are instances of  
InstrumentedAttribute).  the __dict__ is how to get at the instance  
attributes while bypassing the attribute instrumentation entirely.
while the _state hack works right now, and there is an additional  
way it might work which would be to set the mutable_scalars flag to  
True on all the InstrumentedAttribute objects (thereby ignoring the  
_state flag), both of those methods still break all the cascade  
functionality and backref functionality, and will also return the  
wrong list set of deltas in the case of un-lazyloaded attributes that  
get set directly via __dict__.  i.e. the attributes package is  
largely event-based and theres no event listening on __dict__  
directly.  a rewrite would involve replacing the __dict__ of all  
instances with a custom dictionary that does everything, something i  
understand is a Python no-no (and also makes the instrumentation that  
much more opaque, since theres no bypass level anymore).

the cleanest solution of all is just to replace your call to:

myinstance.__dict__

with a proxying dict:

class MyDict(dict):
def __init__(self, obj):
self.obj = obj
def __getitem__(self, key):
return getattr(self.obj, key)
def __setitem__(self, key, value):
setattr(self.obj, key, value)
def keys(self):
return self.obj.__dict__.keys()
# etc ..

MyDict(myinstance)















 

Don't get soaked.  Take a quick peak at the forecast
with the Yahoo! Search weather shortcut.
http://tools.search.yahoo.com/shortcuts/#loc_weather
--~--~-~--~~~---~--~~
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 [EMAIL PROTECTED]
For more options, visit this group at 
http://groups.google.com/group/sqlalchemy?hl=en
-~--~~~~--~~--~--~---



[sqlalchemy] Question about overriding properties

2007-04-26 Thread Barry Hart
In our application's Order table, we have foreign-key fields which reference 
the persons who placed the order, are responsible for fulfilling the order, 
etc. For reporting speed, the Order table holds denormalized copies of contact 
information for these people. Whenever one of the foreign keys is updated, I 
want to update the denormalized information.

I can do this using a Python property, but then I can't use that name in a 
get_by or select_by. I found a nice example in the SQLAlchemy documentation on 
how to create synonyms for existing fields, but I don't think that will help me 
because that would just create a synonym for the ID field, not the object.

Is there a way to satisfy both requirements (updating denormalized info when 
the FK changes, able to query by this property rather than its ID)? I know I 
could use a database trigger, but I would rather stick with pure Python if 
possible.

Thanks,
Barry





__
Do You Yahoo!?
Tired of spam?  Yahoo! Mail has the best spam protection around 
http://mail.yahoo.com 
--~--~-~--~~~---~--~~
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 [EMAIL PROTECTED]
For more options, visit this group at 
http://groups.google.com/group/sqlalchemy?hl=en
-~--~~~~--~~--~--~---