Re: [sqlalchemy] to many statements for collection.append?

2011-11-10 Thread Michael Bayer

On Nov 9, 2011, at 3:37 AM, sector119 wrote:

> 
> ### TEST 2
> # HERE I GOT ERROR if I uncomment "user = ..." line
> 
> session = Session()
> 
> report = session.query(Report).get(1)
> #user = session.query(User).filter_by(username='sector119').one()
> comment = Comment(content=u'test comment', user=user)
> report.comments.append(comment)
> session.add(report)
> session.flush()
> session.commit()
> 
> session.close()
> 

issue is here:

# create new Comment object, user=user means "comment" is now present
# in the Session.  The "report" reference is None.
comment = Comment(content=u'test comment', user=user)

# steps here are:
#   1. access report.comments
#   2. report.comments not present, loads from the database
#   3. autoflush
#   4. append "comment" to collection
report.comments.append(comment)

the above fails as autoflush flushes the incomplete "comment" object.  this can 
be seen in the stack trace:

> self.session._autoflush()
>   File "/home/eps/devel/tourclub/sqlalchemy/lib/sqlalchemy/orm/session.py", 
> line 973, in _autoflush

solution is to set the "report" on the "comment" instead, or to temporarily 
disable autoflush, such as at 

http://www.sqlalchemy.org/trac/wiki/UsageRecipes/DisableAutoflush




-- 
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] UniqueConstraint with func

2011-11-10 Thread Michael Bayer
id never heard of a functional unique constraint but there you go, here's a 
stack overflow answer for this one:

http://stackoverflow.com/questions/1510018/compound-uniqueconstraint-with-a-function



On Nov 10, 2011, at 1:15 AM, lestat wrote:

> Can I add UniqueConstraint like this?
> 
> 
> from sqlalchemy import func
> from sqlalchemy.schema import UniqueConstraint
> from sqlalchemy.dialects import postgres
> 
> class UserIp(db.Model):
>__tablename__ = 'user_ip'
> 
>__table_args__ = (
>UniqueConstraint('user_id', func.md5('ip')),
>)
> 
>user_id = db.Column(db.Integer, db.ForeignKey('user.id'),
> primary_key=True, default=None)
>ip = db.Column(postgres.CIDR, nullable=False,
> default='127.0.0.1/32')
> 
> 
> 
> It raise exception:
> 
> /usr/lib/python2.7/site-packages/flaskext/sqlalchemy.pyc in
> __init__(self, name, bases, d)
>465 def __init__(self, name, bases, d):
>466 bind_key = d.pop('__bind_key__', None)
> --> 467 DeclarativeMeta.__init__(self, name, bases, d)
>468 if bind_key is not None:
>469 self.__table__.info['bind_key'] = bind_key
> 
> /usr/lib/python2.7/site-packages/sqlalchemy/ext/declarative.pyc in
> __init__(cls, classname, bases, dict_)
>   1257 return type.__init__(cls, classname, bases, dict_)
>   1258 else:
> -> 1259 _as_declarative(cls, classname, cls.__dict__)
>   1260 return type.__init__(cls, classname, bases, dict_)
>   1261
> 
> /usr/lib/python2.7/site-packages/sqlalchemy/ext/declarative.pyc in
> _as_declarative(cls, classname, dict_)
>   1156 cls.__table__ = table = Table(tablename,
> cls.metadata,
>   1157   *(tuple(cols) +
> tuple(args)),
> -> 1158**table_kw)
>   1159 else:
>   1160 table = cls.__table__
> 
> /usr/lib/python2.7/site-packages/sqlalchemy/schema.pyc in __new__(cls,
> *args, **kw)
>267 metadata._add_table(name, schema, table)
>268 try:
> --> 269 table._init(name, metadata, *args, **kw)
>270 table.dispatch.after_parent_attach(table,
> metadata)
>271 return table
> 
> /usr/lib/python2.7/site-packages/sqlalchemy/schema.pyc in _init(self,
> name, metadata, *args, **kwargs)
>342 # initialize all the column, etc. objects.  done after
> reflection to
>343 # allow user-overrides
> --> 344 self._init_items(*args)
>345
>346 @property
> 
> /usr/lib/python2.7/site-packages/sqlalchemy/schema.pyc in
> _init_items(self, *args)
> 62 for item in args:
> 63 if item is not None:
> ---> 64 item._set_parent_with_dispatch(self)
> 65
> 66 def get_children(self, **kwargs):
> 
> /usr/lib/python2.7/site-packages/sqlalchemy/events.pyc in
> _set_parent_with_dispatch(self, parent)
>228 def _set_parent_with_dispatch(self, parent):
>229 self.dispatch.before_parent_attach(self, parent)
> --> 230 self._set_parent(parent)
>231 self.dispatch.after_parent_attach(self, parent)
>232
> 
> /usr/lib/python2.7/site-packages/sqlalchemy/schema.pyc in
> _set_parent(self, table)
>   1827
>   1828 def _set_parent(self, table):
> -> 1829 ColumnCollectionMixin._set_parent(self, table)
>   1830 Constraint._set_parent(self, table)
>   1831
> 
> /usr/lib/python2.7/site-packages/sqlalchemy/schema.pyc in
> _set_parent(self, table)
>   1801 if isinstance(col, basestring):
>   1802 col = table.c[col]
> -> 1803 self.columns.add(col)
>   1804
>   1805 class ColumnCollectionConstraint(ColumnCollectionMixin,
> Constraint):
> 
> /usr/lib/python2.7/site-packages/sqlalchemy/sql/expression.pyc in
> add(self, column)
>   2135
>   2136 """
> -> 2137 self[column.key] = column
>   2138
>   2139 def __delitem__(self, key):
> 
> AttributeError: 'Function' object has no attribute 'key'
> 
> 
> 
> 
> 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 
> 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] Getting ENUM-like behavior from a MySQL VARCHAR

2011-11-10 Thread Michael Bayer

On Nov 9, 2011, at 5:27 PM, Ryan wrote:

> I have a MySQL VARCHAR column, but I'd like to get ENUM-like behavior at the 
> ORM level. I'm using the declarative style. Here's what I've got so far:
> 
> language = Column(Enum('en', 'fr', native_enum=False), CheckConstraint(), 
> default='en')
> 
> Docs say that when native_enum is set to False, uses VARCHAR + check 
> constraint for all backends.
> 
> What args do I need to pass to CheckConstraint in order to restrict the list 
> of languages?

the CHECK constraint is generated automatically by the Enum type:

class A(Base):
__tablename__= 'a'
id = Column(Integer, primary_key=True)
language = Column(Enum('en', 'fr', native_enum=False), default='en')
e = create_engine("mysql://scott:tiger@localhost/test", echo=True)
Base.metadata.create_all(e)

output:

CREATE TABLE a (
id INTEGER NOT NULL AUTO_INCREMENT, 
language VARCHAR(2), 
PRIMARY KEY (id), 
CHECK (language IN ('en', 'fr'))
)






> 
> 
> -- 
> 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/-/9upUrF4h5-QJ.
> 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] subqueryload problem

2011-11-10 Thread Michael Bayer

On Nov 10, 2011, at 11:59 AM, Ian Wilson wrote:

> I'm not sure if this is a case of user error or what but I'm trying to
> use a double sub-query load.  The odds are probably pretty good that
> I'm doing something wrong.  I just finally got around to trying
> subqueryload and I think it is what I've been looking for my entire
> life.  Although the SQL being generated looks incorrect.
> 
> The big idea is that I have a list of tours, each tour has a bunch of
> sights below it that all have images.  The tour itself does not have
> an image.  I want to show all the tours with the image of the first
> sight for that tour.  So I'm trying to fire off 3 queries, one to get
> the tours, one to get the first sight of each tour, and one to get the
> image of each first sight.
> 
> I'm using sqlalchemy 0.7.3 in the imperative?(non-declarative)
> fashion.
> 
> Here is the relevant tour mapper that makes the tour.first_sight
> connection:
> 
> tour_m = mapper(Tour, tours_t, {
>'first_sight': relation(Sight, primaryjoin=and_(
>tours_t.c.id == sights_t.c.tour_id,
>sights_t.c.parent_sight_id == None,
> sights_t.c.precedence==0),
>uselist=False),
>#.. more stuff
> })
> 
> Here is the relevant image mapper that makes the first_sight.image
> connection:
> 
> image_m = mapper(Image, images_t, properties={
># Sights which use this image.
>'sights': relation(Sight, backref="image",
>primaryjoin=and_(
>images_t.c.id == sights_t.c.image_id,
>sights_t.c.tour_id == tours_t.c.id,
>tours_t.c.resource_state !=
> resource_states['REMOVED'])),
># More stuff ...
> })

OK well the abuse here is pulling in that "tours" table into the primary join 
between Image and Sight, with an attempt to limit Sight rows to those with 
particular tours.The mechanics of join() and related items can't 
intelligently deal with this out of context table - for example the join() call 
renders "tours" into the criterion but relies upon the fact that "tours" is 
already in the FROM clause from elsewhere.It mostly works by accident.

I.e. in SQL you wouldn't think of a JOIN like this:

SELECT * FROM image JOIN sights ON image.id=sights.image_id AND 
sights.tour_id=tour.id AND tours.state!='REMOVED'

the above query is wrong.  "tours" is not in the FROM clause correctly.

How would you write this query ?  Maybe like this:

SELECT * FROM image JOIN sights ON image.id=sights.image_id JOIN tour 
ON sights.tour_id=tour.id AND tours.state!='REMOVED'

SQLAlchemy works best when you think of things this way.

The way to get "tours" in there without it being part of the FROM is to use a 
subquery, such as with IN:

SELECT * FROM image JOIN sights ON image.id=sights.image_id AND 
sights.tour_id IN (SELECT tour.id FROM tours where tours.state!='REMOVED')

tour_subq = select([Tour.id]).where(Tour.state!='REMOVED')
class Image(Base):
id = Column(Integer, primary_key=True)
sights = relationship("Sight", backref="image",
primaryjoin=
and_(
id==Sight.image_id,
Sight.tour_id.in_(tour_subq)
)
)





> 
> 
> Here is the usage and error:
> 
 query = saquery(Tour).join(User, Tour.owner_id == 
 User.id).filter(and_(Tour.resource_state == 1, User.resource_state == 1, 
 Tour.published == 
 True)).order_by(Tour.last_changed_on.desc()).offset(0).limit(101)
 query = query.options(subqueryload_all('first_sight.image'))
 query.all()
> 2011-11-10 11:45:22,112 INFO  [sqlalchemy.engine.base.Engine]
> [MainThread] BEGIN (implicit)
> 2011-11-10 11:45:22,113 INFO  [sqlalchemy.engine.base.Engine]
> [MainThread] SELECT tours.id AS tours_id, tours.title AS tours_title,
> tours.summary AS tours_summary, tours.slug AS tours_slug,
> tours.owner_id AS tours_owner_id, tours.published AS tours_published,
> tours.created_on AS tours_created_on, tours.resource_state AS
> tours_resource_state, tours.past_tour_id AS tours_past_tour_id,
> tours.published_on AS tours_published_on, tours.modified_on AS
> tours_modified_on, tours.last_changed_on AS tours_last_changed_on,
> tours.region_id AS tours_region_id
> FROM tours JOIN users ON tours.owner_id = users.id
> WHERE tours.resource_state = %(resource_state_1)s AND
> users.resource_state = %(resource_state_2)s AND tours.published = %
> (published_1)s ORDER BY tours.last_changed_on DESC
> LIMIT %(param_1)s OFFSET %(param_2)s
> 2011-11-10 11:45:22,113 INFO  [sqlalchemy.engine.base.Engine]
> [MainThread] {'param_2': 0, 'param_1': 101, 'published_1': True,
> 'resource_state_1': 1, 'resource_state_2': 1}
> 2011-11-10 11:45:22,119 INFO  [sqlalchemy.engine.base.Engine]
> [MainThread] SELECT sights.id AS sights_id, sights.title AS
> sights_title, sights.summary AS sights_summary, sights.old_scene_id AS
> sights_old_scene_id, sights.x1_coordinate AS sights_x1_coordinate,
> sights.y1_coordinate AS sights_y1_coordina

Re: [sqlalchemy] default NULL

2011-11-10 Thread Michael Bayer

On Nov 10, 2011, at 2:09 AM, lestat wrote:

> How I can add default NULL for column?
> 
> class UserIp(db.Model, UnicodeMixin):
>__tablename__ = 'user_ip'
> 
>user_id = db.Column(db.Integer, db.ForeignKey('user.id'),
> primary_key=True, nullable=True, server_default=None)
>ip = db.Column(postgres.CIDR, nullable=False,
> server_default='127.0.0.1/32')
>time_last = db.Column(db.DateTime, nullable=True,
> server_default=None)
> 
> I tried server_default=None, default=None, server_default='NULL', and
> it not works.

two things here:

1. time_last = Column(DateTime, nullable=True, server_default=text('NULL'))

2. all columns in a relational database default to NULL so not sure why you'd 
need to do this.

-- 
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] subqueryload problem

2011-11-10 Thread Ian Wilson
I'm not sure if this is a case of user error or what but I'm trying to
use a double sub-query load.  The odds are probably pretty good that
I'm doing something wrong.  I just finally got around to trying
subqueryload and I think it is what I've been looking for my entire
life.  Although the SQL being generated looks incorrect.

The big idea is that I have a list of tours, each tour has a bunch of
sights below it that all have images.  The tour itself does not have
an image.  I want to show all the tours with the image of the first
sight for that tour.  So I'm trying to fire off 3 queries, one to get
the tours, one to get the first sight of each tour, and one to get the
image of each first sight.

I'm using sqlalchemy 0.7.3 in the imperative?(non-declarative)
fashion.

Here is the relevant tour mapper that makes the tour.first_sight
connection:

tour_m = mapper(Tour, tours_t, {
'first_sight': relation(Sight, primaryjoin=and_(
tours_t.c.id == sights_t.c.tour_id,
sights_t.c.parent_sight_id == None,
sights_t.c.precedence==0),
uselist=False),
#.. more stuff
})

Here is the relevant image mapper that makes the first_sight.image
connection:

image_m = mapper(Image, images_t, properties={
# Sights which use this image.
'sights': relation(Sight, backref="image",
primaryjoin=and_(
images_t.c.id == sights_t.c.image_id,
sights_t.c.tour_id == tours_t.c.id,
tours_t.c.resource_state !=
resource_states['REMOVED'])),
# More stuff ...
})


Here is the usage and error:

>>> query = saquery(Tour).join(User, Tour.owner_id == 
>>> User.id).filter(and_(Tour.resource_state == 1, User.resource_state == 1, 
>>> Tour.published == 
>>> True)).order_by(Tour.last_changed_on.desc()).offset(0).limit(101)
>>> query = query.options(subqueryload_all('first_sight.image'))
>>> query.all()
2011-11-10 11:45:22,112 INFO  [sqlalchemy.engine.base.Engine]
[MainThread] BEGIN (implicit)
2011-11-10 11:45:22,113 INFO  [sqlalchemy.engine.base.Engine]
[MainThread] SELECT tours.id AS tours_id, tours.title AS tours_title,
tours.summary AS tours_summary, tours.slug AS tours_slug,
tours.owner_id AS tours_owner_id, tours.published AS tours_published,
tours.created_on AS tours_created_on, tours.resource_state AS
tours_resource_state, tours.past_tour_id AS tours_past_tour_id,
tours.published_on AS tours_published_on, tours.modified_on AS
tours_modified_on, tours.last_changed_on AS tours_last_changed_on,
tours.region_id AS tours_region_id
FROM tours JOIN users ON tours.owner_id = users.id
WHERE tours.resource_state = %(resource_state_1)s AND
users.resource_state = %(resource_state_2)s AND tours.published = %
(published_1)s ORDER BY tours.last_changed_on DESC
 LIMIT %(param_1)s OFFSET %(param_2)s
2011-11-10 11:45:22,113 INFO  [sqlalchemy.engine.base.Engine]
[MainThread] {'param_2': 0, 'param_1': 101, 'published_1': True,
'resource_state_1': 1, 'resource_state_2': 1}
2011-11-10 11:45:22,119 INFO  [sqlalchemy.engine.base.Engine]
[MainThread] SELECT sights.id AS sights_id, sights.title AS
sights_title, sights.summary AS sights_summary, sights.old_scene_id AS
sights_old_scene_id, sights.x1_coordinate AS sights_x1_coordinate,
sights.y1_coordinate AS sights_y1_coordinate, sights.width AS
sights_width, sights.height AS sights_height, sights.precedence AS
sights_precedence, sights.old_highlight_description AS
sights_old_highlight_description,
sights.old_highlight_description_format AS
sights_old_highlight_description_format, sights.old_highlight_image_id
AS sights_old_highlight_image_id, sights.image_id AS sights_image_id,
sights.slice_image_id AS sights_slice_image_id, sights.parent_sight_id
AS sights_parent_sight_id, sights.tour_id AS sights_tour_id,
sights.subtour_id AS sights_subtour_id, sights.collection_page_id AS
sights_collection_page_id, anon_1.tours_id AS anon_1_tours_id
FROM (SELECT tours.id AS tours_id
FROM tours JOIN users ON tours.owner_id = users.id
WHERE tours.resource_state = %(resource_state_1)s AND
users.resource_state = %(resource_state_2)s AND tours.published = %
(published_1)s ORDER BY tours.last_changed_on DESC
 LIMIT %(param_1)s OFFSET %(param_2)s) AS anon_1 JOIN sights ON
anon_1.tours_id = sights.tour_id AND sights.parent_sight_id IS NULL
AND sights.precedence = %(precedence_1)s ORDER BY anon_1.tours_id
2011-11-10 11:45:22,119 INFO  [sqlalchemy.engine.base.Engine]
[MainThread] {'precedence_1': 0, 'param_1': 101, 'param_2': 0,
'published_1': True, 'resource_state_1': 1, 'resource_state_2': 1}
2011-11-10 11:45:22,121 INFO  [sqlalchemy.engine.base.Engine]
[MainThread] SELECT images.id AS images_id, images.url AS images_url,
images.title AS images_title, images.height AS images_height,
images.width AS images_width, images.owner_id AS images_owner_id,
images.resource_state AS images_resource_state, images.system AS
images_system, images.created_on AS images_created_on,
images.modified_on AS images_modified_on, sights_1.image_

Re: [sqlalchemy] Dynamic data member instrumentation with declarative

2011-11-10 Thread Mark Erbaugh

On Nov 10, 2011, at 12:57 PM, Michael Bayer wrote:

> 
> On Nov 10, 2011, at 9:34 AM, Mark Erbaugh wrote:
> 
>> I'm trying to use data from a sequence to add columns to a SQLAlchemy table 
>> created declaratively. Here's what I'm doing:
>> 
>> class Sizing(Base):
>>   __tablename__ = 'sizing'
>>   id = Column(Integer, primary_key=True)
>> 
>>   [...]
>> 
>> 
>> for name in ('column1', 'column2', 'column3', ...):
>>   x = Column(type_=Integer)
>>   x.name = name
>>   Sizing.__table__.append_column(x)
> 
> 
> that will just add the column to the table but won't map it.   the mapper 
> isn't aware of this operation.
> 
>> 
>> This works as far as creating the table in the database, i.e. viewing the 
>> database shows columns named column1, column2, column3, etc, but code like 
>> getattr(sizing, 'column1')  (sizing is an instance of Sizing) is failinging 
>> with a message "'Sizing' object has no attribute 'column1'"
>> 
>> While code like:
>> 
>> Sizing.colum1 = Column(Integer)
>> 
>> works, but
> 
> right so that hits the __setattr__ of the DeclarativeMeta class which 
> receives the Column object, checks it out, and assigns it correctly to the 
> mapper and table.
> 
>> 
>> Sizing.__dict__['column1'] = Column(Integer)
> 
> In general, you should never set attributes this way from the outside, that's 
> just a Python thing, as you're bypassing whatever attribute set mechanics may 
> be present on the target object.
> 
>> or
>> 
>> Sizing.__setattr__(Sizing, 'column1', Column(Integer))
> 
> this is not much different as again you're bypassing instrumentation that may 
> be available on the class.   Use the Python setattr() function instead:  
> setattr(Sizing, "name", object).


Thanks so much!

Mark

-- 
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] Dynamic data member instrumentation with declarative

2011-11-10 Thread Michael Bayer

On Nov 10, 2011, at 9:34 AM, Mark Erbaugh wrote:

> I'm trying to use data from a sequence to add columns to a SQLAlchemy table 
> created declaratively. Here's what I'm doing:
> 
> class Sizing(Base):
>__tablename__ = 'sizing'
>id = Column(Integer, primary_key=True)
> 
>[...]
> 
> 
> for name in ('column1', 'column2', 'column3', ...):
>x = Column(type_=Integer)
>x.name = name
>Sizing.__table__.append_column(x)


that will just add the column to the table but won't map it.   the mapper isn't 
aware of this operation.

> 
> This works as far as creating the table in the database, i.e. viewing the 
> database shows columns named column1, column2, column3, etc, but code like 
> getattr(sizing, 'column1')  (sizing is an instance of Sizing) is failinging 
> with a message "'Sizing' object has no attribute 'column1'"
> 
> While code like:
> 
> Sizing.colum1 = Column(Integer)
> 
> works, but

right so that hits the __setattr__ of the DeclarativeMeta class which receives 
the Column object, checks it out, and assigns it correctly to the mapper and 
table.

> 
> Sizing.__dict__['column1'] = Column(Integer)

In general, you should never set attributes this way from the outside, that's 
just a Python thing, as you're bypassing whatever attribute set mechanics may 
be present on the target object.

> or
> 
> Sizing.__setattr__(Sizing, 'column1', Column(Integer))

this is not much different as again you're bypassing instrumentation that may 
be available on the class.   Use the Python setattr() function instead:  
setattr(Sizing, "name", object).


-- 
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] Dynamic data member instrumentation with declarative

2011-11-10 Thread Mark Erbaugh
I'm trying to use data from a sequence to add columns to a SQLAlchemy table 
created declaratively. Here's what I'm doing:

class Sizing(Base):
__tablename__ = 'sizing'
id = Column(Integer, primary_key=True)

[...]


for name in ('column1', 'column2', 'column3', ...):
x = Column(type_=Integer)
x.name = name
Sizing.__table__.append_column(x)

This works as far as creating the table in the database, i.e. viewing the 
database shows columns named column1, column2, column3, etc, but code like 
getattr(sizing, 'column1')  (sizing is an instance of Sizing) is failinging 
with a message "'Sizing' object has no attribute 'column1'"

While code like:

Sizing.colum1 = Column(Integer)

works, but

Sizing.__dict__['column1'] = Column(Integer)
or

Sizing.__setattr__(Sizing, 'column1', Column(Integer))

fails

The reason I'm trying to use the sequence to create the colums is that data 
from the sequence containing the column names is used in other parts of the 
application and I'd like to maintain that data in just one place. It's okay if 
I have to rebuild the database when the columns in the sequence change.

Thanks,
Mark

-- 
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: sqlalchemy-migrate 0.7.2 released

2011-11-10 Thread Frédéric Bertolus
Hello,

I'm not an artist but I just tried to make a logo artwork for
SqlAlchemy-Migrate.

http://dev.elveos.org/sqlalchemy-migrate-logo/sql_alchemy_migrate.html

The logo is a reference to the swallow problem in "Monty Python and
the Holy Grail".


Fred
Elveos Developer
https://elveos.org


On 2 nov, 00:06, Jan Dittberner  wrote:
> -BEGIN PGP SIGNED MESSAGE-
> Hash: SHA256
>
> Hello,
>
> thanks to the work of a lot of contributors I can announce the new
> release 0.7.2 of sqlalchemy-migrate today. The release is available at
> PyPI and our project page [1].
>
> Starting with this release we use readthedocs.org to provide you with
> online documentation [2].
>
> We want to know about our users. I therefore wrote a mail [3] and hope
> for your feedback.
>
> Release Notes for sqlalchemy-migrate 0.7.2
> ==
>
> Changes since 0.7.1
> - ---
>
> - - support for SQLAlchemy 0.5.x has been dropped
> - - Python 2.6 is the minimum supported Python version
>
> Documentation
> *
>
> - - add credits for contributors
> - - add glossary
> - - improve advice on testing production changes
> - - improve Sphinx markup
> - - refine Database Schema Versioning texts, add example for
>   adding/droping columns (#104)
> - - add more developer related information
> - - use sphinxcontrib.issuetracker to link to Google Code issue tracker
>
> Features
> 
>
> - - improved PEP 8 compliance (#122)
> - - optionally number versions with timestamps instead of sequences
>   (partly pulled from Pete Keen)
> - - allow descriptions in SQL change script filenames (by Pete Keen)
> - - improved model generation
>
> Fixed Bugs
> **
>
> - - #83: api test downgrade/upgrade does not work with sql scripts
>   (pulled from Yuen Ho Wong)
> - - #105: passing a unicode string as the migrate repository fails (add
>   regression test)
> - - #113: make_update_script_for_model fails with AttributeError:
>   'SchemaDiff' object has no attribute 'colDiffs' (patch by Jeremy
>   Cantrell)
> - - #118: upgrade and downgrade functions are reversed when using the
>   command "make_update_script_for_model" (patch by Jeremy Cantrell)
> - - #121: manage.py should use the "if __name__=='__main__'" trick
> - - #123: column creation in make_update_script_for_model and required
>   API change (by Gabriel de Perthuis)
> - - #124: compare_model_to_db gets confused by sqlite_sequence (pulled
>   from Dustin J. Mitchell)
> - - #125: drop column does not work on persistent sqlite databases
>   (pulled from Benoît Allard)
> - - #128: table rename failure with sqlalchemy 0.7.x (patch by Mark
>    McLoughlin)
> - - #129: update documentation and help text (pulled from Yuen Ho Wong)
>
> Help Wanted
> ===
>
> - - Triage bugs on the issue tracker [4] and provide patches as
>   attachments or your own mercurial clones
>
> - - Improve documentation, provide useful best practice documents, FAQ
>   and more
>
> - - We would like to have some logo artwork (under a free license)
>   idealy as SVG. If you are a skilled graphics artists or know someone
>   who is please feel free to help.
>
> Credits
> ===
>
> Thanks for all contributors who made the release possible. People
> contributing patches are mentioned above. A list of contributors can
> be found at [5]. If you helped us in the past and miss your name there
> please tell us about your contribution and we will add you to the
> list.
>
> Thanks to all bug reporters and people giving valuable feedback to the
> migrate-users list and in #sqlalchemy-migrate on IRC.
>
> Best Regards,
> Jan Dittberner
>
> [1]  http://code.google.com/p/sqlalchemy-migrate/
> [2]  http://readthedocs.org/docs/sqlalchemy-migrate/en/v0.7.2/
> [3]  http://groups.google.com/group/migrate-users/msg/f8b3848d6d4ae8d9
> [4]  http://code.google.com/p/sqlalchemy-migrate/issues/list
> [5]  http://readthedocs.org/docs/sqlalchemy-migrate/en/v0.7.2/credits.html
>
> - --
> Jan Dittberner - Debian Developer
> GPG-key: 4096R/558FB8DD 2009-05-10
>          B2FF 1D95 CE8F 7A22 DF4C  F09B A73E 0055 558F 
> B8DDhttp://www.dittberner.info/
> -BEGIN PGP SIGNATURE-
> Version: GnuPG v1.4.11 (GNU/Linux)
>
> iQIcBAEBCAAGBQJOsHtgAAoJEKc+AFVVj7jdPZoQANDaUmu7OemRF3+ARoamEWNN
> 2J7qbYJQTvZSDTAWtEjvHG2fZr4YuJdtHhmBvJEYBPfZBnAWvQx9/AQ5o7L0FtEZ
> ADBLRejzvKFR9vnb6ywG5Qs3E/UqLycj6/BsQfzuX9uXS5/j4Vx5GTf4gbsxJIIB
> l+Ex4xHiEXlN31uf0qBGvI3RpfRLl50v0HCvC7CXxt+pmMnbZcgDkJ6uDVSoogle
> +ZWjPxTSlHbI8Pm1MB1Nc9O7XdxOh+46A7Dmtv32rRZrybfXX8O9u2gDoQ2/EGvp
> NGuPtYv6xBW6/immSU1Wco0+WZCAwka+lHNOxblwzhda8vwz8b3+jTkC3XjMG2Cs
> fM4CBKb/a3udA4Nek5RGSTD1efqiwQzNk8COnYTRVv9xjXh6dejhguY+zPKjPAGf
> Y9UEtG7Z7q4fhDA/3//As9hiAF3mv5S6CXxjw34MZobm+NkkhDIJf3NWEecvdwy6
> l4m/+L9RWotz2um63mXPWROnqRm6c19S78Is1OyUIAqIe09OLLRBEEW22gzoQiB7
> atZ4b4Al2NyLUCjIyF270WdNZv3JCW76oJo1wlLs+5iLiC328huRVL289fbdDU6w
> d0Tdy26bQ7ZxtfXEgoG95miZCBBEYGIFwcLPN+PghIdGLtJtTfBG2yazoqUN2gGz
> 9oWja8GyuYmC14oaCOrj
> =1Brd
> -END PGP SIGNA

[sqlalchemy] Re: sqlite and "database is locked" errors.

2011-11-10 Thread Matthew Newville
Michael,

Thanks!  Using create_engine(..., poolclass=SingletonThreadPool) works 
perfectly, though  create_engine(..., pool_threadlocal=True) still showed 
similar database is locked on 'session commit'

FWIW, I do have a single engine, connection, and session in the 
application, as with (now):

self.engine = create_engine('sqlite:///%s' % dbname, 
poolclass=SingletonThreadPool)
self.conn   = self.engine.connect()
self.session = sessionmaker(bind=self.engine)()
self.metadata =  MetaData(self.engine)
self.metadata.reflect()

I haven't been rigorous in checking that only one wxPython thread is using 
the connection, as the wx code has lots of wx.CallAfter() to allow 
callbacks from the networking library to call into wx code, which then 
might want to write into the database.   My suspicion is that this is the 
root cause of the issue.

Anyway, I very much appreciate the quick, helpful response and fantastic 
library.

--Matt 

-- 
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/-/20EJ6t8trqsJ.
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] default NULL

2011-11-10 Thread lestat
How I can add default NULL for column?

class UserIp(db.Model, UnicodeMixin):
__tablename__ = 'user_ip'

user_id = db.Column(db.Integer, db.ForeignKey('user.id'),
primary_key=True, nullable=True, server_default=None)
ip = db.Column(postgres.CIDR, nullable=False,
server_default='127.0.0.1/32')
time_last = db.Column(db.DateTime, nullable=True,
server_default=None)

I tried server_default=None, default=None, server_default='NULL', and
it not works.

I need that sqlalchemy generate create table with
"time_last" TIMESTAMP NULL DEFAULT NULL
instead
"time_last" TIMESTAMP NULL

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 
sqlalchemy+unsubscr...@googlegroups.com.
For more options, visit this group at 
http://groups.google.com/group/sqlalchemy?hl=en.



[sqlalchemy] UniqueConstraint with func

2011-11-10 Thread lestat
Can I add UniqueConstraint like this?


from sqlalchemy import func
from sqlalchemy.schema import UniqueConstraint
from sqlalchemy.dialects import postgres

class UserIp(db.Model):
__tablename__ = 'user_ip'

__table_args__ = (
UniqueConstraint('user_id', func.md5('ip')),
)

user_id = db.Column(db.Integer, db.ForeignKey('user.id'),
primary_key=True, default=None)
ip = db.Column(postgres.CIDR, nullable=False,
default='127.0.0.1/32')



It raise exception:

/usr/lib/python2.7/site-packages/flaskext/sqlalchemy.pyc in
__init__(self, name, bases, d)
465 def __init__(self, name, bases, d):
466 bind_key = d.pop('__bind_key__', None)
--> 467 DeclarativeMeta.__init__(self, name, bases, d)
468 if bind_key is not None:
469 self.__table__.info['bind_key'] = bind_key

/usr/lib/python2.7/site-packages/sqlalchemy/ext/declarative.pyc in
__init__(cls, classname, bases, dict_)
   1257 return type.__init__(cls, classname, bases, dict_)
   1258 else:
-> 1259 _as_declarative(cls, classname, cls.__dict__)
   1260 return type.__init__(cls, classname, bases, dict_)
   1261

/usr/lib/python2.7/site-packages/sqlalchemy/ext/declarative.pyc in
_as_declarative(cls, classname, dict_)
   1156 cls.__table__ = table = Table(tablename,
cls.metadata,
   1157   *(tuple(cols) +
tuple(args)),
-> 1158**table_kw)
   1159 else:
   1160 table = cls.__table__

/usr/lib/python2.7/site-packages/sqlalchemy/schema.pyc in __new__(cls,
*args, **kw)
267 metadata._add_table(name, schema, table)
268 try:
--> 269 table._init(name, metadata, *args, **kw)
270 table.dispatch.after_parent_attach(table,
metadata)
271 return table

/usr/lib/python2.7/site-packages/sqlalchemy/schema.pyc in _init(self,
name, metadata, *args, **kwargs)
342 # initialize all the column, etc. objects.  done after
reflection to
343 # allow user-overrides
--> 344 self._init_items(*args)
345
346 @property

/usr/lib/python2.7/site-packages/sqlalchemy/schema.pyc in
_init_items(self, *args)
 62 for item in args:
 63 if item is not None:
---> 64 item._set_parent_with_dispatch(self)
 65
 66 def get_children(self, **kwargs):

/usr/lib/python2.7/site-packages/sqlalchemy/events.pyc in
_set_parent_with_dispatch(self, parent)
228 def _set_parent_with_dispatch(self, parent):
229 self.dispatch.before_parent_attach(self, parent)
--> 230 self._set_parent(parent)
231 self.dispatch.after_parent_attach(self, parent)
232

/usr/lib/python2.7/site-packages/sqlalchemy/schema.pyc in
_set_parent(self, table)
   1827
   1828 def _set_parent(self, table):
-> 1829 ColumnCollectionMixin._set_parent(self, table)
   1830 Constraint._set_parent(self, table)
   1831

/usr/lib/python2.7/site-packages/sqlalchemy/schema.pyc in
_set_parent(self, table)
   1801 if isinstance(col, basestring):
   1802 col = table.c[col]
-> 1803 self.columns.add(col)
   1804
   1805 class ColumnCollectionConstraint(ColumnCollectionMixin,
Constraint):

/usr/lib/python2.7/site-packages/sqlalchemy/sql/expression.pyc in
add(self, column)
   2135
   2136 """
-> 2137 self[column.key] = column
   2138
   2139 def __delitem__(self, key):

AttributeError: 'Function' object has no attribute 'key'




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 
sqlalchemy+unsubscr...@googlegroups.com.
For more options, visit this group at 
http://groups.google.com/group/sqlalchemy?hl=en.