[sqlalchemy] Thread Safety

2020-07-20 Thread Praveen Kumar

Confirming some details re: thread safety ( I noticed older posts in this 
group on the topic... but they're quite old ) --

I'm using version 1.2.7, and can't upgrade. I understand that Connection 
and Transaction are not threadsafe.

Are Engine and QueuePool ( the default pool ) threadsafe ? Can you please 
confirm that Engine.execute() is threadsafe ?

Are there any thread-safety issues with any of the other pool classes 
included in the sqlalchemy.pool module ?

Thanks,

pk

-- 
SQLAlchemy - 
The Python SQL Toolkit and Object Relational Mapper

http://www.sqlalchemy.org/

To post example code, please provide an MCVE: Minimal, Complete, and Verifiable 
Example.  See  http://stackoverflow.com/help/mcve for a full description.
--- 
You received this message because you are subscribed to the Google Groups 
"sqlalchemy" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to sqlalchemy+unsubscr...@googlegroups.com.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/sqlalchemy/7853de23-85d7-416e-b70e-935a0bad12c4o%40googlegroups.com.


Re: [sqlalchemy] How to define metaclass for a class that extends from sqlalchemy declarative base ?

2013-08-26 Thread Praveen
The problem with using Mixins is that you need to know the definition of
columns already for creating the mixin class. What I am trying to do is
more like get the definition dynamically on the fly.Take a look at this:

def get_properties(tablename, map):
table_inspector = reflection.Inspector.from_engine(DB_ENGINE.connect())
table = Table(tablename, metadata)
table_inspector.reflecttable(table, None)
columns = []
for child in table.get_children():
if isinstance(child, Column):
column = list(child.base_columns)[0]
column.table = None
columns.append(column)
return dict([(map[column.key],  column) for column in columns])

class CustomDeclarativeMeta(DeclarativeMeta):
def __new__(cls, name, bases, attrs):
attrs.update(get_properties(attrs.get('__tablename__'),
attrs.get('__map__')))
return super(CustomDeclarativeMeta, cls).__new__(cls, name, bases,
attrs)

# Base = declarative_base(metaclass=CustomDeclarativeMeta)
Base = declarative_base()

class Enum_SampleBase):
__tablename__ = 'Enum_Sample'
__table_args__ = {'useexisting': True}
__metaclass__ = CustomDeclarativeMeta
__map__ = {'Id': 'id', 'Name': 'name', 'Description': 'description',
'IsActive': 'is_active'}

def __init__(self, id, name, description, is_active):
self.id = id
self.name = name
self.description = description
self.is_active = is_active

def __repr__(self):
return (%d, '%s', '%s', %r) % (self.id, self.name,
self.description, self.isactive)

Unfortunately, this isn't working. I want to declare column types by
getting them from a table that's already created in the database.



On Wed, Jul 3, 2013 at 11:11 AM, Michael Bayer mike...@zzzcomputing.comwrote:

 your metaclass must derive from the DeclarativeMeta class.

 Also, I disagree that you need this metaclass,  what you're trying to do
 is very easy using mixins, which are supported in version 0.6:
 http://docs.sqlalchemy.org/en/rel_0_6/orm/extensions/declarative.html#mixing-in-columns




 On Jul 3, 2013, at 12:44 AM, Ven Karri praveen.venk...@gmail.com wrote:

 I use: Python 2.6 and sqlalchemy 0.6.1

 This is what I am trying to do:

 from sqlalchemy.types import (
 Integer,
 String,
 Boolean
 )
 from sqlalchemy.ext.declarative import declarative_base

 Base = declarative_base()

 class SampleMeta(type):
 def __new__(cls, name, bases, attrs):
 attrs.update({   'id': Column('Id', Integer, primary_key=True),
 'name': Column('Name', String),
 'description': Column('Description', String),
 'is_active': Column('IsActive', Boolean)
 })
 return super(SampleMeta, cls).__new__(cls, name, bases, attrs)

 class Sample(Base):
 __tablename__ = 'Sample'
 __table_args__ = {'useexisting': True}
 __metaclass__ = SampleMeta

 def __init__(self, id, name, description, is_active):
 self.id = id
 self.name = name
 self.description = description
 self.is_active = is_active

 def __repr__(self):
 return (%d, '%s', '%s', %r) % (self.id, self.name,
 self.description, self.isactive)

 And the error I am getting is this:

 TypeError: Error when calling the metaclass bases
 metaclass conflict: the metaclass of a derived class must be a
 (non-strict) subclass of the metaclasses of all its bases

 Now, if I do the same thing above by using

 class Sample(object)

 instead of

 class Sample(Base)

 it works absolutely fine.

 I need to update the attributes of the class dynamically. So, I will be
 using dynamic attribute and column names. And I need the above piece code
 to work in order to be able to get there.

 **Please help**

 --
 You received this message because you are subscribed to the Google Groups
 sqlalchemy group.
 To unsubscribe from this group and stop receiving emails from it, send an
 email to sqlalchemy+unsubscr...@googlegroups.com.

 To post to this group, send email to sqlalchemy@googlegroups.com.
 Visit this group at http://groups.google.com/group/sqlalchemy.
 For more options, visit https://groups.google.com/groups/opt_out.




  --
 You received this message because you are subscribed to a topic in the
 Google Groups sqlalchemy group.
 To unsubscribe from this topic, visit
 https://groups.google.com/d/topic/sqlalchemy/37M-1Qf8HO8/unsubscribe.
 To unsubscribe from this group and all its topics, send an email to
 sqlalchemy+unsubscr...@googlegroups.com.
 To post to this group, send email to sqlalchemy@googlegroups.com.
 Visit this group at http://groups.google.com/group/sqlalchemy.
 For more options, visit https://groups.google.com/groups/opt_out.






-- 
Have a nice day !!!

-- 
You received this message because you are subscribed to the Google Groups 
sqlalchemy group.
To unsubscribe from 

Re: [sqlalchemy] How to define metaclass for a class that extends from sqlalchemy declarative base ?

2013-08-26 Thread Praveen
Sorry, it should've been:

class Enum_Sample(Base):

Typo.


On Mon, Aug 26, 2013 at 4:35 PM, Praveen praveen.venk...@gmail.com wrote:

 The problem with using Mixins is that you need to know the definition of
 columns already for creating the mixin class. What I am trying to do is
 more like get the definition dynamically on the fly.Take a look at this:

 def get_properties(tablename, map):
 table_inspector = reflection.Inspector.from_engine(DB_ENGINE.connect())
 table = Table(tablename, metadata)
 table_inspector.reflecttable(table, None)
 columns = []
 for child in table.get_children():
 if isinstance(child, Column):
 column = list(child.base_columns)[0]
 column.table = None
 columns.append(column)
 return dict([(map[column.key],  column) for column in columns])

 class CustomDeclarativeMeta(DeclarativeMeta):
 def __new__(cls, name, bases, attrs):
 attrs.update(get_properties(attrs.get('__tablename__'),
 attrs.get('__map__')))
 return super(CustomDeclarativeMeta, cls).__new__(cls, name, bases,
 attrs)

 # Base = declarative_base(metaclass=CustomDeclarativeMeta)
 Base = declarative_base()

 class Enum_SampleBase):
 __tablename__ = 'Enum_Sample'
 __table_args__ = {'useexisting': True}
 __metaclass__ = CustomDeclarativeMeta
 __map__ = {'Id': 'id', 'Name': 'name', 'Description': 'description',
 'IsActive': 'is_active'}

 def __init__(self, id, name, description, is_active):
 self.id = id
 self.name = name
 self.description = description
 self.is_active = is_active

 def __repr__(self):
 return (%d, '%s', '%s', %r) % (self.id, self.name,
 self.description, self.isactive)

 Unfortunately, this isn't working. I want to declare column types by
 getting them from a table that's already created in the database.



 On Wed, Jul 3, 2013 at 11:11 AM, Michael Bayer 
 mike...@zzzcomputing.comwrote:

 your metaclass must derive from the DeclarativeMeta class.

 Also, I disagree that you need this metaclass,  what you're trying to do
 is very easy using mixins, which are supported in version 0.6:
 http://docs.sqlalchemy.org/en/rel_0_6/orm/extensions/declarative.html#mixing-in-columns




 On Jul 3, 2013, at 12:44 AM, Ven Karri praveen.venk...@gmail.com wrote:

 I use: Python 2.6 and sqlalchemy 0.6.1

 This is what I am trying to do:

 from sqlalchemy.types import (
 Integer,
 String,
 Boolean
 )
  from sqlalchemy.ext.declarative import declarative_base

 Base = declarative_base()

 class SampleMeta(type):
 def __new__(cls, name, bases, attrs):
 attrs.update({   'id': Column('Id', Integer,
 primary_key=True),
 'name': Column('Name', String),
 'description': Column('Description', String),
 'is_active': Column('IsActive', Boolean)
 })
 return super(SampleMeta, cls).__new__(cls, name, bases, attrs)

 class Sample(Base):
 __tablename__ = 'Sample'
 __table_args__ = {'useexisting': True}
 __metaclass__ = SampleMeta

 def __init__(self, id, name, description, is_active):
 self.id = id
 self.name = name
 self.description = description
 self.is_active = is_active

 def __repr__(self):
 return (%d, '%s', '%s', %r) % (self.id, self.name,
 self.description, self.isactive)

 And the error I am getting is this:

 TypeError: Error when calling the metaclass bases
 metaclass conflict: the metaclass of a derived class must be a
 (non-strict) subclass of the metaclasses of all its bases

 Now, if I do the same thing above by using

 class Sample(object)

 instead of

 class Sample(Base)

 it works absolutely fine.

 I need to update the attributes of the class dynamically. So, I will be
 using dynamic attribute and column names. And I need the above piece code
 to work in order to be able to get there.

 **Please help**

 --
 You received this message because you are subscribed to the Google Groups
 sqlalchemy group.
 To unsubscribe from this group and stop receiving emails from it, send an
 email to sqlalchemy+unsubscr...@googlegroups.com.

 To post to this group, send email to sqlalchemy@googlegroups.com.
 Visit this group at http://groups.google.com/group/sqlalchemy.
 For more options, visit https://groups.google.com/groups/opt_out.




  --
 You received this message because you are subscribed to a topic in the
 Google Groups sqlalchemy group.
 To unsubscribe from this topic, visit
 https://groups.google.com/d/topic/sqlalchemy/37M-1Qf8HO8/unsubscribe.
 To unsubscribe from this group and all its topics, send an email to
 sqlalchemy+unsubscr...@googlegroups.com.
 To post to this group, send email to sqlalchemy@googlegroups.com.
 Visit this group at http://groups.google.com/group/sqlalchemy.
 For more options, visit https

Re: [sqlalchemy] How to define metaclass for a class that extends from sqlalchemy declarative base ?

2013-08-26 Thread Praveen
Does this work in sqlalchemy 0.6.1 ?


On Mon, Aug 26, 2013 at 5:36 PM, Michael Bayer mike...@zzzcomputing.comwrote:

 OK here we are, had to switch approaches due to a bug with the column
 reflect event, to use the aforementioned __mapper_cls__ (had the name
 wrong), so I think you'll see this is a pretty open-ended way to control
 how something maps as you're given total access to mapper() here:

 from sqlalchemy import *
 from sqlalchemy.orm import *
 from sqlalchemy.ext.declarative import declarative_base, declared_attr
 from sqlalchemy.ext.declarative import DeferredReflection
 from sqlalchemy import event

 Base = declarative_base()

 e = create_engine(sqlite://, echo=True)
 e.execute(
 create table sample (
 Id integer primary key,
 Name varchar,
 Description varchar,
 IsActive varchar
 )
 )

 class MagicMappyThing(DeferredReflection):
 @declared_attr
 def __mapper_cls__(cls):
 def map_(cls, *arg, **kw):
 props = kw.setdefault(properties, {})
 for k, v in cls.__map__.items():
 props[v] = cls.__table__.c[k]
 return mapper(cls, *arg, **kw)
 return map_

 class Sample(MagicMappyThing, Base):
 __tablename__ = 'sample'
 __map__ = {'Id': 'id', 'Name': 'name', 'Description': 'description',
 'IsActive': 'is_active'}

 def __init__(self, id, name, description, is_active):
 self.id = id
 self.name = name
 self.description = description
 self.is_active = is_active

 MagicMappyThing.prepare(e)

 s = Session(e)

 s.add(Sample(id=1, name='some name', description='foo', is_active='foo'))
 s.commit()




 On Aug 26, 2013, at 5:17 PM, Michael Bayer mike...@zzzcomputing.com
 wrote:


 On Aug 26, 2013, at 5:16 PM, Michael Bayer mike...@zzzcomputing.com
 wrote:


 On Aug 26, 2013, at 4:35 PM, Praveen praveen.venk...@gmail.com wrote:

 The problem with using Mixins is that you need to know the definition of
 columns already for creating the mixin class. What I am trying to do is
 more like get the definition dynamically on the fly.Take a look at this:


 here's a simple way to add reflection events which intercept the Column
 and add the .key of your choice, and saves on code by making use of the
 existing DeferredReflection mixin instead of hand-coding it.


 except it doesnt work yet, give me 10 minutes.





-- 
Have a nice day !!!

-- 
You received this message because you are subscribed to the Google Groups 
sqlalchemy group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to sqlalchemy+unsubscr...@googlegroups.com.
To post to this group, send email to sqlalchemy@googlegroups.com.
Visit this group at http://groups.google.com/group/sqlalchemy.
For more options, visit https://groups.google.com/groups/opt_out.


Re: [sqlalchemy] How to define metaclass for a class that extends from sqlalchemy declarative base ?

2013-08-26 Thread Praveen
I am getting ImportError for the following:

from sqlalchemy.ext.declarative import DeferredReflection
from sqlalchemy import event

I use sqlalchemy 0.6.1. Is there any way I can make it work in 0.6.1 ?


On Mon, Aug 26, 2013 at 5:38 PM, Praveen praveen.venk...@gmail.com wrote:

 Does this work in sqlalchemy 0.6.1 ?


 On Mon, Aug 26, 2013 at 5:36 PM, Michael Bayer 
 mike...@zzzcomputing.comwrote:

 OK here we are, had to switch approaches due to a bug with the column
 reflect event, to use the aforementioned __mapper_cls__ (had the name
 wrong), so I think you'll see this is a pretty open-ended way to control
 how something maps as you're given total access to mapper() here:

 from sqlalchemy import *
 from sqlalchemy.orm import *
 from sqlalchemy.ext.declarative import declarative_base, declared_attr
 from sqlalchemy.ext.declarative import DeferredReflection
 from sqlalchemy import event

 Base = declarative_base()

 e = create_engine(sqlite://, echo=True)
 e.execute(
 create table sample (
 Id integer primary key,
 Name varchar,
 Description varchar,
 IsActive varchar
 )
 )

 class MagicMappyThing(DeferredReflection):
 @declared_attr
 def __mapper_cls__(cls):
 def map_(cls, *arg, **kw):
 props = kw.setdefault(properties, {})
 for k, v in cls.__map__.items():
 props[v] = cls.__table__.c[k]
 return mapper(cls, *arg, **kw)
 return map_

 class Sample(MagicMappyThing, Base):
 __tablename__ = 'sample'
 __map__ = {'Id': 'id', 'Name': 'name', 'Description': 'description',
 'IsActive': 'is_active'}

 def __init__(self, id, name, description, is_active):
 self.id = id
 self.name = name
 self.description = description
 self.is_active = is_active

 MagicMappyThing.prepare(e)

 s = Session(e)

 s.add(Sample(id=1, name='some name', description='foo', is_active='foo'))
 s.commit()




 On Aug 26, 2013, at 5:17 PM, Michael Bayer mike...@zzzcomputing.com
 wrote:


 On Aug 26, 2013, at 5:16 PM, Michael Bayer mike...@zzzcomputing.com
 wrote:


 On Aug 26, 2013, at 4:35 PM, Praveen praveen.venk...@gmail.com wrote:

 The problem with using Mixins is that you need to know the definition of
 columns already for creating the mixin class. What I am trying to do is
 more like get the definition dynamically on the fly.Take a look at this:


 here's a simple way to add reflection events which intercept the Column
 and add the .key of your choice, and saves on code by making use of the
 existing DeferredReflection mixin instead of hand-coding it.


 except it doesnt work yet, give me 10 minutes.





 --
 Have a nice day !!!




-- 
Have a nice day !!!

-- 
You received this message because you are subscribed to the Google Groups 
sqlalchemy group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to sqlalchemy+unsubscr...@googlegroups.com.
To post to this group, send email to sqlalchemy@googlegroups.com.
Visit this group at http://groups.google.com/group/sqlalchemy.
For more options, visit https://groups.google.com/groups/opt_out.


Re: [sqlalchemy] How to define metaclass for a class that extends from sqlalchemy declarative base ?

2013-08-26 Thread Praveen
Could you please point me to the link where I can find the example ?


On Mon, Aug 26, 2013 at 5:41 PM, Michael Bayer mike...@zzzcomputing.comwrote:

 you'd need to hand-roll the deferred reflection part, there's an example
 in 0.7 called declarative_reflection but it might require features that
 aren't in 0.6.

 I'd not be looking to add any kind of slick/magic systems to an 0.6 app,
 0.6 is very early in the curve for declarative techniques.  upgrade it
 first, otherwise stick with the hacky approaches you have.



 On Aug 26, 2013, at 5:38 PM, Praveen praveen.venk...@gmail.com wrote:

 Does this work in sqlalchemy 0.6.1 ?


 On Mon, Aug 26, 2013 at 5:36 PM, Michael Bayer 
 mike...@zzzcomputing.comwrote:

 OK here we are, had to switch approaches due to a bug with the column
 reflect event, to use the aforementioned __mapper_cls__ (had the name
 wrong), so I think you'll see this is a pretty open-ended way to control
 how something maps as you're given total access to mapper() here:

 from sqlalchemy import *
 from sqlalchemy.orm import *
 from sqlalchemy.ext.declarative import declarative_base, declared_attr
 from sqlalchemy.ext.declarative import DeferredReflection
 from sqlalchemy import event

 Base = declarative_base()

 e = create_engine(sqlite://, echo=True)
 e.execute(
 create table sample (
 Id integer primary key,
 Name varchar,
 Description varchar,
 IsActive varchar
 )
 )

 class MagicMappyThing(DeferredReflection):
 @declared_attr
 def __mapper_cls__(cls):
 def map_(cls, *arg, **kw):
 props = kw.setdefault(properties, {})
 for k, v in cls.__map__.items():
 props[v] = cls.__table__.c[k]
 return mapper(cls, *arg, **kw)
 return map_

 class Sample(MagicMappyThing, Base):
 __tablename__ = 'sample'
 __map__ = {'Id': 'id', 'Name': 'name', 'Description': 'description',
 'IsActive': 'is_active'}

 def __init__(self, id, name, description, is_active):
 self.id = id
 self.name = name
 self.description = description
 self.is_active = is_active

 MagicMappyThing.prepare(e)

 s = Session(e)

 s.add(Sample(id=1, name='some name', description='foo', is_active='foo'))
 s.commit()




 On Aug 26, 2013, at 5:17 PM, Michael Bayer mike...@zzzcomputing.com
 wrote:


 On Aug 26, 2013, at 5:16 PM, Michael Bayer mike...@zzzcomputing.com
 wrote:


 On Aug 26, 2013, at 4:35 PM, Praveen praveen.venk...@gmail.com wrote:

 The problem with using Mixins is that you need to know the definition of
 columns already for creating the mixin class. What I am trying to do is
 more like get the definition dynamically on the fly.Take a look at this:


 here's a simple way to add reflection events which intercept the Column
 and add the .key of your choice, and saves on code by making use of the
 existing DeferredReflection mixin instead of hand-coding it.


 except it doesnt work yet, give me 10 minutes.





 --
 Have a nice day !!!

 --
 You received this message because you are subscribed to the Google Groups
 sqlalchemy group.
 To unsubscribe from this group and stop receiving emails from it, send an
 email to sqlalchemy+unsubscr...@googlegroups.com.
 To post to this group, send email to sqlalchemy@googlegroups.com.
 Visit this group at http://groups.google.com/group/sqlalchemy.
 For more options, visit https://groups.google.com/groups/opt_out.





-- 
Have a nice day !!!

-- 
You received this message because you are subscribed to the Google Groups 
sqlalchemy group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to sqlalchemy+unsubscr...@googlegroups.com.
To post to this group, send email to sqlalchemy@googlegroups.com.
Visit this group at http://groups.google.com/group/sqlalchemy.
For more options, visit https://groups.google.com/groups/opt_out.


Re: [sqlalchemy] How to define metaclass for a class that extends from sqlalchemy declarative base ?

2013-08-26 Thread Praveen
nvm... i found it.


On Mon, Aug 26, 2013 at 5:46 PM, Praveen praveen.venk...@gmail.com wrote:

 Could you please point me to the link where I can find the example ?


 On Mon, Aug 26, 2013 at 5:41 PM, Michael Bayer 
 mike...@zzzcomputing.comwrote:

 you'd need to hand-roll the deferred reflection part, there's an example
 in 0.7 called declarative_reflection but it might require features that
 aren't in 0.6.

 I'd not be looking to add any kind of slick/magic systems to an 0.6 app,
 0.6 is very early in the curve for declarative techniques.  upgrade it
 first, otherwise stick with the hacky approaches you have.



 On Aug 26, 2013, at 5:38 PM, Praveen praveen.venk...@gmail.com wrote:

 Does this work in sqlalchemy 0.6.1 ?


 On Mon, Aug 26, 2013 at 5:36 PM, Michael Bayer 
 mike...@zzzcomputing.comwrote:

 OK here we are, had to switch approaches due to a bug with the column
 reflect event, to use the aforementioned __mapper_cls__ (had the name
 wrong), so I think you'll see this is a pretty open-ended way to control
 how something maps as you're given total access to mapper() here:

 from sqlalchemy import *
 from sqlalchemy.orm import *
 from sqlalchemy.ext.declarative import declarative_base, declared_attr
 from sqlalchemy.ext.declarative import DeferredReflection
 from sqlalchemy import event

 Base = declarative_base()

 e = create_engine(sqlite://, echo=True)
 e.execute(
 create table sample (
 Id integer primary key,
 Name varchar,
 Description varchar,
 IsActive varchar
 )
 )

 class MagicMappyThing(DeferredReflection):
 @declared_attr
 def __mapper_cls__(cls):
 def map_(cls, *arg, **kw):
 props = kw.setdefault(properties, {})
 for k, v in cls.__map__.items():
 props[v] = cls.__table__.c[k]
 return mapper(cls, *arg, **kw)
 return map_

 class Sample(MagicMappyThing, Base):
 __tablename__ = 'sample'
 __map__ = {'Id': 'id', 'Name': 'name', 'Description': 'description',
 'IsActive': 'is_active'}

 def __init__(self, id, name, description, is_active):
 self.id = id
 self.name = name
 self.description = description
 self.is_active = is_active

 MagicMappyThing.prepare(e)

 s = Session(e)

 s.add(Sample(id=1, name='some name', description='foo', is_active='foo'))
 s.commit()




 On Aug 26, 2013, at 5:17 PM, Michael Bayer mike...@zzzcomputing.com
 wrote:


 On Aug 26, 2013, at 5:16 PM, Michael Bayer mike...@zzzcomputing.com
 wrote:


 On Aug 26, 2013, at 4:35 PM, Praveen praveen.venk...@gmail.com wrote:

 The problem with using Mixins is that you need to know the definition of
 columns already for creating the mixin class. What I am trying to do is
 more like get the definition dynamically on the fly.Take a look at this:


 here's a simple way to add reflection events which intercept the Column
 and add the .key of your choice, and saves on code by making use of the
 existing DeferredReflection mixin instead of hand-coding it.


 except it doesnt work yet, give me 10 minutes.





 --
 Have a nice day !!!

 --
 You received this message because you are subscribed to the Google Groups
 sqlalchemy group.
 To unsubscribe from this group and stop receiving emails from it, send an
 email to sqlalchemy+unsubscr...@googlegroups.com.
 To post to this group, send email to sqlalchemy@googlegroups.com.
 Visit this group at http://groups.google.com/group/sqlalchemy.
 For more options, visit https://groups.google.com/groups/opt_out.





 --
 Have a nice day !!!




-- 
Have a nice day !!!

-- 
You received this message because you are subscribed to the Google Groups 
sqlalchemy group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to sqlalchemy+unsubscr...@googlegroups.com.
To post to this group, send email to sqlalchemy@googlegroups.com.
Visit this group at http://groups.google.com/group/sqlalchemy.
For more options, visit https://groups.google.com/groups/opt_out.


Re: [sqlalchemy] How to define metaclass for a class that extends from sqlalchemy declarative base ?

2013-08-26 Thread Praveen
I tried your example in sqlalchemy 0.6 by manually plugging in api.py
library (attached) that I got from
herehttps://bitbucket.org/miracle2k/sqlalchemy/src/2d28ed97d3221a133b4b297a229deb294088affe/lib/sqlalchemy/ext/declarative/api.py?at=default
.

I get this error:

File path\to\sample_orm.py, line 33, in map_
props[v] = cls.__table__.c[k]
  File path\to\lib\python2.6\sqlalchemy\util.py, line 731, in __getitem__

KeyError: 'Description'


Here's my code:

from sqlalchemy.orm import mapper
from sqlalchemy import create_engine
from sqlalchemy.ext.declarative import declarative_base
from .api import DeferredReflection, declared_attr -- this is coming from
attached api.py file

Base = declarative_base()

e = create_engine(sqlite://, echo=True)
e.execute(
create table Sample (
Id integer primary key,
Name varchar,
Description varchar,
IsActive varchar
)
)

class MagicMappyThing(DeferredReflection):
@declared_attr
def __mapper_cls__(cls):
def map_(cls, *arg, **kw):
props = kw.setdefault(properties, {})
for k, v in cls.__map__.items():
props[v] = cls.__table__.c[k]
return mapper(cls, *arg, **kw)
return map_

class Sample(MagicMappyThing, Base):
__tablename__ = 'Sample'
__map__ = {'Id': 'id', 'Name': 'name', 'Description': 'description',
'IsActive': 'is_active'}

def __init__(self, id, name, description, is_active):
self.id = id
self.name = name
self.description = description
self.is_active = is_active

MagicMappyThing.prepare(e)

# s = Session(e)

# s.add(Sample(id=1, name='some name', description='foo', is_active='foo'))
# s.commit()


On Mon, Aug 26, 2013 at 5:52 PM, Praveen praveen.venk...@gmail.com wrote:

 It works only in 0.7 like you said. I can't find any way to crack this
 situation in 0.6. :-(


 On Mon, Aug 26, 2013 at 5:49 PM, Praveen praveen.venk...@gmail.comwrote:

 nvm... i found it.


 On Mon, Aug 26, 2013 at 5:46 PM, Praveen praveen.venk...@gmail.comwrote:

 Could you please point me to the link where I can find the example ?


 On Mon, Aug 26, 2013 at 5:41 PM, Michael Bayer mike...@zzzcomputing.com
  wrote:

 you'd need to hand-roll the deferred reflection part, there's an
 example in 0.7 called declarative_reflection but it might require
 features that aren't in 0.6.

 I'd not be looking to add any kind of slick/magic systems to an 0.6
 app, 0.6 is very early in the curve for declarative techniques.  upgrade it
 first, otherwise stick with the hacky approaches you have.



 On Aug 26, 2013, at 5:38 PM, Praveen praveen.venk...@gmail.com wrote:

 Does this work in sqlalchemy 0.6.1 ?


 On Mon, Aug 26, 2013 at 5:36 PM, Michael Bayer 
 mike...@zzzcomputing.com wrote:

 OK here we are, had to switch approaches due to a bug with the column
 reflect event, to use the aforementioned __mapper_cls__ (had the name
 wrong), so I think you'll see this is a pretty open-ended way to control
 how something maps as you're given total access to mapper() here:

 from sqlalchemy import *
 from sqlalchemy.orm import *
 from sqlalchemy.ext.declarative import declarative_base, declared_attr
 from sqlalchemy.ext.declarative import DeferredReflection
 from sqlalchemy import event

 Base = declarative_base()

 e = create_engine(sqlite://, echo=True)
 e.execute(
 create table sample (
 Id integer primary key,
 Name varchar,
 Description varchar,
 IsActive varchar
 )
 )

 class MagicMappyThing(DeferredReflection):
 @declared_attr
 def __mapper_cls__(cls):
 def map_(cls, *arg, **kw):
 props = kw.setdefault(properties, {})
 for k, v in cls.__map__.items():
 props[v] = cls.__table__.c[k]
 return mapper(cls, *arg, **kw)
 return map_

 class Sample(MagicMappyThing, Base):
 __tablename__ = 'sample'
 __map__ = {'Id': 'id', 'Name': 'name', 'Description':
 'description', 'IsActive': 'is_active'}

 def __init__(self, id, name, description, is_active):
 self.id = id
 self.name = name
 self.description = description
 self.is_active = is_active

 MagicMappyThing.prepare(e)

 s = Session(e)

 s.add(Sample(id=1, name='some name', description='foo',
 is_active='foo'))
 s.commit()




 On Aug 26, 2013, at 5:17 PM, Michael Bayer mike...@zzzcomputing.com
 wrote:


 On Aug 26, 2013, at 5:16 PM, Michael Bayer mike...@zzzcomputing.com
 wrote:


 On Aug 26, 2013, at 4:35 PM, Praveen praveen.venk...@gmail.com
 wrote:

 The problem with using Mixins is that you need to know the definition
 of columns already for creating the mixin class. What I am trying to do is
 more like get the definition dynamically on the fly.Take a look at this:


 here's a simple way to add reflection events which intercept the
 Column and add the .key of your choice, and saves on code by making use of
 the existing DeferredReflection mixin instead

[sqlalchemy] Update from select via SqlAclchemy session query or Expression Language

2012-10-12 Thread Praveen
Hello,

I have below use where

Employer and EmployerPhone the one emp can have multiple phone number out 
of which at any given point of time there should be 
only one 'is_active' due to concurrency load, emp_phone got multiple 
'is_active' as 'Y' in emp_phone i want to update the emp_phone table
records to have only is_active record for a given emp.  I tried out query 
and Expression Language to fix this, but i am not lucky enough to fix this. 

Could anyone suggest me to write query in SqlAlchemy to fix this issue.

I have also attached sample python file which i tried with SqlLite.


from sqlalchemy import *
from sqlalchemy.orm import sessionmaker, mapper

#Actual use case is with SQL Server 2008 and Oracle
#uri = mssql+mxodbc://sa:sa@master
#engine = create_engine(uri)

#Tried with SQL Lite
engine = create_engine('sqlite:///:memory:', echo=True)
session = sessionmaker(bind=engine)
session = session()

#Define tables
metadata = MetaData()

emp = Table(emp, metadata,
Column(emp_idn, Integer, primary_key=True, 
autoincrement=True),
Column(emp_name, String),
Column(is_active, String),
)
emp_phone = Table(emp_phone, metadata,
Column(phone_no, String),
Column(emp_phone_idn, Integer, primary_key=True, autoincrement=True),
Column(emp_idn, Float, ForeignKey('emp.emp_idn')),
Column(is_active, String))

metadata.create_all(engine)

#Define model.
class Emp(object):
pass

class EmpPhone(object):
pass

#mapping...
mapper(Emp, emp)
mapper(EmpPhone, emp_phone)

#My goal is to Use Session to create Emp and Emp Phone.
emp = Emp()
emp.emp_name = 'Royal'
emp.is_active = 'Y'
session.add(emp)
session.flush()

emp = Emp()
emp.emp_name = 'Royal Eng'
emp.is_active = 'Y'
session.add(emp)
session.flush()

empPhone = EmpPhone()
empPhone.emp_idn = emp.emp_idn
empPhone.phone_no = '12345'
empPhone.is_active = 'Y'
session.add(empPhone)
session.flush()

empPhone = EmpPhone()
empPhone.emp_idn = emp.emp_idn
empPhone.phone_no = '67890'
empPhone.is_active = 'Y'
session.add(empPhone)
session.flush()


#Update all the Duplicate is_active records with 'N' which are duplicted 
per emp_idn
#There should be only one active phone number per emp
sub_qry = session.query(EmpPhone.emp_idn).filter(EmpPhone.is_active=='Y')
sub_qry = sub_qry.group_by(EmpPhone.emp_idn)
sub_qry = sub_qry.having(func.count(EmpPhone.emp_idn)  1)
upd_qry = 
session.query(EmpPhone).filter(EmpPhone.emp_idn.in_(sub_qry)).update({'is_active':
 
'N'}, False)

session.commit()
for each in session.query(EmpPhone).all():
print each.emp_idn, each.phone_no, each.is_active

##My Goal is to update the emp_phone records having multiple is_active to 
have
##only once is_active as 'Y' based on last loaded record for one employee.
##I figured out raw sql, how ever i am not able get this done in SQ Query 
or SQ expression langauge.

#Raw SQL#  SQ Query or SQ expression langauge
#Update emp_phone set is_active='Y' 
#from emp_phone b inner join (
#Select emp_idn, max(emp_phone_idn) max_emp_phone_idn from emp_phone group 
by emp_idn) 
#a on a.max_emp_phone_idn =b.phone_num_idn
#Raw SQL#





Thanks in advance,

Praveen

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

from sqlalchemy import *
from sqlalchemy.orm import sessionmaker, mapper

#Actual use case is with SQL Server 2008 and Oracle
#uri = mssql+mxodbc://sa:sa@master
#engine = create_engine(uri)

#Tried with SQL Lite
engine = create_engine('sqlite:///:memory:', echo=True)
session = sessionmaker(bind=engine)
session = session()

#Define tables
metadata = MetaData()

emp = Table(emp, metadata,
Column(emp_idn, Integer, primary_key=True, autoincrement=True),
Column(emp_name, String),
Column(is_active, String),
)
emp_phone = Table(emp_phone, metadata,
Column(phone_no, String),
Column(emp_phone_idn, Integer, primary_key=True, autoincrement=True),
Column(emp_idn, Float, ForeignKey('emp.emp_idn')),
Column(is_active, String))

metadata.create_all(engine)

#Define model.
class Emp(object):
pass

class EmpPhone(object):
pass

#mapping...
mapper(Emp, emp)
mapper(EmpPhone, emp_phone)

#My goal is to Use Session to create Emp and Emp Phone.
emp = Emp()
emp.emp_name = 'Royal'
emp.is_active = 'Y'
session.add(emp)
session.flush()

emp = Emp()
emp.emp_name = 'Royal Eng'
emp.is_active = 'Y'
session.add(emp)
session.flush()

empPhone = EmpPhone()
empPhone.emp_idn = emp.emp_idn
empPhone.phone_no = '12345'
empPhone.is_active = 'Y