Re: [sqlalchemy] Re: Cascade Deletes

2011-08-07 Thread Stefano Fontanelli



Il 07/08/11 20.08, Aviv Giladi ha scritto:

I see.

Where can I start looking for such an error? What could possibly be
causing this?


I'm sorry but I cannot help you without your code... not a similar code 
but THE code which produce that error.


Regards,
Stefano.


--
Ing. Stefano Fontanelli
Asidev S.r.l.
Via Osteria Bianca, 108/A 50053 Empoli (Firenze)
Tel. (+39) 333 36 53 294   Fax. (+39) 0571 1 979 978
E-mail: s.fontane...@asidev.com   Web: www.asidev.com
Skype: stefanofontanelli

--
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] Need for ImplicitForeignKeyConstraint

2011-08-07 Thread Michael Bayer
Sorry I didn't look closely.  Yes when you subclass FKC overriding 
_set_parent() to perform additional steps is one way to establish on-connect 
details.  Another is to use event.listen(ImplicitForeignKeyConstraint, 
"after_parent_attach"), it would be a little more of the public API.



On Aug 6, 2011, at 2:01 AM, Fayaz Yusuf Khan wrote:

> So IFKC(ImplicitForeignKeyConstraint) should not have inherited FKC? I did it 
> so that it could seamlessly be passed into Table() and __table_args__.
> 
> PS: Everyone, the repo is at https://bitbucket.org/fayaz/implicit
> 
> On Friday, August 05, 2011 07:31:44 PM Michael Bayer wrote:
>> yeah wow I just saw that.Can you use table.add_constraint(fk) instead
>> of _set_parent() ?
>> 
>> On Aug 5, 2011, at 1:34 AM, Fayaz Yusuf Khan wrote:
>>> So I had been working on this tiny project now and then. And here's the
>>> poc. http://paste.pound-python.org/show/10578/
>>> I think I'm somewhat misusing the _set_parent() here though.
>>> 
>>> On Sunday, July 24, 2011 06:52:45 PM Michael Bayer wrote:
 On Jul 24, 2011, at 8:39 AM, Fayaz Yusuf Khan wrote:
> The problem with using different mixins is that you lose out on a lot
> of code reusability. In my case, I have a 'user' column that appears
> in almost all table declarations. To have a separate mixin class for
> each joint-table inheritance would destroy the purpose of having a
> mixin altogether.
 
 In your example you can simply use CMixin and TMixin separately instead
 of inheriting them from one another, then apply CMixin and TMixin
 directly to C individually.That makes more sense here since for
 every class X which you want to have "user", you'd apply CMixin
 explicitly. The more I look at this the more it seems completely
 correct to me.  Mixins and declarative do a lot , and sticking to
 Python's regular rules for inheritance is what makes them great.
 
> Perhaps, there should be a shorthand for implicitly creating columns
> along with foreign key constraints?
> 
> So something like
> 
>  ImplicitForeignKeyConstraint(
> 
>  ['user', 'timestamp'],
>  ['Timeline.user', 'Timeline.timestamp'], primary_key=True)
> 
> should lead to the creation of
> 
>  Column('user', String, primary_key=True),
>  Column('timestamp',Integer, autoincrement=False, primary_key=True),
>  ForeignKeyConstraint(
> 
>  ['user', 'timestamp'],
>  ['Timeline.user', 'Timeline.timestamp'])
 
 Not something for core but certainly something you could provide
 yourself (use append_column()).  SQLA's APIs try to remain explicit
 about things leaving "implicit helper" layers as an external task
 (hence relationship + ForeignKey, as opposed to the "all in one" demo I
 did at http://techspot.zzzeek.org/2011/05/17/magic-a-new-orm/ , etc)
> 
> -- 
> Fayaz Yusuf Khan
> Cloud developer and designer
> Dexetra SS, Kochi, India
> fayaz.yusuf.khan_AT_gmail_DOT_com
> fayaz_AT_dexetra_DOT_com
> +91-9746-830-823

-- 
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] Fwd: [Gnukhata-devel] not able to put & in account name field

2011-08-07 Thread Michael Bayer
There's not much information there which says much about the ultimate issue.
Suffice to say SQLAlchemy itself has no issue with psycopg2 and the string "A & 
B", attached is a demonstration inserting, querying, updating this value and 
similar in many ways.   Only with a specific test case that demonstrates the 
issue can anyone on the list here be of any help.

from sqlalchemy import *
from sqlalchemy.orm import *
from sqlalchemy.ext.declarative import declarative_base

Base = declarative_base()
e = create_engine("postgresql://scott:tiger@localhost/test", echo=True)
class A(Base):
__tablename__ = 'a'
id = Column(Integer, primary_key=True)
data = Column(String(50))

Base.metadata.drop_all(e)
Base.metadata.create_all(e)
s = Session(e)
s.add(A(data="A & B"))
s.commit()

assert s.query(A.data).all() == [("A & B",)]
assert s.query(A.data).filter_by(data="A & B").all() == [("A & B",)]

a2 = A(data="some new data")
s.add(a2)
s.commit()
a2.data = "B & C"
s.commit()

assert [a.data for a in s.query(A).order_by(A.id).all()] == ["A & B", "B & C"]


On Aug 7, 2011, at 2:19 PM, Krishnakant Mane wrote:

> 
> I really don't think that's the issue.
> no eval is used.
> Secondly it did work through psycopg2 directly with postgresql
> If some would have the kindness to look at the code I am paisting it here.
> Sorry for making it long, it contains comments to explain the situation.
> 
> def xmlrpc_setAccount(self,queryParams,client_id):
> '''
> Purpose : Adds new account i.e row to the account table in the 
> database
> Parameters : It expects a list of queryParams which 
> contains[suggestedcode(datatype:integer),groupcode(datatype:integer),subgroupcode(datatype:integer),accountname(datatype:text)openingbalance(datatype:numeric),openingdate(datatype:timestamp),balance(datatype:numeric)]
> Returns : Boolean
> Description : Querys the account table and add new row.
> To add account first time check wether max of accountcode if 
> there is nothing in that coloumn maxAccountcode will increament by 1 and if 
> there is max value then go to else condition and increament by 1
> It takes  which is a foreign key from the group table,account 
> name which is name of the account, and openingbalance which is previous 
> financial year balance amount and opening date i.e when a new account is 
> added (it always takes the todays date), balance is the balance amount 
> remaining with that account.
> When record entered successfully  it returns True else returns 
> False.
> '''
> connection = dbconnect.engines[client_id].connect()
> Session = dbconnect.session(bind=connection)
> account_creation_date = str(strftime("%Y-%m-%d %H:%M:%S"))
> if queryParams[5] != 0:
> 
> Session.add(dbconnect.Account(queryParams[5],queryParams[0],queryParams[1],queryParams[2],queryParams[3],account_creation_date,queryParams[4]))
> else:
> maxAccountCode = 0
> maxAccountCode = 
> Session.query(func.count(dbconnect.Account.accountcode)).scalar()
> if maxAccountCode == None:
> maxAccountCode = 0
> maxAccountCode = int(maxAccountCode) + 1
> else:
> maxAccountCode = int(maxAccountCode) + 1
> 
> 
> Session.add(dbconnect.Account(maxAccountCode,queryParams[0],queryParams[1],queryParams[2],queryParams[3],account_creation_date,queryParams[4]))
> Session.commit()
> Session.close()
> 
> 
> Mind you, it is an  xmlrpc call.
> and the constructor of the table instance takes all the parameter hence the 
> way in which session.add is coded.
> Happy hacking.
> Krishnakant.
> 
> 
> On 07/08/11 21:11, Michael Bayer wrote:
>> 
>> 
>> On Aug 7, 2011, at 8:19 AM, Krishnakant Mane wrote:
>> 
>>> Hello all.
>>> This might be interesting.
>>> I don't know if we are doing some thing wrong.
>>> We use session.query on a table and for adding records we use the orm.
>>> But look at the forwarded email, I don't know what's wrong.
>>> happy hacking.
>> 
>> you'd need to know what happens when someone enters "A & B".  If for example 
>> you're calling eval() on that or something, "&" is a Python operator.   
>> 
>> 
>> 
>>> Krishnakant.
>>> 
>>> 
>>> 
>>> 
>>>  Original Message 
>>> Subject:[Gnukhata-devel] not able to put & in account name field
>>> Date:   Sun, 7 Aug 2011 17:35:51 +0530
>>> From:   ankita shanbhag 
>>> To: gnukhata dev 
>>> 
>>> Hello All,
>>> 
>>> This may sound silly but entering & in account field eg "A & B" can
>>> cause difficulty in retrival of that account from database.
>>> 
>>> I tried to query the Account table using postgres and its able to
>>> fetch record properly.
>>> 
>>> I feel its a problem of SqlAlchemy.I am afraid if we want '&' then we
>>> have to look through rpc_account.py specially getAccount!!
>>> 
>>> Thanking you.
>>> 

Re: [sqlalchemy] Fwd: [Gnukhata-devel] not able to put & in account name field

2011-08-07 Thread Krishnakant Mane


I really don't think that's the issue.
no eval is used.
Secondly it did work through psycopg2 directly with postgresql
If some would have the kindness to look at the code I am paisting it here.
Sorry for making it long, it contains comments to explain the situation.

def xmlrpc_setAccount(self,queryParams,client_id):
'''
Purpose : Adds new account i.e row to the account table in the 
database
Parameters : It expects a list of queryParams which 
contains[suggestedcode(datatype:integer),groupcode(datatype:integer),subgroupcode(datatype:integer),accountname(datatype:text)openingbalance(datatype:numeric),openingdate(datatype:timestamp),balance(datatype:numeric)]

Returns : Boolean
Description : Querys the account table and add new row.
To add account first time check wether max of accountcode 
if there is nothing in that coloumn maxAccountcode will increament by 1 
and if there is max value then go to else condition and increament by 1
It takes  which is a foreign key from the group 
table,account name which is name of the account, and openingbalance 
which is previous financial year balance amount and opening date i.e 
when a new account is added (it always takes the todays date), balance 
is the balance amount remaining with that account.
When record entered successfully  it returns True else 
returns False.

'''
connection = dbconnect.engines[client_id].connect()
Session = dbconnect.session(bind=connection)
account_creation_date = str(strftime("%Y-%m-%d %H:%M:%S"))
if queryParams[5] != 0:

Session.add(dbconnect.Account(queryParams[5],queryParams[0],queryParams[1],queryParams[2],queryParams[3],account_creation_date,queryParams[4]))

else:
maxAccountCode = 0
maxAccountCode = 
Session.query(func.count(dbconnect.Account.accountcode)).scalar()

if maxAccountCode == None:
maxAccountCode = 0
maxAccountCode = int(maxAccountCode) + 1
else:
maxAccountCode = int(maxAccountCode) + 1


Session.add(dbconnect.Account(maxAccountCode,queryParams[0],queryParams[1],queryParams[2],queryParams[3],account_creation_date,queryParams[4]))

Session.commit()
Session.close()


Mind you, it is an  xmlrpc call.
and the constructor of the table instance takes all the parameter hence 
the way in which session.add is coded.

Happy hacking.
Krishnakant.


On 07/08/11 21:11, Michael Bayer wrote:


On Aug 7, 2011, at 8:19 AM, Krishnakant Mane wrote:


Hello all.
This might be interesting.
I don't know if we are doing some thing wrong.
We use session.query on a table and for adding records we use the orm.
But look at the forwarded email, I don't know what's wrong.
happy hacking.


you'd need to know what happens when someone enters "A & B".  If for 
example you're calling eval() on that or something, "&" is a Python 
operator.





Krishnakant.




 Original Message 
Subject:[Gnukhata-devel] not able to put & in account name field
Date:   Sun, 7 Aug 2011 17:35:51 +0530
From:   ankita shanbhag 
To: gnukhata dev 



Hello All,

This may sound silly but entering&  in account field eg "A&  B" can
cause difficulty in retrival of that account from database.

I tried to query the Account table using postgres and its able to
fetch record properly.

I feel its a problem of SqlAlchemy.I am afraid if we want '&' then we
have to look through rpc_account.py specially getAccount!!

Thanking you.


--
"FOSS is not just about coding..its more of collaborative project management"


ankita shanbhag
___
Gnukhata-devel mailing list
gnukhata-de...@cis-india.org
http://lists.cis-india.org/mailman/listinfo/gnukhata-devel


--
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.


--
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: Cascade Deletes

2011-08-07 Thread Aviv Giladi
I see.

Where can I start looking for such an error? What could possibly be
causing this?

On Aug 7, 6:51 am, Stefano Fontanelli  wrote:
> Il 07/08/11 00.35, Aviv Giladi ha scritto:
>
> > Everything works great when I create and assign all 3 subratings to
> > the rating object before I add it to the session.
> > However, I need to be able to create a Rating that only has 1 or 2
> > subratings, and the other subratings absent.
> > When I do that, SQLAlchemy tells me:
> > InterfaceError: (InterfaceError) Error binding parameter 0 - probably
> > unsupported type. u'SELECT SubRating2.id AS subrating2_id \nFROM
> > subratings2 \nWHERE subrating2.id = ?' (,)
>
> > The above error is when I set Ratings's subrating1 and subrating3, but
> > not subrating2.
> > How do I avoid this error?
>
> I think the error is somewhere else in your application code.
> The model works as you can check in the attached test.
>
> Regards,
> Stefano.
>
> --
> Ing. Stefano Fontanelli
> Asidev S.r.l.
> Via Osteria Bianca, 108/A 50053 Empoli (Firenze)
> Tel. (+39) 333 36 53 294   Fax. (+39) 0571 1 979 978
> E-mail: s.fontane...@asidev.com   Web:www.asidev.com
> Skype: stefanofontanelli
>
>  test.py
> 7KViewDownload

-- 
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] Fwd: [Gnukhata-devel] not able to put & in account name field

2011-08-07 Thread Michael Bayer

On Aug 7, 2011, at 8:19 AM, Krishnakant Mane wrote:

> Hello all.
> This might be interesting.
> I don't know if we are doing some thing wrong.
> We use session.query on a table and for adding records we use the orm.
> But look at the forwarded email, I don't know what's wrong.
> happy hacking.

you'd need to know what happens when someone enters "A & B".  If for example 
you're calling eval() on that or something, "&" is a Python operator.   



> Krishnakant.
> 
> 
> 
> 
>  Original Message 
> Subject:  [Gnukhata-devel] not able to put & in account name field
> Date: Sun, 7 Aug 2011 17:35:51 +0530
> From: ankita shanbhag 
> To:   gnukhata dev 
> 
> Hello All,
> 
> This may sound silly but entering & in account field eg "A & B" can
> cause difficulty in retrival of that account from database.
> 
> I tried to query the Account table using postgres and its able to
> fetch record properly.
> 
> I feel its a problem of SqlAlchemy.I am afraid if we want '&' then we
> have to look through rpc_account.py specially getAccount!!
> 
> Thanking you.
> 
> 
> -- 
> "FOSS is not just about coding..its more of collaborative project management"
> 
> 
> ankita shanbhag
> ___
> Gnukhata-devel mailing list
> gnukhata-de...@cis-india.org
> http://lists.cis-india.org/mailman/listinfo/gnukhata-devel
> 
> 
> -- 
> 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] Two bugs or different behaviors between 0.6 and 0.7

2011-08-07 Thread Michael Bayer

On Aug 7, 2011, at 4:54 AM, Arturo Sevilla wrote:

> Hi,
> 
> I think I have detected two bugs for PostgreSQL databases. I don't think is a 
> different behavior between 0.6 and 0.7 as there is no problem with sqlite.
> 
> In the following code I have a very simple model, which contains a helper 
> "pre-process" list class, which just transforms strings into the correct 
> model object. Very similar to @collection.converter, however it works for 
> append and extend. It works without errors (obviously w/o MutableComposite) 
> in 0.6 and sqlite in 0.7. But the strange part is that it follows different 
> behavior depending on when you add the parent object to the session: if you 
> add it after creating the "company" (just like I put it here), then it will 
> not insert the "data" object (see the produced log, if you change it to the 
> sqlite engine it will work); but if you add and commit it, before and after 
> the append operation it will fail with an IntegrityError in both sqlite and 
> postgresql (this is why I doubt if it is a different behavior or not).
> 
> Either way I think that adding the object, committing it, then adding it 
> again, and committing it, although very wasteful, should behave without 
> error, specially for occasions when you don't know how your object has been 
> handled in relation with your database.
> 
> The other bug is just for PostgreSQL and can be reproduced by uncommenting 
> the "metadata.create_all()" line of code. It appears that is trying to create 
> the data table before company. It doesn't matter in which order are defined 
> the same error is raised.

Ran your test, and here are the facts I have about what is below, which appear 
to disagree with your observations:

1. the error I am seeing, equally on PG and SQLite, is:

sqlalchemy.exc.IntegrityError: (IntegrityError) null value in column "company" 
violates not-null constraint
 'INSERT INTO data (data, company) VALUES (%(data)s, %(company)s) RETURNING 
data.id' {'company': None, 'data': 'adata'}

There is no other error I can produce, and it's only with the add().  The 
reason is simple, which is that your custom list is preventing instrumentation 
from working correctly.  Without the explicit add(), the "Data" element never 
makes it into the Session.  With the add(), it makes it in the session but no 
history event is apparent allowing the sync from company->data.

2. mutable composite, the point, etc. has nothing to do with anything here.  
Removed it all for simplicity, makes no difference.

3. It would be *extremely* unusual/unexplainable if create_all() were actually 
failing to see the ForeignKey applied to "data" establishing it as dependent on 
"company".   That cannot be reproduced at all here.

4. I make extremely scant usage of the @collection decorators, as they are 
giving you a window into an already intricate system which has not seen much 
customization in practice.  The thing you're calling down towards needs to be 
instrumented which is not the case here, its just plain list.append() - so I 
moved it to _append() which is the one that gets the instrumentation - then 
@internally_instrumented to keep it from instrumenting append().I think if 
the collection approach were used fully, *maybe* it could do the use case here 
fully, i.e. if __iter__ and friends were also implemented to produce the "view 
of strings".

5. The use case of "I'd like a collection that shows off just a string 
attribute" is extremely doable via association proxy, which is designed exactly 
for this kind of thing.   The assoc_proxy.py example attached, in just a few 
lines of code, produces a pure view of "a", "b", "c", "d", etc. with the "data" 
suffix as well as the existence of Data() entirely concealed.  
Assignment/set/remove all work equally well.  Documentation for association 
proxy was just rewritten two days ago.






from sqlalchemy import create_engine, MetaData, Table, Column, Integer, \
   String, ForeignKey
from sqlalchemy.orm import mapper, relationship, sessionmaker
from sqlalchemy.orm import collections

engine = create_engine('postgresql://scott:tiger@localhost/test', echo=True)
metadata = MetaData()

company = Table(
'company',
metadata,
Column('id', Integer, primary_key=True),
Column('name', String, nullable=False),
sqlite_autoincrement=True
)

data = Table(
'data',
metadata,
Column('id', Integer, primary_key=True),
Column('data', String, nullable=False),
Column('company', Integer, ForeignKey('company.id'), nullable=False),
sqlite_autoincrement=True
)

metadata.bind = engine
metadata.drop_all()
metadata.create_all()

class PreprocessList(list):
def __init__(self, items=None):
if items is None:
super(PreprocessList, self).__init__()
else:
super(PreprocessList, self).__init__(
[self.preprocess(item) for item in items]
)

def preprocess(self, value):
r

Re: [sqlalchemy] Re: Cascade Deletes

2011-08-07 Thread Stefano Fontanelli

Il 07/08/11 00.35, Aviv Giladi ha scritto:

Everything works great when I create and assign all 3 subratings to
the rating object before I add it to the session.
However, I need to be able to create a Rating that only has 1 or 2
subratings, and the other subratings absent.
When I do that, SQLAlchemy tells me:
InterfaceError: (InterfaceError) Error binding parameter 0 - probably
unsupported type. u'SELECT SubRating2.id AS subrating2_id \nFROM
subratings2 \nWHERE subrating2.id = ?' (,)

The above error is when I set Ratings's subrating1 and subrating3, but
not subrating2.
How do I avoid this error?



I think the error is somewhere else in your application code.
The model works as you can check in the attached test.

Regards,
Stefano.


--
Ing. Stefano Fontanelli
Asidev S.r.l.
Via Osteria Bianca, 108/A 50053 Empoli (Firenze)
Tel. (+39) 333 36 53 294   Fax. (+39) 0571 1 979 978
E-mail: s.fontane...@asidev.com   Web: www.asidev.com
Skype: stefanofontanelli

--
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.


from sqlalchemy import *
from sqlalchemy.orm import backref
from sqlalchemy.orm import relationship
from sqlalchemy.ext.declarative import declarative_base


Base = declarative_base()

class SubRating1(Base):
__tablename__ = 'subratings1'
id = Column(Integer, primary_key=True)
name = Column(Unicode(32), unique=True)


class SubRating2(Base):
__tablename__ = 'subratings2'
id = Column(Integer, primary_key=True)
name = Column(Unicode(32), unique=True)


class SubRating3(Base):
__tablename__ = 'subratings3'
id = Column(Integer, primary_key=True)
name = Column(Unicode(32), unique=True)


class Rating(Base):
__tablename__ = 'ratings'
id = Column(Integer, primary_key=True)
name = Column(Unicode(32), unique=True)

subrating1_id = Column(Integer, ForeignKey('subratings1.id'))
subrating1 = relationship("SubRating1",
  backref=backref("rating", 
  cascade="all, delete-orphan",
  uselist=False))

subrating2_id = Column(Integer, ForeignKey('subratings2.id'))
subrating2 = relationship("SubRating2",
  backref=backref("rating", 
  cascade="all, delete-orphan",
  uselist=False))

subrating3_id = Column(Integer, ForeignKey('subratings3.id'))
subrating3 = relationship("SubRating3", 
  backref=backref("rating",
  cascade="all, delete-orphan",
  uselist=False))


if __name__ == '__main__':

from sqlalchemy import create_engine
from sqlalchemy.orm import scoped_session
from sqlalchemy.orm import sessionmaker

engine = create_engine('sqlite:///', echo=True)
Base.metadata.create_all(engine)
session = scoped_session(sessionmaker())
session.configure(bind=engine)

rating = Rating(name=u'My First Rating')
session.add(rating)
session.flush()

assert rating.subrating1 == None
assert rating.subrating2 == None
assert rating.subrating3 == None

session.commit()

subrating1 = SubRating1(name=u'My First SubRating1')
rating.subrating1 = subrating1

assert rating.subrating1 == subrating1
assert rating.subrating2 == None
assert rating.subrating3 == None
assert subrating1.rating == rating

session.flush()
session.commit()

subrating3 = SubRating3(name=u'My First SubRating3')
rating.subrating3 = subrating3

assert rating.subrating1 == subrating1
assert subrating1.rating == rating
assert rating.subrating2 == None
assert rating.subrating3 == subrating3
assert subrating3.rating == rating

session.flush()
session.commit()



"""
$ python test.py 
2011-08-07 15:48:54,697 INFO sqlalchemy.engine.base.Engine PRAGMA table_info("subratings3")
2011-08-07 15:48:54,697 INFO sqlalchemy.engine.base.Engine ()
2011-08-07 15:48:54,698 INFO sqlalchemy.engine.base.Engine PRAGMA table_info("subratings2")
2011-08-07 15:48:54,698 INFO sqlalchemy.engine.base.Engine ()
2011-08-07 15:48:54,698 INFO sqlalchemy.engine.base.Engine PRAGMA table_info("subratings1")
2011-08-07 15:48:54,698 INFO sqlalchemy.engine.base.Engine ()
2011-08-07 15:48:54,698 INFO sqlalchemy.engine.base.Engine PRAGMA table_info("ratings")
2011-08-07 15:48:54,698 INFO sqlalchemy.engine.base.Engine ()
2011-08-07 15:48:54,699 INFO sqlalchemy.engine.base.Engine 
CREATE TABLE subratings3 (
	id INTEGER NOT NULL, 
	name VARCHAR(32), 
	PRIMARY KEY (id), 
	UNIQUE (name)
)


2011-08-07 15:48:

[sqlalchemy] Fwd: [Gnukhata-devel] not able to put & in account name field

2011-08-07 Thread Krishnakant Mane

Hello all.
This might be interesting.
I don't know if we are doing some thing wrong.
We use session.query on a table and for adding records we use the orm.
But look at the forwarded email, I don't know what's wrong.
happy hacking.
Krishnakant.




 Original Message 
Subject:[Gnukhata-devel] not able to put & in account name field
Date:   Sun, 7 Aug 2011 17:35:51 +0530
From:   ankita shanbhag 
To: gnukhata dev 



Hello All,

This may sound silly but entering&  in account field eg "A&  B" can
cause difficulty in retrival of that account from database.

I tried to query the Account table using postgres and its able to
fetch record properly.

I feel its a problem of SqlAlchemy.I am afraid if we want '&' then we
have to look through rpc_account.py specially getAccount!!

Thanking you.


--
"FOSS is not just about coding..its more of collaborative project management"


ankita shanbhag
___
Gnukhata-devel mailing list
gnukhata-de...@cis-india.org
http://lists.cis-india.org/mailman/listinfo/gnukhata-devel


--
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] Two bugs or different behaviors between 0.6 and 0.7

2011-08-07 Thread Arturo Sevilla
Hi,

I think I have detected two bugs for PostgreSQL databases. I don't think is 
a different behavior between 0.6 and 0.7 as there is no problem with sqlite.

In the following code I have a very simple model, which contains a helper 
"pre-process" list class, which just transforms strings into the correct 
model object. Very similar to @collection.converter, however it works for 
append and extend. It works without errors (obviously w/o MutableComposite) 
in 0.6 and sqlite in 0.7. But the strange part is that it follows different 
behavior depending on when you add the parent object to the session: if you 
add it after creating the "company" (just like I put it here), then it will 
not insert the "data" object (see the produced log, if you change it to the 
sqlite engine it will work); but if you add and commit it, before and after 
the append operation it will fail with an IntegrityError in both sqlite and 
postgresql (this is why I doubt if it is a different behavior or not).

Either way I think that adding the object, committing it, then adding it 
again, and committing it, although very wasteful, should behave without 
error, specially for occasions when you don't know how your object has been 
handled in relation with your database.

The other bug is just for PostgreSQL and can be reproduced by uncommenting 
the "metadata.create_all()" line of code. It appears that is trying to 
create the data table before company. It doesn't matter in which order are 
defined the same error is raised.

Thanks

from sqlalchemy import create_engine, MetaData, Table, Column, Integer, \
   String, ForeignKey
from sqlalchemy.orm.collections import collection
from sqlalchemy.orm import mapper, relationship, sessionmaker, composite
from sqlalchemy.ext.mutable import MutableComposite

engine = create_engine('postgresql://user:password@localhost:5432/db', 
echo=True)
#engine = create_engine('sqlite:///:memory:', echo=True)
metadata = MetaData()

company = Table(
'company',
metadata,
Column('id', Integer, primary_key=True),
Column('name', String, nullable=False),
Column('x', Integer, nullable=False),
Column('y', Integer, nullable=False),
sqlite_autoincrement=True
)

data = Table(
'data',
metadata,
Column('id', Integer, primary_key=True),
Column('data', String, nullable=False),
Column('company', Integer, ForeignKey('company.id'), nullable=False),
sqlite_autoincrement=True
)

metadata.bind = engine
#metadata.drop_all()
company.create()
data.create()
#metadata.create_all()


class PreprocessList(list):
def __init__(self, items=None):
if items is None:
super(PreprocessList, self).__init__()
else:
super(PreprocessList, self).__init__(
[self.preprocess(item) for item in items]
)

def preprocess(self, value):
return value

def __setitem__(self, key, value):
value = self.preprocess(value)
super(PreprocessList, self).__setitem__(key, value)

@collection.internally_instrumented
def append(self, value):
value = self.preprocess(value)
super(PreprocessList, self).append(value)

@collection.internally_instrumented
def extend(self, items):
for item in items:
self.append(item)

class AppenderList(PreprocessList):
def preprocess(self, value):
v = Data()
v.data = value + 'data'
return v

def __getitem__(self, key):
value = super(AppenderList, self).__getitem__(key)
return value.data

class Data(object):
pass

class Company(object):
pass

class Point(MutableComposite):
def __init__(self, x, y):
self.x = x
self.y = y

def __setattr__(self, key, value):
"Intercept set events"

# set the attribute
object.__setattr__(self, key, value)

# alert all parents to the change
self.changed()

def __composite_values__(self):
return self.x, self.y

def __eq__(self, other):
return isinstance(other, Point) and \
other.x == self.x and \
other.y == self.y

def __ne__(self, other):
return not self.__eq__(other)

mapper(Company, company, properties={
'id': company.c.id,
'name': company.c.name,
'data': relationship(
Data,
collection_class=AppenderList
),
'point': composite(Point, company.c.x, company.c.y)
})
mapper(Data, data)
session = sessionmaker(bind=engine)()

# CHANGE BELOW

c = Company()
c.name = 'company 1'
c.data = AppenderList()
c.point = Point(3, 5)
session.add(c)
session.commit()

c.data.append('a')

#session.add(c)
session.commit()

metadata.drop_all()

print 'ok'


-- 
You received this message because you are subscribed to the Google Groups 
"sqlalchemy" group.
To view this discussion on the web visit 
https://groups.google.com/d/msg/sqlalchemy/-/9vkKkIpe9aEJ.
To post to this group, send em