[sqlalchemy] Re: Create tables with metadata

2008-12-11 Thread jarrod.ches...@gmail.com

Doesn't get created in the database.
How do i add columns to tables already defined in the database after i
have reflected them into the metadata



On Dec 12, 12:59 am, Empty  wrote:
> Hi,
>
> On Thu, Dec 11, 2008 at 8:12 AM, jarrod.ches...@gmail.com <
>
>
>
> jarrod.ches...@gmail.com> wrote:
>
> > Hi
> > I've scoured the documentation and i can't find any info on how to
> > create a column using metadata.
>
> > from sqlalchemy import engine
> > from sqlalchemy import schema
> > from sqlalchemy import types
>
> > _config_dbengine = engine.create_engine('sqlite:tmp/db')
> > _config_metadata = schema.MetaData(_config_dbengine, reflect=True)
> > table = _config_metadata.tables['table_name']
> > table.append_column(schema.Column('id', types.Integer,
> > primary_key=True, autoincrement=True))
>
> > This is the steps i'm using but the column doesn't get created.
>
> Doesn't get created where?  In the database?  That's not going to happen.
>  Are you saying it's not included as part of the table definition?
>
> Michael
--~--~-~--~~~---~--~~
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] Unstable results using lambda function

2008-12-11 Thread channing

I have a weird problem: Two identical functions, created using a
lambda from the same issuing identical SQL, return two different
answers. I'm embarrassed to say this, but it looks stochastic. I'm
running 0.4.2p3 with Python 2.5.2 and Ipython 0.8.1.

First, the guided tour. I'm using a lambda function to make new,
single-argument versions of a multi-argument function:

def _parse_fun(fun, fun_args=None):
return lambda x: fun.__call__(x,fun_args)

Now I have another function that does some filtering and counting:

def n_classresps(unit,class_name):
return query(ClassResponse).filter_by(unit=unit)\
.filter_by(class_name=class_name).count()

And I use _parse_fun to set the value of the class_name argument:

yf = _parse_fun(n_classresps,'noise')

The problem comes when I make multiple instances:

foo = _parse_fun(n_classresps,'noise')

Now calling yf and foo returns different results: yf(qunits[0])
returns 0, while foo(qunits[0]) returns 3.

I've included a model below that reproduces my problem. The server is
a test server that only I'm using, so the database isn't changing. I
have this saved to a file, and I run it in IPython 0.8.1 using the run
command. After running, if I define

foo = _parse_fun(n_classresps,'zf song')

And foo(qunits[0]) gives me 3. Then I define

bar = _parse_fun(n_classresps,'zf song')

Now bar(qunits[0]) gives me 0. See where this is going?

The version in my full app reliably gives me the wrong answer, despite
issuing the right SQL. I've set engine.echo=True and enabled query
logging on the MySQL server, and the SQL is all fine. Running the SQL
with engine.execute gives the right answer, as does running the SQL
from a command-line tool.

Any ideas as to what could be causing this? I am at a complete loss.

Thanks,

Channing

--- Code follows -

from sqlalchemy import MetaData, Table, Column, ForeignKey,
create_engine, Integer, String, select
from sqlalchemy.orm import mapper, relation, ColumnProperty,
scoped_session, sessionmaker
from sqlalchemy.databases.mysql import MSEnum

'''
Set up engine
'''
engine = create_engine(*)
Session = scoped_session(sessionmaker(autoflush=True,
transactional=True,
  bind=engine))
metadata = MetaData(engine)
query = Session.query

def _parse_fun(fun,fun_args=None):
return lambda x: fun.__call__(x,fun_args)

def n_classresps(unit,class_name):
return query(ClassResponse)\
.filter_by(unit=unit)\
.filter_by(class_name=class_name)\
.count()

class Presentation(object):
pass

class Response(object):
pass

class Unit(object):
pass

class ClassPresentation(Presentation):
pass

class ClassResponse(Response):
pass

presentations = Table('presentations', metadata,
  Column('presentation_id', Integer,
 primary_key=True, nullable=False),
  Column('block_id', Integer, nullable=False),
  Column('type', MSEnum
('single','repeated','class'),
 nullable=False)
  )

responses = Table('responses', metadata,
  Column('response_id', Integer,
 primary_key=True, nullable=False),
  Column('unit_id', Integer,
 ForeignKey('units.unit_id'),
 nullable=False),
  Column(u'presentation_id', Integer,
 ForeignKey('presentations.presentation_id'),
 nullable=False)
  )

class_presentations = Table('class_presentations', metadata,
Column('presentation_id', Integer,
   ForeignKey
('presentations.presentation_id'),
   primary_key=True, nullable=False),
Column('class_name', String,
nullable=False)
)

units = Table('units', metadata,
  Column('unit_id', Integer, primary_key=True,
 nullable=False),
  Column('recsite_id', Integer, nullable=False),
  Column('type', MSEnum('extracellular','intracellular'),
 nullable=False)
  )

mapper(Presentation,presentations,
   polymorphic_on=presentations.c.type,
   polymorphic_identity='presentation')

rmapper = mapper(Response,responses.join(presentations),
 polymorphic_on=presentations.c.type,
 polymorphic_identity='response',
 properties={'unit':relation(Unit)})

mapper(Unit,units)

mapper(ClassPresentation,class_presentations,
   inherits=Presentation,
   polymorphic_identity='class')

mapper(ClassResponse, inherits=rmapper,
   polymorphic_identity='class',
   properties={'class_name':ColumnProperty(select
([class_presentations.c.class_name],

responses.c.presentation_id==c

[sqlalchemy] Unstable results using lambda function

2008-12-11 Thread channing

I have a weird problem: Two identical functions, created using a
lambda from the same issuing identical SQL, return two different
answers. I'm embarrassed to say this, but it looks stochastic. I'm
running 0.4.2p3 with Python 2.5.2 and Ipython 0.8.1.

First, the guided tour. I'm using a lambda function to make new,
single-argument versions of a multi-argument function:

def _parse_fun(fun, fun_args=None):
return lambda x: fun.__call__(x,fun_args)

Now I have another function that does some filtering and counting:

def n_classresps(unit,class_name):
return query(ClassResponse).filter_by(unit=unit)\
.filter_by(class_name=class_name).count()

And I use _parse_fun to set the value of the class_name argument:

yf = _parse_fun(n_classresps,'noise')

The problem comes when I make multiple instances:

foo = _parse_fun(n_classresps,'noise')

Now calling yf and foo returns different results: yf(qunits[0])
returns 0, while foo(qunits[0]) returns 3.

I've included a model below that reproduces my problem. The server is
a test server that only I'm using, so the database isn't changing. I
have this saved to a file, and I run it in IPython 0.8.1 using the run
command. After running, if I define

foo = _parse_fun(n_classresps,'zf song')

And foo(qunits[0]) gives me 3. Then I define

bar = _parse_fun(n_classresps,'zf song')

Now bar(qunits[0]) gives me 0. See where this is going?

The version in my full app reliably gives me the wrong answer, despite
issuing the right SQL. I've set engine.echo=True and enabled query
logging on the MySQL server, and the SQL is all fine. Running the SQL
with engine.execute gives the right answer, as does running the SQL
from a command-line tool.

Any ideas as to what could be causing this? I am at a complete loss.

Thanks,

Channing

--- Code follows -

from sqlalchemy import MetaData, Table, Column, ForeignKey,
create_engine, Integer, String, select
from sqlalchemy.orm import mapper, relation, ColumnProperty,
scoped_session, sessionmaker
from sqlalchemy.databases.mysql import MSEnum

'''
Set up engine
'''
engine = create_engine('mysql://
channing:**...@database.fet.berkeley.edu:3306/physiology')
Session = scoped_session(sessionmaker(autoflush=True,
transactional=True,
  bind=engine))
metadata = MetaData(engine)
query = Session.query

def _parse_fun(fun,fun_args=None):
return lambda x: fun.__call__(x,fun_args)

def n_classresps(unit,class_name):
return query(ClassResponse)\
.filter_by(unit=unit)\
.filter_by(class_name=class_name)\
.count()

class Presentation(object):
pass

class Response(object):
pass

class Unit(object):
pass

class ClassPresentation(Presentation):
pass

class ClassResponse(Response):
pass

presentations = Table('presentations', metadata,
  Column('presentation_id', Integer,
 primary_key=True, nullable=False),
  Column('block_id', Integer, nullable=False),
  Column('type', MSEnum
('single','repeated','class'),
 nullable=False)
  )

responses = Table('responses', metadata,
  Column('response_id', Integer,
 primary_key=True, nullable=False),
  Column('unit_id', Integer,
 ForeignKey('units.unit_id'),
 nullable=False),
  Column(u'presentation_id', Integer,
 ForeignKey('presentations.presentation_id'),
 nullable=False)
  )

class_presentations = Table('class_presentations', metadata,
Column('presentation_id', Integer,
   ForeignKey
('presentations.presentation_id'),
   primary_key=True, nullable=False),
Column('class_name', String,
nullable=False)
)

units = Table('units', metadata,
  Column('unit_id', Integer, primary_key=True,
 nullable=False),
  Column('recsite_id', Integer, nullable=False),
  Column('type', MSEnum('extracellular','intracellular'),
 nullable=False)
  )

mapper(Presentation,presentations,
   polymorphic_on=presentations.c.type,
   polymorphic_identity='presentation')

rmapper = mapper(Response,responses.join(presentations),
 polymorphic_on=presentations.c.type,
 polymorphic_identity='response',
 properties={'unit':relation(Unit)})

mapper(Unit,units)

mapper(ClassPresentation,class_presentations,
   inherits=Presentation,
   polymorphic_identity='class')

mapper(ClassResponse, inherits=rmapper,
   polymorphic_identity='class',
   properties={'class_name':ColumnProperty(select
([clas

[sqlalchemy] Unstable results using lambda function

2008-12-11 Thread channing

I have a weird problem: Two identical functions, created using a
lambda from the same issuing identical SQL, return two different
answers. I'm embarrassed to say this, but it looks stochastic. I'm
running 0.4.2p3 with Python 2.5.2 and Ipython 0.8.1.

First, the guided tour. I'm using a lambda function to make new,
single-argument versions of a multi-argument function:

def _parse_fun(fun, fun_args=None):
return lambda x: fun.__call__(x,fun_args)

Now I have another function that does some filtering and counting:

def n_classresps(unit,class_name):
return query(ClassResponse).filter_by(unit=unit)\
.filter_by(class_name=class_name).count()

And I use _parse_fun to set the value of the class_name argument:

yf = _parse_fun(n_classresps,'noise')

The problem comes when I make multiple instances:

foo = _parse_fun(n_classresps,'noise')

Now calling yf and foo returns different results: yf(qunits[0])
returns 0, while foo(qunits[0]) returns 3.

I've included a model below that reproduces my problem. The server is
a test server that only I'm using, so the database isn't changing. I
have this saved to a file, and I run it in IPython 0.8.1 using the run
command. After running, if I define

foo = _parse_fun(n_classresps,'zf song')

And foo(qunits[0]) gives me 3. Then I define

bar = _parse_fun(n_classresps,'zf song')

Now bar(qunits[0]) gives me 0. See where this is going?

The version in my full app reliably gives me the wrong answer, despite
issuing the right SQL. I've set engine.echo=True and enabled query
logging on the MySQL server, and the SQL is all fine. Running the SQL
with engine.execute gives the right answer, as does running the SQL
from a command-line tool.

Any ideas as to what could be causing this? I am at a complete loss.

Thanks,

Channing

--- Code follows -

from sqlalchemy import MetaData, Table, Column, ForeignKey,
create_engine, Integer, String, select
from sqlalchemy.orm import mapper, relation, ColumnProperty,
scoped_session, sessionmaker
from sqlalchemy.databases.mysql import MSEnum

'''
Set up engine
'''
engine = create_engine('mysql://
channing:fi...@database.fet.berkeley.edu:3306/physiology')
Session = scoped_session(sessionmaker(autoflush=True,
transactional=True,
  bind=engine))
metadata = MetaData(engine)
query = Session.query

def _parse_fun(fun,fun_args=None):
return lambda x: fun.__call__(x,fun_args)

def n_classresps(unit,class_name):
return query(ClassResponse)\
.filter_by(unit=unit)\
.filter_by(class_name=class_name)\
.count()

class Presentation(object):
pass

class Response(object):
pass

class Unit(object):
pass

class ClassPresentation(Presentation):
pass

class ClassResponse(Response):
pass

presentations = Table('presentations', metadata,
  Column('presentation_id', Integer,
 primary_key=True, nullable=False),
  Column('block_id', Integer, nullable=False),
  Column('type', MSEnum
('single','repeated','class'),
 nullable=False)
  )

responses = Table('responses', metadata,
  Column('response_id', Integer,
 primary_key=True, nullable=False),
  Column('unit_id', Integer,
 ForeignKey('units.unit_id'),
 nullable=False),
  Column(u'presentation_id', Integer,
 ForeignKey('presentations.presentation_id'),
 nullable=False)
  )

class_presentations = Table('class_presentations', metadata,
Column('presentation_id', Integer,
   ForeignKey
('presentations.presentation_id'),
   primary_key=True, nullable=False),
Column('class_name', String,
nullable=False)
)

units = Table('units', metadata,
  Column('unit_id', Integer, primary_key=True,
 nullable=False),
  Column('recsite_id', Integer, nullable=False),
  Column('type', MSEnum('extracellular','intracellular'),
 nullable=False)
  )

mapper(Presentation,presentations,
   polymorphic_on=presentations.c.type,
   polymorphic_identity='presentation')

rmapper = mapper(Response,responses.join(presentations),
 polymorphic_on=presentations.c.type,
 polymorphic_identity='response',
 properties={'unit':relation(Unit)})

mapper(Unit,units)

mapper(ClassPresentation,class_presentations,
   inherits=Presentation,
   polymorphic_identity='class')

mapper(ClassResponse, inherits=rmapper,
   polymorphic_identity='class',
   properties={'class_name':ColumnProperty(select
([clas

[sqlalchemy] Re: iterate_properties missing in 0.5?

2008-12-11 Thread Michael Bayer


On Dec 11, 2008, at 7:08 PM, Jorge Vargas wrote:

>
> Hi, has the behavior here
> http://www.sqlalchemy.org/trac/wiki/FAQ#Whatsthebestwaytofigureoutwhichattributesarecolumnsgivenaclass
> changed in 0.5?
>
> I'm trying that and getting
>
> AttributeError: iterate_properties
>
> this is my code, so far:
>
> klass = model.User
>
> def add_user():
>obj = klass()

this is the error:

>mapper = class_mapper(klass).columns

you want the mapper, not mapper.columns


--~--~-~--~~~---~--~~
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] iterate_properties missing in 0.5?

2008-12-11 Thread Jorge Vargas

Hi, has the behavior here
http://www.sqlalchemy.org/trac/wiki/FAQ#Whatsthebestwaytofigureoutwhichattributesarecolumnsgivenaclass
changed in 0.5?

I'm trying that and getting

AttributeError: iterate_properties

this is my code, so far:

klass = model.User

def add_user():
obj = klass()
mapper = class_mapper(klass).columns
print mapper,type(mapper)
for column in mapper.iterate_properties:
raw_input('value for %s'%column)

--~--~-~--~~~---~--~~
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: .compile() not using default params

2008-12-11 Thread zepolen

Ah, makes sense.

Thanks.

On Dec 11, 5:50 pm, Michael Bayer  wrote:
> you're compiling the text() construct against the DefaultDialect, when  
> it needs to be compiled against the PG dialect in order for the :num  
> bind param to be converted to PG's desired format, %(num)s.    Also im  
> not 100% sure if PG allows bind params for LIMIT, probably does though.
>
> On Dec 11, 2008, at 5:33 AM, zepolen wrote:
>
>
>
>
>
> > It seems compile()'ing a query results in the default bindparams not
> > being used, is this a bug?
>
> > Simple test case:
>
>  from sqlalchemy import *
>  engine = create_engine('postgres://uname:pw...@localhost/testdb')
>  query = text('select * from table limit :num',  
>  bindparams=[bindparam('num', value=50)])
>  engine.execute(query).rowcount
> > 50
>  query = text('select * from table limit :num',  
>  bindparams=[bindparam('num', value=50)]).compile()
>  query.params
> > {'num': 50}
>  engine.execute(query).rowcount
> > Traceback (most recent call last):
> >  File "", line 1, in 
> >  File "/home/zepolen/projects/test/ENV/lib/python2.5/site-packages/
> > SQLAlchemy-0.5.0rc4-py2.5.egg/sqlalchemy/engine/base.py", line 1174,
> > in execute
> >    return connection.execute(statement, *multiparams, **params)
> >  File "/home/zepolen/projects/test/ENV/lib/python2.5/site-packages/
> > SQLAlchemy-0.5.0rc4-py2.5.egg/sqlalchemy/engine/base.py", line 806, in
> > execute
> >    return Connection.executors[c](self, object, multiparams, params)
> >  File "/home/zepolen/projects/test/ENV/lib/python2.5/site-packages/
> > SQLAlchemy-0.5.0rc4-py2.5.egg/sqlalchemy/engine/base.py", line 865, in
> > _execute_compiled
> >    return self.__execute_context(context)
> >  File "/home/zepolen/projects/test/ENV/lib/python2.5/site-packages/
> > SQLAlchemy-0.5.0rc4-py2.5.egg/sqlalchemy/engine/base.py", line 878, in
> > __execute_context
> >    self._cursor_execute(context.cursor, context.statement,
> > context.parameters[0], context=context)
> >  File "/home/zepolen/projects/test/ENV/lib/python2.5/site-packages/
> > SQLAlchemy-0.5.0rc4-py2.5.egg/sqlalchemy/engine/base.py", line 927, in
> > _cursor_execute
> >    self._handle_dbapi_exception(e, statement, parameters, cursor)
> >  File "/home/zepolen/projects/test/ENV/lib/python2.5/site-packages/
> > SQLAlchemy-0.5.0rc4-py2.5.egg/sqlalchemy/engine/base.py", line 909, in
> > _handle_dbapi_exception
> >    raise exc.DBAPIError.instance(statement, parameters, e,
> > connection_invalidated=is_disconnect)
> > sqlalchemy.exc.ProgrammingError: (ProgrammingError) syntax error at or
> > near ":"
> > LINE 1: select * from table limit :num
> >                                    ^
> > 'select * from table limit :num' {'num': 50}
--~--~-~--~~~---~--~~
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] session.add

2008-12-11 Thread n00b

hello,

i need to generate a unique number from a table based on the primary
key. i used to lock
the table (with write) and got what i needed. working with the ORM,
though, it seems that
session.add(object) functions just as well. at the time of the
session.add(), the primary key assigned to the object, which is still
in the session, is unique. calling the 'live' object.id get's me what
i need - a unique primary key. somehow this seems too good to be
true ... what am i missing here?

thx
--~--~-~--~~~---~--~~
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: ORM lifecycle questions

2008-12-11 Thread Michael Bayer


On Dec 11, 2008, at 2:04 PM, Ross Vandegrift wrote:

>
> Hi guys,
>
> I'm somewhat confused about the different lifecycle states of objects
> that are backed by the SA ORM.
>
> According to the SA docs (FWIW, I'm on 0.4), an object is in the
> Persistent state when it is present in the session and has a record in
> the database.
>
> So if I do something like this:
>
> p = meta.session.query(model.Pool)
> pool = p.get(7)
> meta.session.refresh(pool)
> InvalidRequestError: Instance 'p...@0xa6aca8c' is not persistent  
> within this Session

um thats kind of weird.   that sort of looks like meta.session is  
being closed out at some point (i.e. not illustrated in the example)  
and being recreated later on is that possible ?

heres a test

from sqlalchemy import *
from sqlalchemy.orm import *

e = create_engine('sqlite://', echo=True)
m = MetaData(e)
t = Table('t', m, Column('id', Integer, primary_key=True))
t.create()

class C(object):
 pass
mapper(C, t)
s = sessionmaker()()

s.save(C())
s.flush()
s.clear()

c1 = s.query(C)
c1 = c1.get(1)
s.refresh(c1)



--~--~-~--~~~---~--~~
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] ORM lifecycle questions

2008-12-11 Thread Ross Vandegrift

Hi guys,

I'm somewhat confused about the different lifecycle states of objects
that are backed by the SA ORM.

According to the SA docs (FWIW, I'm on 0.4), an object is in the
Persistent state when it is present in the session and has a record in
the database.

So if I do something like this:

p = meta.session.query(model.Pool)
pool = p.get(7)
meta.session.refresh(pool)
InvalidRequestError: Instance 'p...@0xa6aca8c' is not persistent within this 
Session



Working on the theory that I've misunderstood what a Persistent object
is, I try this:

meta.session.save(pool)
InvalidRequestError: Instance 'p...@0xa6aca8c' is already persistent


Now I'm really confused.  What did I do?


-- 
Ross Vandegrift
r...@kallisti.us

"If the fight gets hot, the songs get hotter.  If the going gets tough,
the songs get tougher."
--Woody Guthrie

--~--~-~--~~~---~--~~
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: save on new objects?

2008-12-11 Thread Michael Bayer


On Dec 11, 2008, at 12:57 PM, Max Ischenko wrote:

>
> Are you using Session.mapper ?   That's the same behavior the
> extension had in 0.4, save-on-init.   I don't favor the usage of
> Session.mapper.
>
> I do use Session.mapper. I recall I switched to it since I was  
> getting "Parent instance ... is not bound" error with sa.orm.mapper.
>
> I hastily put my SA-updated 0.5 into production and now my inbox  
> filled with hundreds of errors like:
>
> WebApp Error: :  
> Instance  is not bound to a Session;  
> attribute refresh operation cannot proceed
>
> and
>
> WebApp Error: :  
> (ProgrammingError) (2014, "Commands out of sync; you can't run this  
> command now")
>
> and
>
> WebApp Error: : QueuePool limit  
> of size 5 overflow 10 reached, connection timed out, timeout 30
>
> I seems to have fixed the last one by adding these pool config lines  
> to my config.ini.
> sqlalchemy.blog.pool_size = 15
> sqlalchemy.blog.max_overflow = 10
>
>
> Any ideas what I screwed up with the first two errors?

you definitely need to get that code out of production until you work  
out your session usage.   It seems likely that your app is relying on  
a certain behavior that we removed in 0.5 which is the get_session()  
method on Mapper.the 05Migration doc has a note about this which  
is probably easy to miss:

get_session() - this method was not very noticeable, but had the  
effect of associating lazy loads with a particular session even if the  
parent object was entirely detached, when an extension such as  
scoped_session() or the old SessionContextExt was used. It's possible  
that some applications which relied upon this behavior will no longer  
work as expected; but the better programming practice here is to  
always ensure objects are present within sessions if database access  
from their attributes are required.

You're the first person that has reported running into this issue in  
the 05 series so it seemed hopeful that the removal of this method  
wasn't going to have a big impact.

A common pattern which can cause what you see there is if your  
templates are accessing lazy loaders on objects, but the Session which  
loaded those objects had been clear()'ed or otherwise closed before  
the template was allowed to render.  You should try to keep the same  
Session open throughout the full request lifecycle, and you should  
avoid removing any objects from the Session which you wish to continue  
using.

Alternatively, this kind of error may occur if you are using detached  
objects that are stored in a persistent cache.  These objects wont  
"auto attach" when used for the same reason, and in fact even in the  
0.4 series this is a dangerous pattern since globally accessible  
objects can be accessed by multiple threads.   If you want to bring  
cached objects into a current session, bring them in using  
session.merge(dont_load=True).  There's a recipe illustrating this in  
the distribution in examples/query_caching/query_caching.py if you  
want to see a working pattern.






--~--~-~--~~~---~--~~
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: save on new objects?

2008-12-11 Thread Max Ischenko
>
>
> Are you using Session.mapper ?   That's the same behavior the
> extension had in 0.4, save-on-init.   I don't favor the usage of
> Session.mapper.
>

I do use Session.mapper. I recall I switched to it since I was getting
"Parent instance ... is not bound" error with sa.orm.mapper.

I hastily put my SA-updated 0.5 into production and now my inbox filled with
hundreds of errors like:

WebApp Error: : Instance
 is not bound to a Session; attribute refresh
operation cannot proceed

and

WebApp Error: : (ProgrammingError)
(2014, "Commands out of sync; you can't run this command now")

and

WebApp Error: : QueuePool limit of size
5 overflow 10 reached, connection timed out, timeout 30

I seems to have fixed the last one by adding these pool config lines to my
config.ini.
sqlalchemy.blog.pool_size = 15
sqlalchemy.blog.max_overflow = 10


Any ideas what I screwed up with the first two errors?

Here is my current  setup:

from sqlalchemy.orm import scoped_session, sessionmaker
Session = scoped_session(sessionmaker())
Session.extension = Session.extension.configure(save_on_init=False)

def dbinit()
engine = engine_from_config(config, key.rstrip('url'))
session.configure(bind=engine)
meta = sqlalchemy.MetaData(engine)
metadata_cache[dbname] = meta
# используем Session mapper, а не sqlalchemy.orm.mapper
# последний дает иногда ошибку "Parent instance ... is not bound",
# http://tinyurl.com/2a76hp
callback(session.mapper, meta)





-- 
Max.
http://www.developers.org.ua/m/max/

--~--~-~--~~~---~--~~
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: PickleType copy_values and compare_values bug

2008-12-11 Thread Michael Bayer

the change is in r5461, objects like dicts and lists will compare  
correctly with no changes.   Objects that don't implement __eq__() and  
are not None will raise a deprecation warning and use the old dumps()  
method.   Docs are updated on the site as well as 05Migration.




--~--~-~--~~~---~--~~
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: Variable_TypeByValue(): unhandled data type unicode

2008-12-11 Thread Michael Bayer


Look into using the Unicode type for python unicode values.

http://www.sqlalchemy.org/docs/05/reference/sqlalchemy/types.html?highlight=unicode#sqlalchemy.Unicode


On Dec 11, 2008, at 12:01 PM, jo wrote:

>
> Hi all,
>
> I'm using SA with cx_Oracle. In some queries it raises the following  
> error:
>
>
> File "/usr/lib/python2.4/site-packages/sqlalchemy/engine/base.py",  
> line 581, in _execute_raw
>self._execute(context)
>  File "/usr/lib/python2.4/site-packages/sqlalchemy/engine/base.py",  
> line 599, in _execute
>raise exceptions.SQLError(context.statement, context.parameters, e)
> SQLError: (NotSupportedError) Variable_TypeByValue(): unhandled data  
> type unicode
> 'SELECT comune.data_fine AS comune_data_fine, comune.id AS  
> comune_id, comune.auto_sync_bdn AS comune_auto_sync_bdn,
> comune.cod_provincia AS comune_cod_provincia, comune.istat AS  
> comune_istat, comune.data_inizio AS comune_data_inizio,
> comune.cap AS comune_cap, comune.codice_erariale AS  
> comune_codice_erariale, comune.bdn_id AS comune_bdn_id,
> comune.nome AS comune_nome
> \nFROM comune
> \nWHERE comune.id = :comune_id ORDER BY comune.rowid' {'comune_id':  
> u'2895'}
>
>
> Someone could help me?
>
> j
>
>
>
> >


--~--~-~--~~~---~--~~
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] Variable_TypeByValue(): unhandled data type unicode

2008-12-11 Thread jo

Hi all,

I'm using SA with cx_Oracle. In some queries it raises the following error:


 File "/usr/lib/python2.4/site-packages/sqlalchemy/engine/base.py", line 581, 
in _execute_raw
self._execute(context)
  File "/usr/lib/python2.4/site-packages/sqlalchemy/engine/base.py", line 599, 
in _execute
raise exceptions.SQLError(context.statement, context.parameters, e)
SQLError: (NotSupportedError) Variable_TypeByValue(): unhandled data type 
unicode 
'SELECT comune.data_fine AS comune_data_fine, comune.id AS comune_id, 
comune.auto_sync_bdn AS comune_auto_sync_bdn, 
comune.cod_provincia AS comune_cod_provincia, comune.istat AS comune_istat, 
comune.data_inizio AS comune_data_inizio, 
comune.cap AS comune_cap, comune.codice_erariale AS comune_codice_erariale, 
comune.bdn_id AS comune_bdn_id, 
comune.nome AS comune_nome 
\nFROM comune 
\nWHERE comune.id = :comune_id ORDER BY comune.rowid' {'comune_id': u'2895'}


Someone could help me?

j



--~--~-~--~~~---~--~~
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: PickleType copy_values and compare_values bug

2008-12-11 Thread Michael Bayer


On Dec 11, 2008, at 5:50 AM, Jonathan Marshall wrote:

> Also I don't agree that the current desired behaviour is documented.
> See http://www.sqlalchemy.org/docs/05/types.html#types_standard_pickletype
> and 
> http://www.sqlalchemy.org/docs/05/sqlalchemy_types.html#docstrings_sqlalchemy.types_PickleType

OK both of those files you must have found through an outdated google  
search and are now removed from the site.  Here is the correct document:

http://www.sqlalchemy.org/docs/05/reference/sqlalchemy/types.html?highlight=pickletype#sqlalchemy.PickleType

however mutable + object without __eq__() is being deprecated as we  
speak and will raise a warning.

--~--~-~--~~~---~--~~
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: Oracle sql syntax

2008-12-11 Thread jo

You are right, Michael,
1=0 works.
thank you,
j

Michael Bayer ha scritto:
> I'd try 1 = 0  I dont think oracle has boolean keywords at least  
> last I checked...
>
>
> On Dec 11, 2008, at 4:09 AM, jo wrote:
>
>   
>> Hi all,
>>
>> I'm trying sqlalchemy with Oracle. Seems Oracle doesn't understand  
>> the syntax  True = False
>>
>> ...
>>  File "/usr/lib/python2.4/site-packages/sqlalchemy/engine/base.py",  
>> line 599, in _execute
>>raise exceptions.SQLError(context.statement, context.parameters, e)
>> SQLError: (DatabaseError) ORA-00904: "FALSE": invalid identifier
>> 'SELECT count(permesso.codice) \nFROM permesso \nWHERE True =  
>> False' {}
>>
>>
>> any ideas?
>>
>> j
>>
>>
>>
>> 
>
>
> >
>   


--~--~-~--~~~---~--~~
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: Oracle sql syntax

2008-12-11 Thread Michael Bayer

I'd try 1 = 0  I dont think oracle has boolean keywords at least  
last I checked...


On Dec 11, 2008, at 4:09 AM, jo wrote:

>
> Hi all,
>
> I'm trying sqlalchemy with Oracle. Seems Oracle doesn't understand  
> the syntax  True = False
>
> ...
>  File "/usr/lib/python2.4/site-packages/sqlalchemy/engine/base.py",  
> line 599, in _execute
>raise exceptions.SQLError(context.statement, context.parameters, e)
> SQLError: (DatabaseError) ORA-00904: "FALSE": invalid identifier
> 'SELECT count(permesso.codice) \nFROM permesso \nWHERE True =  
> False' {}
>
>
> any ideas?
>
> j
>
>
>
> >


--~--~-~--~~~---~--~~
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: date in sqlite

2008-12-11 Thread Michael Bayer

the name of your Date column is "premiera", I dont see a "termin"  
column specified in the example ?

On Dec 11, 2008, at 7:35 AM, grat wrote:

>
> Hi,
>
> i have this table:
>
> class ZmenaDH(Base):
>__tablename__="zmenahost"
>id = Column(Integer,primary_key=True)
>duvod=Column(String(120))
>premiera=Column(Date)
>id_solo = Column(Integer, ForeignKey('sola.id'))
>
>solo = relation("Solo", backref=backref('zmenahost', order_by=id,
> uselist=False))
>def __init__(self,duvod,termin):
>self.duvod=duvod
>self.termin=termin
>
> in use:
> zm=ZmenaDH("Smlouva",datetime.date(2002, 3, 11))
> zm.id_solo=109
> sql.session.add(zm)
> sql.session.commit()
>
> but date not store in table, no errors
>
> please, howto save date in sqlite?
>
> Thanks
>
> >


--~--~-~--~~~---~--~~
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: .compile() not using default params

2008-12-11 Thread Michael Bayer

you're compiling the text() construct against the DefaultDialect, when  
it needs to be compiled against the PG dialect in order for the :num  
bind param to be converted to PG's desired format, %(num)s.Also im  
not 100% sure if PG allows bind params for LIMIT, probably does though.

On Dec 11, 2008, at 5:33 AM, zepolen wrote:

>
> It seems compile()'ing a query results in the default bindparams not
> being used, is this a bug?
>
> Simple test case:
>
 from sqlalchemy import *
 engine = create_engine('postgres://uname:[EMAIL PROTECTED]/testdb')
 query = text('select * from table limit :num',  
 bindparams=[bindparam('num', value=50)])
 engine.execute(query).rowcount
> 50
 query = text('select * from table limit :num',  
 bindparams=[bindparam('num', value=50)]).compile()
 query.params
> {'num': 50}
 engine.execute(query).rowcount
> Traceback (most recent call last):
>  File "", line 1, in 
>  File "/home/zepolen/projects/test/ENV/lib/python2.5/site-packages/
> SQLAlchemy-0.5.0rc4-py2.5.egg/sqlalchemy/engine/base.py", line 1174,
> in execute
>return connection.execute(statement, *multiparams, **params)
>  File "/home/zepolen/projects/test/ENV/lib/python2.5/site-packages/
> SQLAlchemy-0.5.0rc4-py2.5.egg/sqlalchemy/engine/base.py", line 806, in
> execute
>return Connection.executors[c](self, object, multiparams, params)
>  File "/home/zepolen/projects/test/ENV/lib/python2.5/site-packages/
> SQLAlchemy-0.5.0rc4-py2.5.egg/sqlalchemy/engine/base.py", line 865, in
> _execute_compiled
>return self.__execute_context(context)
>  File "/home/zepolen/projects/test/ENV/lib/python2.5/site-packages/
> SQLAlchemy-0.5.0rc4-py2.5.egg/sqlalchemy/engine/base.py", line 878, in
> __execute_context
>self._cursor_execute(context.cursor, context.statement,
> context.parameters[0], context=context)
>  File "/home/zepolen/projects/test/ENV/lib/python2.5/site-packages/
> SQLAlchemy-0.5.0rc4-py2.5.egg/sqlalchemy/engine/base.py", line 927, in
> _cursor_execute
>self._handle_dbapi_exception(e, statement, parameters, cursor)
>  File "/home/zepolen/projects/test/ENV/lib/python2.5/site-packages/
> SQLAlchemy-0.5.0rc4-py2.5.egg/sqlalchemy/engine/base.py", line 909, in
> _handle_dbapi_exception
>raise exc.DBAPIError.instance(statement, parameters, e,
> connection_invalidated=is_disconnect)
> sqlalchemy.exc.ProgrammingError: (ProgrammingError) syntax error at or
> near ":"
> LINE 1: select * from table limit :num
>^
> 'select * from table limit :num' {'num': 50}
>
> >


--~--~-~--~~~---~--~~
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: save on new objects?

2008-12-11 Thread Michael Bayer


On Dec 11, 2008, at 9:43 AM, Max Ischenko wrote:

>
> Hello,
>
> I'm migrating my pylons app to SA 0.5 I ran into strange behaviour.
>
> I found that hen creating new object it ends up in Session
> automatically. Why is that?
>
> After some debugging I found this:
>
>def init_instance(self, mapper, class_, oldinit, instance, args,
> kwargs):
>if self.save_on_init:
>session = kwargs.pop('_sa_session', None)
>if session is None:
>session = self.context.registry()
>session._save_without_cascade(instance)
>return EXT_CONTINUE
>
> Obviously this is international. But why? It doesn't make sense and
> 05Migration do not mention this.
>
> After I added
> Session.extension = Session.extension.configure(save_on_init=False)
>
> the code started working again.
>
> Do I miss something or this is a bug?

Are you using Session.mapper ?   That's the same behavior the  
extension had in 0.4, save-on-init.   I don't favor the usage of  
Session.mapper.





--~--~-~--~~~---~--~~
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: PickleType copy_values and compare_values bug

2008-12-11 Thread Michael Bayer


On Dec 11, 2008, at 5:50 AM, Jonathan Marshall wrote:

>
> The problem seems to be the assumption that copies of an object
> produce identical pickles. Perhaps a better solution may be for
> compare_values to use __eq__ by default if it exists otherwise compare
> __dict__?

comparing __dict__ is pretty involved and would mean we'd have to dig  
down arbitrarily deep into the object tree.  It would be like  
reimplementing pickle, really.  I'd rather just make __eq__()  
mandatory for the usage of PickleType when mutable=True.


> Also I don't agree that the current desired behaviour is documented.
> See http://www.sqlalchemy.org/docs/05/types.html#types_standard_pickletype
> and 
> http://www.sqlalchemy.org/docs/05/sqlalchemy_types.html#docstrings_sqlalchemy.types_PickleType

OK, thats a bug in the configuration of our new sphinx doc generator.   
Here is the docstring for PickleType:

 """Holds Python objects.

 PickleType builds upon the Binary type to apply Python's
 ``pickle.dumps()`` to incoming objects, and ``pickle.loads()`` on
 the way out, allowing any pickleable Python object to be stored as
 a serialized binary field.

 """
 """
 Construct a PickleType.

 :param protocol: defaults to ``pickle.HIGHEST_PROTOCOL``.

 :param pickler: defaults to cPickle.pickle or pickle.pickle if
   cPickle is not available.  May be any object with
   pickle-compatible ``dumps` and ``loads`` methods.

 :param mutable: defaults to True; implements
   :meth:`AbstractType.is_mutable`.

 :param comparator: optional. a 2-arg callable predicate used
   to compare values of this type.  Defaults to equality if
   *mutable* is False or ``pickler.dumps()`` equality if
   *mutable* is True.

 """


--~--~-~--~~~---~--~~
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: Setting up a self-referential mapper using the declarative layer

2008-12-11 Thread Michael Bayer


On Dec 11, 2008, at 5:50 AM, Andreas Jung wrote:

>
> This works to some degree:
>
> class Hierarchies(Base):
> __tablename__ = 'hierarchies'
> __table_args__ = (
> { 'autoload' : True, })
>
> parent_id = Column('parent_id', Integer,  
> ForeignKey('hierarchies.id'))
>
> _children = relation('Hierarchies',
>
> primaryjoin='Hierarchies.parent_id==Hierarchies.id',
>  order_by=['Hierarchies.pos'],
>  cascade="all",
>  backref=backref("parent",
> remote_side=['Hierarchies.id'])
>
>
> hso = session.query(Hierarchies).filter_by(id=1641).one()
> print hso._children
> for c in hso._children:
> print c
>
> hso._children is a PropertyLoader instance in this case that can not  
> be used
> for iteration.
>
> The "same" code implemented as standard mapper using SA 0.3 behaves as
> it should.
> I can not see the difference how to make it work with SA 0.5.

Actually that code doesn't work for me at all so I dont know how  
you're getting that result.   When I changed it to be "correct", I  
uncovered a bug relating to using a string for remote_side in  
backref() and fixed in r5460.

the strings you give to the arguments are eval'ed, so any list  
constructs need to be part of the string too (but are not needed  
here).So here are the ways you can do this, the first one is the  
only one that relies upon the fix in 5460:

class Hierarchies(Base):
 __tablename__ = 'hierarchies'
 __table_args__ = ({ 'autoload' : True, })

 parent_id = Column('parent_id', Integer,  
ForeignKey('hierarchies.id'))

 _children =  
relation 
('Hierarchies',primaryjoin='Hierarchies.parent_id==Hierarchies.id',
  order_by='Hierarchies.pos',
  cascade="all",
  backref=backref("parent",  
remote_side='Hierarchies.id')
  )


class Hierarchies(Base):
 __table__ = Table('hierarchies', Base.metadata, autoload=True)

 _children =  
relation 
('Hierarchies',primaryjoin=__table__.c.parent_id==__table__.c.id,
  order_by=__table__.c.pos
  cascade="all",
  backref=backref("parent",  
remote_side=__table__.c.id)
  )

# not using autoload, this is the core "declarative" usage  
since...well its declarative:

class Hierarchies(Base):
 __tablename__ = 'hierarchies'

 id = Column(Integer, primary_key=True)
 parent_id = Column(Integer, ForeignKey('hierarchies.id'))
 pos = Column(Integer)

 _children = relation('Hierarchies',primaryjoin=parent_id==id,
  order_by=pos
  cascade="all",
  backref=backref("parent", remote_side=id)
  )



--~--~-~--~~~---~--~~
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: Extending sqlalchemy.schema.Column and metaprogramming traps

2008-12-11 Thread Michael Bayer


On Dec 11, 2008, at 3:37 AM, Angri wrote:

>
> Here it is: http://www.sqlalchemy.org/trac/ticket/1244
>
> Maybe it is good idea to drop some new lines in faq? Something like
> this:
>
> Q: How should I extend sqlalchemy.schema.Column?
> A: You surely dont need it. Recommended way to achive your possible
> needs is to write instance-factory function which decorates creation
> of sqlalchemy.schema.Column instances.
>
> Q: But I'm really need it!
> A: Ok. To subclass Column, this is the current recipe:
>
> from sqlalchemy.sql.util import Annotated, annotated_classes
>
> class MyColumn(Column):
>...
>
> class AnnotatedMyColumn(Annotated, MyColumn):
>pass
>
> annotated_classes[MyColumn] = AnnotatedMyColumn
>
> Do not forget to put AnnotatedMyColumn in the module namespace, or
> your schema will not be pickleable!
>
> Correct me please if I am wrong somewhere and excuse me for my
> English.

Well the AnnotatedMyColumn part is less than ideal since its an  
internal.  the way that works could very likely change.   Creating an  
AnnotatedXXX class *can* be automated.  the pickle thing just might be  
a caveat we'd document or arrange for an exception to occur (like  
putting a throw in a __getstate__ method).

--~--~-~--~~~---~--~~
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] date in sqlite

2008-12-11 Thread grat

Hi,

i have this table:

class ZmenaDH(Base):
__tablename__="zmenahost"
id = Column(Integer,primary_key=True)
duvod=Column(String(120))
premiera=Column(Date)
id_solo = Column(Integer, ForeignKey('sola.id'))

solo = relation("Solo", backref=backref('zmenahost', order_by=id,
uselist=False))
def __init__(self,duvod,termin):
self.duvod=duvod
self.termin=termin

in use:
zm=ZmenaDH("Smlouva",datetime.date(2002, 3, 11))
zm.id_solo=109
sql.session.add(zm)
sql.session.commit()

but date not store in table, no errors

please, howto save date in sqlite?

Thanks

--~--~-~--~~~---~--~~
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] .compile() not using default params

2008-12-11 Thread zepolen

It seems compile()'ing a query results in the default bindparams not
being used, is this a bug?

Simple test case:

>>> from sqlalchemy import *
>>> engine = create_engine('postgres://uname:[EMAIL PROTECTED]/testdb')
>>> query = text('select * from table limit :num', bindparams=[bindparam('num', 
>>> value=50)])
>>> engine.execute(query).rowcount
50
>>> query = text('select * from table limit :num', bindparams=[bindparam('num', 
>>> value=50)]).compile()
>>> query.params
{'num': 50}
>>> engine.execute(query).rowcount
Traceback (most recent call last):
  File "", line 1, in 
  File "/home/zepolen/projects/test/ENV/lib/python2.5/site-packages/
SQLAlchemy-0.5.0rc4-py2.5.egg/sqlalchemy/engine/base.py", line 1174,
in execute
return connection.execute(statement, *multiparams, **params)
  File "/home/zepolen/projects/test/ENV/lib/python2.5/site-packages/
SQLAlchemy-0.5.0rc4-py2.5.egg/sqlalchemy/engine/base.py", line 806, in
execute
return Connection.executors[c](self, object, multiparams, params)
  File "/home/zepolen/projects/test/ENV/lib/python2.5/site-packages/
SQLAlchemy-0.5.0rc4-py2.5.egg/sqlalchemy/engine/base.py", line 865, in
_execute_compiled
return self.__execute_context(context)
  File "/home/zepolen/projects/test/ENV/lib/python2.5/site-packages/
SQLAlchemy-0.5.0rc4-py2.5.egg/sqlalchemy/engine/base.py", line 878, in
__execute_context
self._cursor_execute(context.cursor, context.statement,
context.parameters[0], context=context)
  File "/home/zepolen/projects/test/ENV/lib/python2.5/site-packages/
SQLAlchemy-0.5.0rc4-py2.5.egg/sqlalchemy/engine/base.py", line 927, in
_cursor_execute
self._handle_dbapi_exception(e, statement, parameters, cursor)
  File "/home/zepolen/projects/test/ENV/lib/python2.5/site-packages/
SQLAlchemy-0.5.0rc4-py2.5.egg/sqlalchemy/engine/base.py", line 909, in
_handle_dbapi_exception
raise exc.DBAPIError.instance(statement, parameters, e,
connection_invalidated=is_disconnect)
sqlalchemy.exc.ProgrammingError: (ProgrammingError) syntax error at or
near ":"
LINE 1: select * from table limit :num
^
 'select * from table limit :num' {'num': 50}

--~--~-~--~~~---~--~~
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] save on new objects?

2008-12-11 Thread Max Ischenko

Hello,

I'm migrating my pylons app to SA 0.5 I ran into strange behaviour.

I found that hen creating new object it ends up in Session
automatically. Why is that?

After some debugging I found this:

def init_instance(self, mapper, class_, oldinit, instance, args,
kwargs):
if self.save_on_init:
session = kwargs.pop('_sa_session', None)
if session is None:
session = self.context.registry()
session._save_without_cascade(instance)
return EXT_CONTINUE

Obviously this is international. But why? It doesn't make sense and
05Migration do not mention this.

After I added
Session.extension = Session.extension.configure(save_on_init=False)

the code started working again.

Do I miss something or this is a bug?

--
Max.
http://www.developers.org.ua/m/max/
--~--~-~--~~~---~--~~
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: Create tables with metadata

2008-12-11 Thread Empty
Hi,

On Thu, Dec 11, 2008 at 8:12 AM, [EMAIL PROTECTED] <
[EMAIL PROTECTED]> wrote:

>
> Hi
> I've scoured the documentation and i can't find any info on how to
> create a column using metadata.
>
> from sqlalchemy import engine
> from sqlalchemy import schema
> from sqlalchemy import types
>
> _config_dbengine = engine.create_engine('sqlite:tmp/db')
> _config_metadata = schema.MetaData(_config_dbengine, reflect=True)
> table = _config_metadata.tables['table_name']
> table.append_column(schema.Column('id', types.Integer,
> primary_key=True, autoincrement=True))
>
> This is the steps i'm using but the column doesn't get created.
>

Doesn't get created where?  In the database?  That's not going to happen.
 Are you saying it's not included as part of the table definition?

Michael

--~--~-~--~~~---~--~~
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] Create tables with metadata

2008-12-11 Thread jarrod.ches...@gmail.com

Hi
I've scoured the documentation and i can't find any info on how to
create a column using metadata.

from sqlalchemy import engine
from sqlalchemy import schema
from sqlalchemy import types

_config_dbengine = engine.create_engine('sqlite:tmp/db')
_config_metadata = schema.MetaData(_config_dbengine, reflect=True)
table = _config_metadata.tables['table_name']
table.append_column(schema.Column('id', types.Integer,
primary_key=True, autoincrement=True))

This is the steps i'm using but the column doesn't get created.

Any ideas?
--~--~-~--~~~---~--~~
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: PickleType copy_values and compare_values bug

2008-12-11 Thread Jonathan Marshall

On Dec 10, 7:33 pm, Michael Bayer <[EMAIL PROTECTED]> wrote:
> this is the documented behavior and the comparator=operator.eq setting  
> is provided for exactly the purpose of efficiently comparing objects  
> which do implement an __eq__() that compares internal state, like that  
> of a dict (and who also don't provide identical pickles each time).    
> The default behavior of comparing pickles is to support user-defined  
> objects with mutable state which do not have an __eq__() method  
> provided.

Hi Michael,

It doesn't always work for the case that you mentioned.

class Foo:
  pass

d1 = Foo()
d1.Broker = 'A'
d1.F = 'B'
d1.Amt = 'A'

assert p.compare_values(p.copy_value(d1), d1)

If you use pickletools you can see that the variables of Foo are being
dumped in a different order in each of the cases below:

pickletools.dis(pickle.dumps(d1))
pickletools.dis(pickle.dumps(pickle.loads(pickle.dumps(d1
pickletools.dis(pickle.dumps(copy.copy(d1)))

The problem seems to be the assumption that copies of an object
produce identical pickles. Perhaps a better solution may be for
compare_values to use __eq__ by default if it exists otherwise compare
__dict__?

Also I don't agree that the current desired behaviour is documented.
See http://www.sqlalchemy.org/docs/05/types.html#types_standard_pickletype
and 
http://www.sqlalchemy.org/docs/05/sqlalchemy_types.html#docstrings_sqlalchemy.types_PickleType

Cheers,
Jon.
--~--~-~--~~~---~--~~
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: Setting up a self-referential mapper using the declarative layer

2008-12-11 Thread Andreas Jung
On 11.12.2008 11:10 Uhr, [EMAIL PROTECTED] wrote:
> afaik, u can supply strings instead of real things everywhere in those
> arguments.. they are eval()ed against some context at later time.
>

This works to some degree:

class Hierarchies(Base):
 __tablename__ = 'hierarchies'
 __table_args__ = (
 { 'autoload' : True, })

 parent_id = Column('parent_id', Integer, ForeignKey('hierarchies.id'))

 _children = relation('Hierarchies',
 
primaryjoin='Hierarchies.parent_id==Hierarchies.id',
  order_by=['Hierarchies.pos'],
  cascade="all",
  backref=backref("parent", 
remote_side=['Hierarchies.id'])


hso = session.query(Hierarchies).filter_by(id=1641).one()
print hso._children
for c in hso._children:
 print c

hso._children is a PropertyLoader instance in this case that can not be used
for iteration.

The "same" code implemented as standard mapper using SA 0.3 behaves as 
it should.
I can not see the difference how to make it work with SA 0.5.

Andreas

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

begin:vcard
fn:Andreas Jung
n:Jung;Andreas
org:ZOPYX Ltd. & Co. KG
adr;quoted-printable:;;Charlottenstr. 37/1;T=C3=BCbingen;;72070;Germany
email;internet:[EMAIL PROTECTED]
title:CEO
tel;work:+49-7071-793376
tel;fax:+49-7071-7936840
tel;home:+49-7071-793257
x-mozilla-html:FALSE
url:www.zopyx.com
version:2.1
end:vcard



[sqlalchemy] Re: Oracle sql syntax

2008-12-11 Thread jo

I'm Sorry, unwittingly, I changed the original subject.

--~--~-~--~~~---~--~~
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] Oracle sql syntax

2008-12-11 Thread jo

Hi all,

I'm trying sqlalchemy with Oracle. Seems Oracle doesn't understand the syntax  
True = False 

...
  File "/usr/lib/python2.4/site-packages/sqlalchemy/engine/base.py", line 599, 
in _execute
raise exceptions.SQLError(context.statement, context.parameters, e)
SQLError: (DatabaseError) ORA-00904: "FALSE": invalid identifier
 'SELECT count(permesso.codice) \nFROM permesso \nWHERE True = False' {}


any ideas?

j



--~--~-~--~~~---~--~~
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: Setting up a self-referential mapper using the declarative layer

2008-12-11 Thread az

afaik, u can supply strings instead of real things everywhere in those 
arguments.. they are eval()ed against some context at later time.

On Thursday 11 December 2008 10:40, Andreas Jung wrote:
> Can the decl. layer be used to setup a self-referential mapper like
>
>
> class Foo(Base):
>
> __tablename__ = 'foo'
> __table_args__ = {'autoload' : True}
>
> children = relation(Foo, primaryjoin=Foo.parent_id==Foo.id)
> parent = relation(Foo, primary_join=Foo.parent_id=Foo.id,
>   remote_side=[Foo.id])
>
> Basically using 'Foo' within the relation() does not work within the
> class definition of Foo itself.
>
> Andreas
>
> 

--~--~-~--~~~---~--~~
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] Setting up a self-referential mapper using the declarative layer

2008-12-11 Thread Andreas Jung
Can the decl. layer be used to setup a self-referential mapper like


class Foo(Base):

__tablename__ = 'foo'
__table_args__ = {'autoload' : True}

children = relation(Foo, primaryjoin=Foo.parent_id==Foo.id)
parent = relation(Foo, primary_join=Foo.parent_id=Foo.id,
  remote_side=[Foo.id])

Basically using 'Foo' within the relation() does not work within the 
class definition of Foo itself.

Andreas

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

begin:vcard
fn:Andreas Jung
n:Jung;Andreas
org:ZOPYX Ltd. & Co. KG
adr;quoted-printable:;;Charlottenstr. 37/1;T=C3=BCbingen;;72070;Germany
email;internet:[EMAIL PROTECTED]
title:CEO
tel;work:+49-7071-793376
tel;fax:+49-7071-7936840
tel;home:+49-7071-793257
x-mozilla-html:FALSE
url:www.zopyx.com
version:2.1
end:vcard



[sqlalchemy] Re: Extending sqlalchemy.schema.Column and metaprogramming traps

2008-12-11 Thread Angri

Here it is: http://www.sqlalchemy.org/trac/ticket/1244

Maybe it is good idea to drop some new lines in faq? Something like
this:

Q: How should I extend sqlalchemy.schema.Column?
A: You surely dont need it. Recommended way to achive your possible
needs is to write instance-factory function which decorates creation
of sqlalchemy.schema.Column instances.

Q: But I'm really need it!
A: Ok. To subclass Column, this is the current recipe:

from sqlalchemy.sql.util import Annotated, annotated_classes

class MyColumn(Column):
...

class AnnotatedMyColumn(Annotated, MyColumn):
pass

annotated_classes[MyColumn] = AnnotatedMyColumn

Do not forget to put AnnotatedMyColumn in the module namespace, or
your schema will not be pickleable!

Correct me please if I am wrong somewhere and excuse me for my
English.

On 11 дек, 01:23, Michael Bayer <[EMAIL PROTECTED]> wrote:
> hey send it as an email attachment, or create a ticket in trac as  
> guest/guest and attach it there:  http://www.sqlalchemy.org/trac/newticket
>
> On Dec 10, 2008, at 5:19 PM, Angri wrote:
>
>
>
>
>
> >> if you'd like to submit a patch which defines __visit_name__ for all
> >> ClauseElements and removes the logic from VisitableType to guess the
> >> name, it will be accepted.  The second half of VisitableType still  
> >> may
> >> be needed since it improves performance.
>
> > Ok, I did it. Can not find where I can attach file to message in
> > google groups, so I put it in paste bin:http://paste.org/index.php?id=4463
>
> > I made some automated tests to make sure that nothing will break.
> > Existing Visitable's descendants after applying the patch will have
> > exactly the same value of __visit_name__ property. I also put small
> > test from first message in the topic. It fails with vanila trunk and
> > pass ok with patched.
>
> > Take a look, please.
--~--~-~--~~~---~--~~
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
-~--~~~~--~~--~--~---