[sqlalchemy] Alembic. Can i pass upgrades and downgrade directly from alembic.command.revision?

2019-04-15 Thread Tolstov Sergey
If i create migrations on GUI (browser), how can i pass upgrades/downgrades?

-- 
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 post to this group, send email to sqlalchemy@googlegroups.com.
Visit this group at https://groups.google.com/group/sqlalchemy.
For more options, visit https://groups.google.com/d/optout.


Re: [sqlalchemy] Custom Handler for "No such polymorphic_identity"

2019-03-12 Thread Tolstov Sergey
Addition. 
 If i create all possible classes i may get a low perfomance (rel to root 
class)

-- 
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 post to this group, send email to sqlalchemy@googlegroups.com.
Visit this group at https://groups.google.com/group/sqlalchemy.
For more options, visit https://groups.google.com/d/optout.


Re: [sqlalchemy] Custom Handler for "No such polymorphic_identity"

2019-03-12 Thread Tolstov Sergey
Thanks for answer.
Problem is too much loading time (~40 seconds) if i use standart 
declaration.

To resolve this, 
i define classes when they called (write class factory), but on factory i 
cannot redefine func to get relationship value if return non-main class 
(such as child)

Realization is 
def handle_assertion_error(self, err_info):
  result = re.match(
  "^No such polymorphic_identity '(.*)' is defined$", str(err_info))
  if result.groups() is None:
raise DBException(str(err_info))
  for class_name in class_factory.all_classes_list:
if (class_name.lower() == result.groups()[0]):
  getattr(class_factory, class_name)
  return
With child of  *sqlalchemy.orm.query.Query* class i override methods *all*, 
and *__getitem__ *and now query works
But that is not good for orm objects such is *Organisation.Users*, need to 
use this handler for all queries

I ask how can i pass handler to sqlalchemy?

-- 
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 post to this group, send email to sqlalchemy@googlegroups.com.
Visit this group at https://groups.google.com/group/sqlalchemy.
For more options, visit https://groups.google.com/d/optout.


[sqlalchemy] Re: Custom Handler for "No such polymorphic_identity"

2019-03-11 Thread Tolstov Sergey
Another example is
class cls1 (Base)
  ...

class cls1_child(cls1)
  ...

class cls2(Base)
  cls1_rel = sqlalchemy.rel(cls1, ...)
  ...

a = session.query(cls2)
a.cls1_rel - > throw exception if return cls1_child( and it is not loaded 
before)

-- 
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 post to this group, send email to sqlalchemy@googlegroups.com.
Visit this group at https://groups.google.com/group/sqlalchemy.
For more options, visit https://groups.google.com/d/optout.


[sqlalchemy] Re: Custom Handler for "No such polymorphic_identity"

2019-03-11 Thread Tolstov Sergey
Another example is
cls1

cls1_child(cls1)

cls2
  cls1_rel = sqlalchemy.rel(cls1, ...)


a = session.queyr(cls2)
a.cls1_rel - > throw exception if return cls1_child( and it is not loaded 
before)

-- 
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 post to this group, send email to sqlalchemy@googlegroups.com.
Visit this group at https://groups.google.com/group/sqlalchemy.
For more options, visit https://groups.google.com/d/optout.


[sqlalchemy] Custom Handler for "No such polymorphic_identity"

2019-03-11 Thread Tolstov Sergey
Can i override handler for this error?
Example is - >
  1) defined only Parent class
  2) session.query(Parent)
  -- > raised Exceptions

Resolutions:
  1) try_except for all_queries (too much entry points)
  2) load all possible classes (low perfomance)

How can i override /sqlalchemy/orm/loading.py
  configure_subclass_mapper on runtime?

-- 
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 post to this group, send email to sqlalchemy@googlegroups.com.
Visit this group at https://groups.google.com/group/sqlalchemy.
For more options, visit https://groups.google.com/d/optout.


Re: [sqlalchemy] Redefine class on runtime

2019-03-04 Thread Tolstov Sergey
Thanks for answer,  can i get only part of classes mappers? Somethink about 
Myclass.mapper.clear()?

-- 
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 post to this group, send email to sqlalchemy@googlegroups.com.
Visit this group at https://groups.google.com/group/sqlalchemy.
For more options, visit https://groups.google.com/d/optout.


[sqlalchemy] Redefine class on runtime

2019-03-03 Thread Tolstov Sergey
Hi, for unit tests i need to create class with *Base.metadata.create_all*, 
and delete table defintion (for tests)

On second definition i have a error (already defined)

With use *Base.metadata.clear *i get *warning*

SAWarning: Reassigning polymorphic association for identity 
'testparentclass' from  to 
: Check for duplicate use of 
'testparentclass' as value for polymorphic_identity.

Can i clear cached inherit?

-- 
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 post to this group, send email to sqlalchemy@googlegroups.com.
Visit this group at https://groups.google.com/group/sqlalchemy.
For more options, visit https://groups.google.com/d/optout.


Re: [sqlalchemy] make reconstructor dynamic

2018-12-17 Thread Tolstov Sergey
Now it works, with using class as decorator it not compiled on loading, 
just when init called

понедельник, 17 декабря 2018 г., 15:26:34 UTC+3 пользователь Simon King 
написал:
>
> On Mon, Dec 17, 2018 at 11:58 AM Tolstov Sergey  > wrote: 
> >>> 
> >>> problem not with decorator, 
> > 
> > It is just my fail, i dont know it 
> > 
> https://stackoverflow.com/questions/18062443/python-decorator-function-called-at-compile-time
>  
> > 
>
> I'm sorry, I don't understand. Do you still have a problem, or is 
> everything OK now? 
>
> Simon 
>

-- 
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 post to this group, send email to sqlalchemy@googlegroups.com.
Visit this group at https://groups.google.com/group/sqlalchemy.
For more options, visit https://groups.google.com/d/optout.


Re: [sqlalchemy] make reconstructor dynamic

2018-12-17 Thread Tolstov Sergey

>
> problem not with decorator,
>
> It is just my fail, i dont know it
https://stackoverflow.com/questions/18062443/python-decorator-function-called-at-compile-time
 

-- 
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 post to this group, send email to sqlalchemy@googlegroups.com.
Visit this group at https://groups.google.com/group/sqlalchemy.
For more options, visit https://groups.google.com/d/optout.


Re: [sqlalchemy] make reconstructor dynamic

2018-12-17 Thread Tolstov Sergey
nope, it anyway called on class created, not on loading

понедельник, 17 декабря 2018 г., 13:28:40 UTC+3 пользователь Simon King 
написал:
>
> On Mon, Dec 17, 2018 at 9:05 AM Tolstov Sergey  > wrote: 
> > 
> > Decorator sqlalchemy.orm.reconstructor compilated once, when build code. 
> > How can i create dynamic content(like __init__?) 
> > 
>
> Are you asking how you can override the reconstructor in subclasses? 
> If so, perhaps you could do something like this: 
>
> from sqlalchemy import orm 
>
> class MyMappedClass(object): 
> @orm.reconstructor 
> def _handle_init_on_load(self): 
> # call a normal method that can be overridden in subclasses 
> self._init_on_load() 
>
> def _init_on_load(): 
> # override this method in subclasses 
> pass 
>
>
> Hope that helps, 
>
> Simon 
>

-- 
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 post to this group, send email to sqlalchemy@googlegroups.com.
Visit this group at https://groups.google.com/group/sqlalchemy.
For more options, visit https://groups.google.com/d/optout.


[sqlalchemy] make reconstructor dynamic

2018-12-17 Thread Tolstov Sergey
Decorator *sqlalchemy.orm.reconstructor* compilated once, when build code.
How can i create dynamic content(like *__init__*?)

-- 
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 post to this group, send email to sqlalchemy@googlegroups.com.
Visit this group at https://groups.google.com/group/sqlalchemy.
For more options, visit https://groups.google.com/d/optout.


[sqlalchemy] Re: __init__ not called for session.query items

2018-12-14 Thread Tolstov Sergey
My bad, answer on 
here 
https://docs.sqlalchemy.org/en/latest/orm/constructors.html#constructors-and-object-initialization.
Delete this theme, please!

-- 
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 post to this group, send email to sqlalchemy@googlegroups.com.
Visit this group at https://groups.google.com/group/sqlalchemy.
For more options, visit https://groups.google.com/d/optout.


[sqlalchemy] __init__ not called for session.query items

2018-12-14 Thread Tolstov Sergey
Is it normal? How i can write methods to loading objects?

-- 
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 post to this group, send email to sqlalchemy@googlegroups.com.
Visit this group at https://groups.google.com/group/sqlalchemy.
For more options, visit https://groups.google.com/d/optout.


[sqlalchemy] Re: can't read the change with mysql in time

2018-12-14 Thread Tolstov Sergey
Did you close and open connection before check on second service?
https://www.postgresql.org/docs/10/explicit-locking.html

-- 
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 post to this group, send email to sqlalchemy@googlegroups.com.
Visit this group at https://groups.google.com/group/sqlalchemy.
For more options, visit https://groups.google.com/d/optout.


Re: [sqlalchemy] composite type nested

2018-12-13 Thread Tolstov Sergey
To resolve this i try  to create proxy object

-- 
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 post to this group, send email to sqlalchemy@googlegroups.com.
Visit this group at https://groups.google.com/group/sqlalchemy.
For more options, visit https://groups.google.com/d/optout.


Re: [sqlalchemy] composite type nested

2018-12-13 Thread Tolstov Sergey
test_instance.street_address.town_detail.name = 'tataa' 
after create now work, is it normal?

-- 
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 post to this group, send email to sqlalchemy@googlegroups.com.
Visit this group at https://groups.google.com/group/sqlalchemy.
For more options, visit https://groups.google.com/d/optout.


Re: [sqlalchemy] composite type nested

2018-12-13 Thread Tolstov Sergey
That's perfect when have not > 3k tables and dont need load compound 
columns and relationships when called)
Without that for create with orm i need ~ 200s with SSD and ~ 60 seconds to 
load all relationships))

-- 
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 post to this group, send email to sqlalchemy@googlegroups.com.
Visit this group at https://groups.google.com/group/sqlalchemy.
For more options, visit https://groups.google.com/d/optout.


Re: [sqlalchemy] composite type nested

2018-12-13 Thread Tolstov Sergey
That is my fault, sorry)

-- 
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 post to this group, send email to sqlalchemy@googlegroups.com.
Visit this group at https://groups.google.com/group/sqlalchemy.
For more options, visit https://groups.google.com/d/optout.


Re: [sqlalchemy] composite type nested

2018-12-13 Thread Tolstov Sergey
Here is my example, how to get arond decorator classmethod (without it not 
work, self.__class__ instead of Address not override this function)
session = sqlalchemy.orm.scoped_session(sqlalchemy.orm.sessionmaker(
bind=engine, autoflush=False))




def make_dump(obj):
  return json.dumps(
  obj, default=lambda o: o.__dict__, sort_keys=True, indent=4)




class TownDetail(object):
  def __init__(self, name, value):
self.name = name
self.value = value


  def __composite_values__(self):
return self.name, self.value


  def __eq__(self, other):
return isinstance(other, self.__class__) and\
make_dump(self) == make_dump(other)


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




class Address(object):
  def __init__(self, name=None, value=None, town_detail=None):
self.name = name
self.value = value
self.town_detail = town_detail
Address.generate = self.generate


  def __composite_values__(self):
return (self.name, self.value) + self.town_detail.__composite_values__()


  def __eq__(self, other):
return isinstance(other, self.__class__) and\
make_dump(self) == make_dump(other)


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




def address_gen_function(name, value, town_detail_name, town_detail_value):
  return Address(name, value, TownDetail(town_detail_name, town_detail_value
))




Address.generate = address_gen_function




class TestComposite(Base):
  __tablename__ = 'test_composite'
  id = sqlalchemy.Column(sqlalchemy.types.Integer, primary_key=True)
  name = sqlalchemy.Column(sqlalchemy.types.String)
  _street_address_name = sqlalchemy.Column(sqlalchemy.types.String)
  _street_address_value = sqlalchemy.Column(sqlalchemy.types.Integer)
  _street_address_town_detail_name = sqlalchemy.Column(sqlalchemy.types.
String)
  _street_address_town_detail_value = sqlalchemy.Column(
  sqlalchemy.types.Integer)


  street_address = composite(
  Address.generate, _street_address_name, _street_address_value,
  _street_address_town_detail_name, _street_address_town_detail_value
  )




test_instance = TestComposite(
name='tratata!', street_address=Address(
name=22, value='values', town_detail=TownDetail(name='test_nested', 
value=228))
)

-- 
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 post to this group, send email to sqlalchemy@googlegroups.com.
Visit this group at https://groups.google.com/group/sqlalchemy.
For more options, visit https://groups.google.com/d/optout.


Re: [sqlalchemy] composite type nested

2018-12-13 Thread Tolstov Sergey
I cannot undestand, why you use @classmethod?

среда, 12 декабря 2018 г., 20:33:05 UTC+3 пользователь Mike Bayer написал:
>
> composites of composites aren't supported directly so you'd have to 
> map out all the columns for "street" directly, then define a 
> constructor that handles the columns: 
>
> class Address(object): 
>   def __init__(self, name, value, towndetail): 
> self.name = name 
> self.value = value 
> self.towndetail = towndetail 
>
>   @classmethod 
>   def generate(cls, a, b, c, d): 
> return Address(a, b, TownDetail(c, d)) 
>
>   def __composite_values__(self): 
> return (self.name, self.value) + 
> self.towndetail.__composite_values__() 
>
>   def __eq__(self, other): 
> return isinstance(other, self.__class__) and\ 
> make_dump(self) == make_dump(other) 
>
>   def __ne__(self, other): 
> return not self.__eq__(other) 
>
> ... 
>
> class TestComposite(Base): 
> ... 
>   towndetail = composite(TownDetail, _street_address_town_detail_name, 
> _street_address_town_detail_value) 
>   street = composite(Address.generate, _street_address_name, 
> _street_address_value, _street_address_town_detail_name, 
> _street_address_town_detail_value) 
>
> that trick using "Address.generate" isn't documented right now.   I 
> just discovered it :).   Another way would be make Address.__init__ 
> know how to handle both sets of arguments. 
>
>
> On Tue, Dec 11, 2018 at 12:18 AM Tolstov Sergey  > wrote: 
> > 
> > Can someone have example of this? 
> > Example is 
> > class TownDetail(object): 
> >   def __init__(self, name, value): 
> > self.name = name 
> > self.value = value 
> > 
> >   def __composite_values__(self): 
> > return self.name, self.value 
> > 
> >   def __eq__(self, other): 
> > return isinstance(other, self.__class__) and\ 
> > make_dump(self) == make_dump(other) 
> > 
> >   def __ne__(self, other): 
> > return not self.__eq__(other) 
> > 
> > 
> > class Address(object): 
> >   def __init__(self, name, value, towndetail): 
> > self.name = name 
> > self.value = value 
> > self.towndetail = towndetail 
> > 
> >   def __composite_values__(self): 
> > return self.name, self.value 
> > 
> >   def __eq__(self, other): 
> > return isinstance(other, self.__class__) and\ 
> > make_dump(self) == make_dump(other) 
> > 
> >   def __ne__(self, other): 
> > return not self.__eq__(other) 
> > 
> > class TestComposite(Base): 
> >   __tablename__ = 'test_composite' 
> >   id = sqlalchemy.Column(sqlalchemy.types.Integer, primary_key=True) 
> >   name = sqlalchemy.Column(sqlalchemy.types.String) 
> >   _street_address_name = sqlalchemy.Column(sqlalchemy.types.String) 
> >   _street_address_value = sqlalchemy.Column(sqlalchemy.types.Integer) 
> >   _street_address_town_detail_name = 
> sqlalchemy.Column(sqlalchemy.types.String) 
> >   _street_address_town_detail_value = 
> sqlalchemy.Column(sqlalchemy.types.Integer) 
> > 
> > 
> >   towndetail = composite(TownDetail, _street_address_town_detail_name, 
> _street_address_town_detail_value) 
> >   street = composite(Address, _street_address_name, 
> _street_address_value, towndetail) 
> > 
> > 
> > test_instance = TestComposite( 
> > name='tratata!', street=Address(name=22, value='values', 
> towndetail=TownDetail(322, '322'))) 
> > 
> > Error is 
> > 
> > sqlalchemy.exc.ArgumentError: Composite expects Column objects or mapped 
> attributes/attribute names as arguments, got:  0x7f7aa0a75d68; towndetail> 
> > 
> > have some info in here, but cannot undestand what to do. No access to 
> full example bucket 
> > 
> > -- 
> > 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+...@googlegroups.com . 
> > To post to this group, send email to sqlal...@googlegroups.com 
> . 
> > Visit this group at https://groups.google.com/group/sqlalchemy. 
> > For more options, visit https://groups.google.com/d/optout. 
>

-- 
SQLAlch

Re: [sqlalchemy] composite type nested

2018-12-12 Thread Tolstov Sergey
Thanks, Not so bad as expected) Can you add this example to official docs?

среда, 12 декабря 2018 г., 20:33:05 UTC+3 пользователь Mike Bayer написал:
>
> composites of composites aren't supported directly so you'd have to 
> map out all the columns for "street" directly, then define a 
> constructor that handles the columns: 
>
> class Address(object): 
>   def __init__(self, name, value, towndetail): 
> self.name = name 
> self.value = value 
> self.towndetail = towndetail 
>
>   @classmethod 
>   def generate(cls, a, b, c, d): 
> return Address(a, b, TownDetail(c, d)) 
>
>   def __composite_values__(self): 
> return (self.name, self.value) + 
> self.towndetail.__composite_values__() 
>
>   def __eq__(self, other): 
> return isinstance(other, self.__class__) and\ 
> make_dump(self) == make_dump(other) 
>
>   def __ne__(self, other): 
> return not self.__eq__(other) 
>
> ... 
>
> class TestComposite(Base): 
> ... 
>   towndetail = composite(TownDetail, _street_address_town_detail_name, 
> _street_address_town_detail_value) 
>   street = composite(Address.generate, _street_address_name, 
> _street_address_value, _street_address_town_detail_name, 
> _street_address_town_detail_value) 
>
> that trick using "Address.generate" isn't documented right now.   I 
> just discovered it :).   Another way would be make Address.__init__ 
> know how to handle both sets of arguments. 
>
>
> On Tue, Dec 11, 2018 at 12:18 AM Tolstov Sergey  > wrote: 
> > 
> > Can someone have example of this? 
> > Example is 
> > class TownDetail(object): 
> >   def __init__(self, name, value): 
> > self.name = name 
> > self.value = value 
> > 
> >   def __composite_values__(self): 
> > return self.name, self.value 
> > 
> >   def __eq__(self, other): 
> > return isinstance(other, self.__class__) and\ 
> > make_dump(self) == make_dump(other) 
> > 
> >   def __ne__(self, other): 
> > return not self.__eq__(other) 
> > 
> > 
> > class Address(object): 
> >   def __init__(self, name, value, towndetail): 
> > self.name = name 
> > self.value = value 
> > self.towndetail = towndetail 
> > 
> >   def __composite_values__(self): 
> > return self.name, self.value 
> > 
> >   def __eq__(self, other): 
> > return isinstance(other, self.__class__) and\ 
> > make_dump(self) == make_dump(other) 
> > 
> >   def __ne__(self, other): 
> > return not self.__eq__(other) 
> > 
> > class TestComposite(Base): 
> >   __tablename__ = 'test_composite' 
> >   id = sqlalchemy.Column(sqlalchemy.types.Integer, primary_key=True) 
> >   name = sqlalchemy.Column(sqlalchemy.types.String) 
> >   _street_address_name = sqlalchemy.Column(sqlalchemy.types.String) 
> >   _street_address_value = sqlalchemy.Column(sqlalchemy.types.Integer) 
> >   _street_address_town_detail_name = 
> sqlalchemy.Column(sqlalchemy.types.String) 
> >   _street_address_town_detail_value = 
> sqlalchemy.Column(sqlalchemy.types.Integer) 
> > 
> > 
> >   towndetail = composite(TownDetail, _street_address_town_detail_name, 
> _street_address_town_detail_value) 
> >   street = composite(Address, _street_address_name, 
> _street_address_value, towndetail) 
> > 
> > 
> > test_instance = TestComposite( 
> > name='tratata!', street=Address(name=22, value='values', 
> towndetail=TownDetail(322, '322'))) 
> > 
> > Error is 
> > 
> > sqlalchemy.exc.ArgumentError: Composite expects Column objects or mapped 
> attributes/attribute names as arguments, got:  0x7f7aa0a75d68; towndetail> 
> > 
> > have some info in here, but cannot undestand what to do. No access to 
> full example bucket 
> > 
> > -- 
> > 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+...@googlegroups.com . 
> > To post to this group, send email to sqlal...@googlegroups.com 
> . 
> > Visit this group at https://groups.google.com/group/sqlalchemy. 
> > For more options, visit https://groups.google.c

[sqlalchemy] Re: Get sqlalchemy base class object instead of children

2018-12-10 Thread Tolstov Sergey
This query return orm objects.  If it will return view as you want, in your 
session may have two copies of one object 
** and * *and they not equals, but need to be equals
If you need to print values -  You need to create something simular to 
decorator of data, that return copy of required fields
If need to check type - You may use *instance.__class__.__name__* instead 
of *isinstance*


понедельник, 10 декабря 2018 г., 14:18:00 UTC+3 пользователь Mehrdad 
Pedramfar написал:
>
> Hi everybody,
> I have three classes in my model, which one class inherited by the other 
> two:
>
>
> class Item(Base):
> __tablename__ = 'item'
>
> id = Column(Integer, primary_key=True)
> title = Column(Unicode(300))
> type = Column(Unicode(50))
>
> __mapper_args__ = {
> 'polymorphic_on': type
> }
>
>
> class Note(Item):
> __tablename__ = 'note'
>
> id = Column(Integer, ForeignKey('item.id'), primary_key=True)
> extra = Column(Text)
>
> __mapper_args__ = {
> 'polymorphic_identity': 'note'
> }
>
>
> class Task(Item):
> __tablename__ = 'task'
>
> id = Column(Integer, ForeignKey('item.id'), primary_key=True)
> another_extra = Column(Text)
>
> __mapper_args__ = {
> 'polymorphic_identity': 'task'
> }
> So, when I execute `session.query(Item).all()` I get a list that includes 
> both `Note` and `Task` objects, but I don't want that, I want my objects to 
> be the instance of `Item` class and just have `id`, `title`, `type`, not 
> those extra fields. how should I write the query?
>
> to clarify more, currently, I get:
>
>
> [
>  ,
>  ,
>  ,
>  ...
> ]
>
> But I want to get:
>
> [
> ,
> ,
> ,
> ...
> ]
>
> I have asked the same question in StackOverflow, but still nothing. here 
> is the : 
> Get sqlalchemy base class object instead of children 
> 
>
> Get sqlalchemy base class object instead of children
>
> I have three classes in my model, which one class inherited by the other 
> two: class Item(Base): __tablename...
>
> 
>
>
>

-- 
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 post to this group, send email to sqlalchemy@googlegroups.com.
Visit this group at https://groups.google.com/group/sqlalchemy.
For more options, visit https://groups.google.com/d/optout.


[sqlalchemy] composite type nested

2018-12-10 Thread Tolstov Sergey
Can someone have example of this?
Example is 
class TownDetail(object):
  def __init__(self, name, value):
self.name = name
self.value = value

  def __composite_values__(self):
return self.name, self.value

  def __eq__(self, other):
return isinstance(other, self.__class__) and\
make_dump(self) == make_dump(other)

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


class Address(object):
  def __init__(self, name, value, towndetail):
self.name = name
self.value = value
self.towndetail = towndetail

  def __composite_values__(self):
return self.name, self.value

  def __eq__(self, other):
return isinstance(other, self.__class__) and\
make_dump(self) == make_dump(other)

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

class TestComposite(Base):
  __tablename__ = 'test_composite'
  id = sqlalchemy.Column(sqlalchemy.types.Integer, primary_key=True)
  name = sqlalchemy.Column(sqlalchemy.types.String)
  _street_address_name = sqlalchemy.Column(sqlalchemy.types.String)
  _street_address_value = sqlalchemy.Column(sqlalchemy.types.Integer)
  _street_address_town_detail_name = sqlalchemy.Column(sqlalchemy.types.
String)
  _street_address_town_detail_value = sqlalchemy.Column(sqlalchemy.types.
Integer)


  towndetail = composite(TownDetail, _street_address_town_detail_name, 
_street_address_town_detail_value)
  street = composite(Address, _street_address_name, _street_address_value, 
towndetail)


test_instance = TestComposite(
name='tratata!', street=Address(name=22, value='values', 
towndetail=TownDetail(322, '322')))

Error is 

sqlalchemy.exc.ArgumentError: Composite expects Column objects or mapped 
attributes/attribute names as arguments, got: 

have some info in here 
,
 
but cannot undestand what to do. No access to full example bucket 


-- 
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 post to this group, send email to sqlalchemy@googlegroups.com.
Visit this group at https://groups.google.com/group/sqlalchemy.
For more options, visit https://groups.google.com/d/optout.


Re: [sqlalchemy] How to get ForeignKey from Relationship property

2018-04-11 Thread Tolstov Sergey
Thanks for answer.
I dynamicly create classes, their columns, their relationship.
Add new works with new_instances, who will load after defintion, and 
already loaded classes who doesn't contain foreignkeys(for relationships).
session.expire(attribute), does not work, because contained foreign key 
does not refreshed, and sqlalchemy think that is equal None

Kludge is look for adding foreign_keys and refresh them

if refreshed_attribute is not None:
  for instance in gc.get_objects():
if isinstance(instance, refreshed_attribute['factory_class']):
  if instance in session.dirty or instance in session.deleted:
session.refresh(current_instance, attribute_names = 
[refreshed_attribute['refreshed_attribute']])
  elif instance in session and instance not in session.new:
session.refresh(instance) 

-- 
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 post to this group, send email to sqlalchemy@googlegroups.com.
Visit this group at https://groups.google.com/group/sqlalchemy.
For more options, visit https://groups.google.com/d/optout.


[sqlalchemy] How to get ForeignKey from Relationship property

2018-04-11 Thread Tolstov Sergey
I use dynamic constructor for class.
It works fine for instance who have not foreign keys. But when FK on 
another instance it cannot load them

Example:
class left (Base):
  id = sqlalchemy.Column(UUID, primary_key = True)
  def __getattr__(self, attribute):
if attribute == 'rights':
  right().left
  return getattr(self, attribute)

class right(Base):
  id = sqlalchemy.Column(UUID, primary_key = True)
  def __getattr__(self, attribute):
if attribute == 'left':
  rel_key = sqlalchemy.Column(UUID, sqlalchemy.ForeignKey(left.mRID), 
nullable = True)
  setattr(self.__class__, 'left_mRID', rel_key)
  setattr(self.__class__, 'left', sqlalchemy.orm.relationship(left,\
   foreign_keys = rel_key, uselist = False,\
   backref = sqlalchemy.orm.backref('rights', uselist = True)))
  return getattr(self,attribute)  

Works:
left_1 = session.query(left).first()
print (str(left_1.rights))

Not works:
right_1 = session.query(right).first()
print (str(right_1.left))
I think that it may be fix them, but i need universal for all 
relationshipproperties
class right(Base):
  ...
  def __getattr__(self, attribute):
...
session.refresh(self, attribute_names = ['left_mRID'])

-- 
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 post to this group, send email to sqlalchemy@googlegroups.com.
Visit this group at https://groups.google.com/group/sqlalchemy.
For more options, visit https://groups.google.com/d/optout.


Re: [sqlalchemy] Using __getattr__ and __setattr__ with sqlalchemy

2018-03-30 Thread Tolstov Sergey
I'm sorry, not it work.
I cannot undestand how work this commands:
1)if (key in self.__dict__ or key in self.__class__.__dict__ or not 
hasattr(self, '_sa_instance_state') or 'AssociationProxy' in key):
Base.__setattr__(self, key, value)
2) self._sa_instance_state.initialize(key)

Can you tell me, please

-- 
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 post to this group, send email to sqlalchemy@googlegroups.com.
Visit this group at https://groups.google.com/group/sqlalchemy.
For more options, visit https://groups.google.com/d/optout.


Re: [sqlalchemy] Using __getattr__ and __setattr__ with sqlalchemy

2018-03-30 Thread Tolstov Sergey
This is may fault, now function found __getattr__, but it cannot find 
'__sa_instance_state' in self.__dict__ self.__class__.__dict__

it will raise Max recursive eror

import datetime
sl_starttime= datetime.datetime.utcnow()
import copy
import collections
import datetime
import enum
import json
import flask
import sqlalchemy
import sqlalchemy.ext.declarative
import sqlalchemy.orm
import sqlalchemy.orm.query
import sqlalchemy.sql
import sqlalchemy.types
import sys
import uuid
import warnings
from config import app, db_login, db_password, db_remote_adress, 
db_remote_port, db_name, db_echo, db_isolation_level, ignore_list
engine = 
sqlalchemy.create_engine('postgresql+psycopg2://'+db_login+':'+db_password+'@'+db_remote_adress+':'+str(db_remote_port)+'/'+db_name,
 
echo=db_echo, isolation_level=db_isolation_level)
engine.execute("SET TIME ZONE 0")
Base = sqlalchemy.ext.declarative.declarative_base()

session = sqlalchemy.orm.sessionmaker(bind = engine)()
class UUID(sqlalchemy.types.TypeDecorator):
  impl = sqlalchemy.types.BINARY
  def load_dialect_impl(self, dialect):
if dialect.name == 'postgresql':
  return dialect.type_descriptor(sqlalchemy.dialects.postgresql.UUID())
else:
  return dialect.type_descriptor(sqlalchemy.types.BINARY(16))
  def process_bind_param(self, value, dialect):
if value is None:
  return value
else:
  if not isinstance(value, uuid.UUID):
if isinstance(value, bytes):
  value = uuid.UUID(bytes=value)
elif isinstance(value, int):
  value = uuid.UUID(int=value)
elif isinstance(value, str):
  value = uuid.UUID(value)
if dialect.name == 'postgresql':
  return str(value)
else:
  return value.bytes
  def process_result_value(self, value, dialect):
if value is None:
  return value
if dialect.name == 'postgresql':
  return uuid.UUID(value)
else:
  return uuid.UUID(bytes=value)
engine.execute('CREATE EXTENSION IF NOT EXISTS "uuid-ossp";')
warnings.filterwarnings("ignore")


class Basic_class(Base):
  __tablename__ = "documentsrelationship_"
  all_id =sqlalchemy.Column(UUID, 
server_default=sqlalchemy.text("uuid_generate_v4()"), primary_key=True)
  polymorphic_type = sqlalchemy.Column(sqlalchemy.types.String)
  __mapper_args__ = 
{'polymorphic_identity':__tablename__,'polymorphic_on':polymorphic_type}

class db_factory_class ():
  def __getattr__(self, attr):
if False:
  pass
elif attr == "Class_a":
  class Class_a(Base):
__tablename__ = "class_a"
all_id = sqlalchemy.Column(UUID, 
sqlalchemy.ForeignKey(Basic_class.all_id), primary_key = True)
__mapper_args__ = {"polymorphic_identity" :  __tablename__, 
"inherit_condition" : all_id == Basic_class.all_id}
name = sqlalchemy.Column(sqlalchemy.types.String)
def __getattr__ (self2, key2):
  if key2 == "_sa_instance_state":
if key2 in self2.__dict__:
  return self2.__dict__[key2]
elif key2 in self2.__class__.__dict__:
  return self2.__class__.__dict__[key2]
else:
  return Base.__getattr__(self2, key2)
  elif key2 == "Class_b":
load_function("Class_a", "Class_b")
  else:
getattr(self.__class__.__bases__[0], key2)
def __setattr__ (self2, key2, value2):
  if key2 == "_sa_instance_state":
Base.__setattr__(self2, key2, value2)
  else:
old_value = getattr(self2, key2)
  setattr(self2, key2, value2)
  class_factory.Class_a = Class_a
elif attr == "Class_b":
  class Class_b(Base):
__tablename__ = "class_b"
all_id = sqlalchemy.Column(UUID, 
sqlalchemy.ForeignKey(Basic_class.all_id), primary_key = True)
__mapper_args__ = {"polymorphic_identity" :  __tablename__, 
"inherit_condition" : all_id == Basic_class.all_id}
name = sqlalchemy.Column(sqlalchemy.types.String)
def __getattr__ (self2, key2):
  if key2 == "_sa_instance_state":
if key2 in self2.__dict__:
  return self2.__dict__[key2]
elif key2 in self2.__class__.__dict__:
  return self2.__class__.__dict__[key2]
else:
  return Base.__getattr__(self2, key2)
  elif key2 == "Class_a":
load_function("Class_b", "Class_a")
  else:
getattr(self.__class__.__bases__[0], key2)
def __setattr__ (self2, key2, value2):
  if key2 == "_sa_instance_state":
Base.__setattr__(self2, key2, value2)
  else:
old_value = getattr(self2, key2)
  setattr(self2, key2, value2)
  class_factory.Class_b = Class_b
return getattr(self, attr)

class_factory = db_factory_class()
class_factory.Class_a()
def load_function (class_name, attr_name):
  print ('called preload for ' + str(class_name) + ' attr '+ str(attr_name))
  if False:
pass
  elif class_name == "Class_b" 

Re: [sqlalchemy] Using __getattr__ and __setattr__ with sqlalchemy

2018-03-30 Thread Tolstov Sergey

import datetime
sl_starttime= datetime.datetime.utcnow()
import copy
import collections
import datetime
import enum
import json
import flask
import sqlalchemy
import sqlalchemy.ext.declarative
import sqlalchemy.orm
import sqlalchemy.orm.query
import sqlalchemy.sql
import sqlalchemy.types
import sys
import uuid
import warnings
from config import app, db_login, db_password, db_remote_adress, 
db_remote_port, db_name, db_echo, db_isolation_level, ignore_list
engine = 
sqlalchemy.create_engine('postgresql+psycopg2://'+db_login+':'+db_password+'@'+db_remote_adress+':'+str(db_remote_port)+'/'+db_name,
 
echo=db_echo, isolation_level=db_isolation_level)
engine.execute("SET TIME ZONE 0")
Base = sqlalchemy.ext.declarative.declarative_base()

session = sqlalchemy.orm.sessionmaker(bind = engine)()
class UUID(sqlalchemy.types.TypeDecorator):
  impl = sqlalchemy.types.BINARY
  def load_dialect_impl(self, dialect):
if dialect.name == 'postgresql':
  return dialect.type_descriptor(sqlalchemy.dialects.postgresql.UUID())
else:
  return dialect.type_descriptor(sqlalchemy.types.BINARY(16))
  def process_bind_param(self, value, dialect):
if value is None:
  return value
else:
  if not isinstance(value, uuid.UUID):
if isinstance(value, bytes):
  value = uuid.UUID(bytes=value)
elif isinstance(value, int):
  value = uuid.UUID(int=value)
elif isinstance(value, str):
  value = uuid.UUID(value)
if dialect.name == 'postgresql':
  return str(value)
else:
  return value.bytes
  def process_result_value(self, value, dialect):
if value is None:
  return value
if dialect.name == 'postgresql':
  return uuid.UUID(value)
else:
  return uuid.UUID(bytes=value)
engine.execute('CREATE EXTENSION IF NOT EXISTS "uuid-ossp";')
warnings.filterwarnings("ignore")


class Basic_class(Base):
  __tablename__ = "documentsrelationship_"
  all_id =sqlalchemy.Column(UUID, 
server_default=sqlalchemy.text("uuid_generate_v4()"), primary_key=True)
  polymorphic_type = sqlalchemy.Column(sqlalchemy.types.String)
  __mapper_args__ = 
{'polymorphic_identity':__tablename__,'polymorphic_on':polymorphic_type}

class db_factory_class ():
  def __getattr__(self, attr):
if False:
  pass
elif attr == "Class_a":
  class Class_a(Base):
__tablename__ = "class_a"
all_id = sqlalchemy.Column(UUID, 
sqlalchemy.ForeignKey(Basic_class.all_id), primary_key = True)
__mapper_args__ = {"polymorphic_identity" :  __tablename__, 
"inherit_condition" : all_id == Basic_class.all_id}
name = sqlalchemy.Column(sqlalchemy.types.String)
def __getattr__ (self2, key2):
  if key2 == "_sa_instance_state":
  return Base.__getattr__(self2, key2)
  elif key2 == "Class_b":
load_function("Class_a", "Class_b")
  else:
getattr(self.__class__.__bases__[0], key2)
def __setattr__ (self2, key2, value2):
  if key2 == "_sa_instance_state":
Base.__setattr__(self2, key2, value2)
  else:
old_value = getattr(self2, key2)
  setattr(self2, key2, value2)
  class_factory.Class_a = Class_a
elif attr == "Class_b":
  class Class_b(Base):
__tablename__ = "class_b"
all_id = sqlalchemy.Column(UUID, 
sqlalchemy.ForeignKey(Basic_class.all_id), primary_key = True)
__mapper_args__ = {"polymorphic_identity" :  __tablename__, 
"inherit_condition" : all_id == Basic_class.all_id}
name = sqlalchemy.Column(sqlalchemy.types.String)
def __getattr__ (self2, key2):
  if key2 == "_sa_instance_state":
  return Base.__getattr__(self2, key2)
  elif key2 == "Class_a":
load_function("Class_b", "Class_a")
  else:
getattr(self.__class__.__bases__[0], key2)
def __setattr__ (self2, key2, value2):
  if key2 == "_sa_instance_state":
Base.__setattr__(self2, key2, value2)
  else:
old_value = getattr(self2, key2)
  setattr(self2, key2, value2)
  class_factory.Class_b = Class_b
return getattr(self, attr)

class_factory = db_factory_class()
class_factory.Class_a()
def load_function (class_name, attr_name):
  print ('called preload for ' + str(class_name) + ' attr '+ str(attr_name))
  if False:
pass
  elif class_name == "Class_b" and attr_name == "Class_a":
class_factory.Class_b.Class_a_id = sqlalchemy.Column(UUID, sqlalchemy. 
ForeignKey(class_factory.Class_a.mRID), nullable = True)
class_factory.Class_b.Class_a = 
sqlalchemy.orm.relationship(class_factory.Class_a, foreign_keys = 
class_factory.Class_b.Class_a_id,\
uselist = False, backref = sqlalchemy.orm.backref("Class_b", uselist = 
True))
  elif class_name == "Class_a" and attr_name == "Class_b":
load_function("Class_b", "Class_a")
  else:

raise ValueError ("invalid class/attribute")

-- 
SQLAlchemy - 
The Python SQL 

Re: [sqlalchemy] Using __getattr__ and __setattr__ with sqlalchemy

2018-03-30 Thread Tolstov Sergey

import datetime
sl_starttime= datetime.datetime.utcnow()
import copy
import collections
import datetime
import enum
import json
import flask
import sqlalchemy
import sqlalchemy.ext.declarative
import sqlalchemy.orm
import sqlalchemy.orm.query
import sqlalchemy.sql
import sqlalchemy.types
import sys
import uuid
import warnings
from config import app, db_login, db_password, db_remote_adress, 
db_remote_port, db_name, db_echo, db_isolation_level, ignore_list
engine = 
sqlalchemy.create_engine('postgresql+psycopg2://'+db_login+':'+db_password+'@'+db_remote_adress+':'+str(db_remote_port)+'/'+db_name,
 
echo=db_echo, isolation_level=db_isolation_level)
engine.execute("SET TIME ZONE 0")
Base = sqlalchemy.ext.declarative.declarative_base()

session = sqlalchemy.orm.sessionmaker(bind = engine)()
class UUID(sqlalchemy.types.TypeDecorator):
  impl = sqlalchemy.types.BINARY
  def load_dialect_impl(self, dialect):
if dialect.name == 'postgresql':
  return dialect.type_descriptor(sqlalchemy.dialects.postgresql.UUID())
else:
  return dialect.type_descriptor(sqlalchemy.types.BINARY(16))
  def process_bind_param(self, value, dialect):
if value is None:
  return value
else:
  if not isinstance(value, uuid.UUID):
if isinstance(value, bytes):
  value = uuid.UUID(bytes=value)
elif isinstance(value, int):
  value = uuid.UUID(int=value)
elif isinstance(value, str):
  value = uuid.UUID(value)
if dialect.name == 'postgresql':
  return str(value)
else:
  return value.bytes
  def process_result_value(self, value, dialect):
if value is None:
  return value
if dialect.name == 'postgresql':
  return uuid.UUID(value)
else:
  return uuid.UUID(bytes=value)
engine.execute('CREATE EXTENSION IF NOT EXISTS "uuid-ossp";')
warnings.filterwarnings("ignore")


class Basic_class(Base):
  __tablename__ = "documentsrelationship_"
  all_id =sqlalchemy.Column(UUID, 
server_default=sqlalchemy.text("uuid_generate_v4()"), primary_key=True)
  polymorphic_type = sqlalchemy.Column(sqlalchemy.types.String)
  __mapper_args__ = 
{'polymorphic_identity':__tablename__,'polymorphic_on':polymorphic_type}

class db_factory_class ():
  def __getattr__(self, attr):
if False:
  pass
elif attr == "Class_a":
  class Class_a(Base):
__tablename__ = "class_a"
all_id = sqlalchemy.Column(UUID, 
sqlalchemy.ForeignKey(Basic_class.all_id), primary_key = True)
__mapper_args__ = {"polymorphic_identity" :  __tablename__, 
"inherit_condition" : all_id == Basic_class.all_id}
name = sqlalchemy.Column(sqlalchemy.types.String)
def __getattr__ (self2, key2):
  if key2 == "_sa_instance_state":
  return Base.__getattr__(self2, key2)
  elif key2 == "Class_b":
load_function("Class_a", "Class_b")
  else:
getattr(self.__class__.__bases__[0], key2)
def __setattr__ (self2, key2, value2):
  if key2 != "_sa_instance_state":
Base.__setattr__(self2, key2, value2)
  else:
old_value = getattr(self2, key2)
  setattr(self2, key2, value2)
  class_factory.Class_a = Class_a
elif attr == "Class_b":
  class Class_b(Base):
__tablename__ = "class_b"
all_id = sqlalchemy.Column(UUID, 
sqlalchemy.ForeignKey(Basic_class.all_id), primary_key = True)
__mapper_args__ = {"polymorphic_identity" :  __tablename__, 
"inherit_condition" : all_id == Basic_class.all_id}
name = sqlalchemy.Column(sqlalchemy.types.String)
def __getattr__ (self2, key2):
  if key2 == "_sa_instance_state":
  return Base.__getattr__(self2, key2)
  elif key2 == "Class_a":
load_function("Class_b", "Class_a")
  else:
getattr(self.__class__.__bases__[0], key2)
def __setattr__ (self2, key2, value2):
  if key2 != "_sa_instance_state":
Base.__setattr__(self2, key2, value2)
  else:
old_value = getattr(self2, key2)
  setattr(self2, key2, value2)
  class_factory.Class_b = Class_b
return getattr(self, attr)

class_factory = db_factory_class()
class_factory.Class_a()
def load_function (class_name, attr_name):
  print ('called preload for ' + str(class_name) + ' attr '+ str(attr_name))
  if False:
pass
  elif class_name == "Class_b" and attr_name == "Class_a":
class_factory.Class_b.Class_a_id = sqlalchemy.Column(UUID, sqlalchemy. 
ForeignKey(class_factory.Class_a.mRID), nullable = True)
class_factory.Class_b.Class_a = 
sqlalchemy.orm.relationship(class_factory.Class_a, foreign_keys = 
class_factory.Class_b.Class_a_id,\
uselist = False, backref = sqlalchemy.orm.backref("Class_b", uselist = 
True))
  elif class_name == "Class_a" and attr_name == "Class_b":
load_function("Class_b", "Class_a")
  else:

raise ValueError ("invalid class/attribute")

-- 
SQLAlchemy - 
The Python SQL 

[sqlalchemy] Re: Using __getattr__ and __setattr__ with sqlalchemy

2018-03-29 Thread Tolstov Sergey
def __getattr__ (self2, key2):
  if False:
pass
  elif key2 == "attr_new":
 self2.attr_new = sqlalchemy.Column(UUID, sqlalchemy. 
ForeignKey(self.RELATED_CLASS.mRID), nullable = True)
  else:
return getattr(self2.__class__, key2)
  return getattr(self2, key2)

-- 
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 post to this group, send email to sqlalchemy@googlegroups.com.
Visit this group at https://groups.google.com/group/sqlalchemy.
For more options, visit https://groups.google.com/d/optout.


Re: [sqlalchemy] Using __getattr__ and __setattr__ with sqlalchemy

2018-03-29 Thread Tolstov Sergey
Solved,
return getattr(self2.__class__, key2)

-- 
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 post to this group, send email to sqlalchemy@googlegroups.com.
Visit this group at https://groups.google.com/group/sqlalchemy.
For more options, visit https://groups.google.com/d/optout.


Re: [sqlalchemy] Using __getattr__ and __setattr__ with sqlalchemy

2018-03-29 Thread Tolstov Sergey
Before update it worked. But today i have a exception AttributeError: type 
object 'Base' has no attribute '__getattr__'

-- 
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 post to this group, send email to sqlalchemy@googlegroups.com.
Visit this group at https://groups.google.com/group/sqlalchemy.
For more options, visit https://groups.google.com/d/optout.


[sqlalchemy] Re: Reload mapper column definition

2018-03-04 Thread Tolstov Sergey
*Addition:*
This is a *relationship*

-- 
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 post to this group, send email to sqlalchemy@googlegroups.com.
Visit this group at https://groups.google.com/group/sqlalchemy.
For more options, visit https://groups.google.com/d/optout.


[sqlalchemy] Reload mapper column definition

2018-03-04 Thread Tolstov Sergey
On my project, i use __getattr__ for adding column deifinition to object 
class
Such as: 

def __getattr__(self,attr):
...
  my_load_function(...)
  session.refresh(self)
   ...
return getattr(self,attr)

It works, but refresh loses changes on this object. I cannot flush, because 
it used for another function.

I found solution 
session.refresh(self, attribute_names=['attr_name'])

But it will raise exception
sqlalchemy.exc.InvalidRequestError: No column-based properties specified 
for refresh operation. Use session.expire() to reload collections and 
related items.]

I already tried use session.expire(self) and session.expire(self, 
attribute_names=['attr_name'])) before and after refresh, but nothing 
changed

Can someone help me with this eror?

-- 
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 post to this group, send email to sqlalchemy@googlegroups.com.
Visit this group at https://groups.google.com/group/sqlalchemy.
For more options, visit https://groups.google.com/d/optout.


[sqlalchemy] check enums?

2018-01-09 Thread Tolstov Sergey
I create enums with this code

*MonthDay = 
sqlalchemy.types.Enum('1','2','3','4','5','6','7','8','9','10','11','12','13','14','15','16','17','18','19','20','21','22','23','24','25','26','27','28','29','30','31',
 
name= 'monthday',metadata=Base.metadata)*

But i can set it to

season.startDate = '37'

Exception raises only when write to database. 
How i can check it before flushing to database?

-- 
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 post to this group, send email to sqlalchemy@googlegroups.com.
Visit this group at https://groups.google.com/group/sqlalchemy.
For more options, visit https://groups.google.com/d/optout.


[sqlalchemy] Re: Transactions

2018-01-08 Thread Tolstov Sergey
Problem fixed with delete *threaded* parameter on Flask, sorry

-- 
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 post to this group, send email to sqlalchemy@googlegroups.com.
Visit this group at https://groups.google.com/group/sqlalchemy.
For more options, visit https://groups.google.com/d/optout.


[sqlalchemy] Re: Transactions

2018-01-08 Thread Tolstov Sergey


вторник, 9 января 2018 г., 9:08:22 UTC+3 пользователь Tolstov Sergey 
написал:
>
> I use transactions and sometimes it must be *session.rollback*.
> Sometimes i get a AttributeError: 'NoneType' object has no attribute 
> 'twophase' 
> That error raises, when one transaction open and processed, and *another* 
> transaction with session use *rollback*
>


Some example on stackoverflow 
<https://stackoverflow.com/questions/25768428/sqlalchemy-connection-errors> 

-- 
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 post to this group, send email to sqlalchemy@googlegroups.com.
Visit this group at https://groups.google.com/group/sqlalchemy.
For more options, visit https://groups.google.com/d/optout.


[sqlalchemy] Transactions

2018-01-08 Thread Tolstov Sergey
I use transactions and sometimes it must be *session.rollback*.
Sometimes i get a AttributeError: 'NoneType' object has no attribute 
'twophase' 
That error raises, when one transaction open and processed, and *another* 
transaction with session use *rollback*

-- 
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 post to this group, send email to sqlalchemy@googlegroups.com.
Visit this group at https://groups.google.com/group/sqlalchemy.
For more options, visit https://groups.google.com/d/optout.


Re: [sqlalchemy] Cancel update and delete before commit

2017-12-10 Thread Tolstov Sergey
Mike, very thanks for answer. I just use custom function and add to object 
session. I create some lists to save object and after rollback i add them
On this func i just use session.dirty, session.new, session.delete
for rollback i use
 
 def user_commit():
...
config.session.rollback()
 ...
for item in saved_items():
  config.session.add(item)
...
config.session.commit()

config.session.user_commit=user_commit

-- 
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 post to this group, send email to sqlalchemy@googlegroups.com.
Visit this group at https://groups.google.com/group/sqlalchemy.
For more options, visit https://groups.google.com/d/optout.


Re: [sqlalchemy] Cancel update and delete before commit

2017-12-10 Thread Tolstov Sergey
Mike, very thanks for answer. I just use custom function and add to object 
session. I create some lists to save object and after rollback i add them
On this func i just use session.dirty, session.new, session.delete
for rollback i use

config.session.rollback()
 
 def user_commit():
...
config.session.rollback()
 ...
for item in saved_items():
  config.session.add(item)
...
config.session.commit()

config.session.user_commit=user_commit

-- 
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 post to this group, send email to sqlalchemy@googlegroups.com.
Visit this group at https://groups.google.com/group/sqlalchemy.
For more options, visit https://groups.google.com/d/optout.


Re: [sqlalchemy] Cancel update and delete before commit

2017-12-10 Thread Tolstov Sergey

>
> Mike, very thanks for answer. I just use custom function and add to object 
> session 

 
 def user_commit():
  ...
  config.session.commit()

config.session.user_commit=user_commit

-- 
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 post to this group, send email to sqlalchemy@googlegroups.com.
Visit this group at https://groups.google.com/group/sqlalchemy.
For more options, visit https://groups.google.com/d/optout.


[sqlalchemy] Cancel update and delete before commit

2017-12-08 Thread Tolstov Sergey


I need to *switch off changing* (not new) database rows and write all 
changes to specific table on event "*before_commit*".

 But when i try to use *config.session.rollback()* SqlAlchemy show me 

*AttributeError: 'NoneType' object has no attribute 'transaction'*

I try config.session.expunge all instances on config.session.dirty and 
config.session.deleted but changes anyway write to database 

Can someone help me, how can i *drop all transactions *and *write new *on 
event *before_commit* ?

-- 
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 post to this group, send email to sqlalchemy@googlegroups.com.
Visit this group at https://groups.google.com/group/sqlalchemy.
For more options, visit https://groups.google.com/d/optout.


[sqlalchemy] Re: Tracking new relationships

2017-12-01 Thread Tolstov Sergey
Solved, SQlalchemy create object based on instance, i didn't guess that, 
sorry

-- 
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 post to this group, send email to sqlalchemy@googlegroups.com.
Visit this group at https://groups.google.com/group/sqlalchemy.
For more options, visit https://groups.google.com/d/optout.


[sqlalchemy] Tracking new relationships

2017-11-30 Thread Tolstov Sergey
Hi, everyone.

I cannot found information how to find information about new relationships, 
when they related with secondary table.
Inspect can't work with class RelationshipProperty.
 class_mapper.iterate_properties have't information about changed 
attributes

My *task* is:
  Write transactions for all changes, i use them for generate old condition 
of instances
I try to use:
  Write to common table Transcations, data:

classname,
instance_id,
attribute_name,
new_value,
old_value
TransactionsComment - group of transactions (such as *git commit*)

*Example* is:
  users=db.session.query(Group_).first()
  if users is None:
users=Group_(name='users')
db.session.add(users)
db.session.commit()
  print ('now on user')
##New User
  user=db.session.query(User_).first()
  if user is None:
# print ('need new user')
user=User_(login='trololo', groups=[users])
db.session.add(user)
db.session.commit()
  return 'good'

I use *listener "before_commit"*

#update
  for i in db.session.dirty:
tr=[]
print ('\nUpdated   '+i.__class__.__name__+'  '+str(i.__dict__))

for prop in class_mapper(i.__class__).iterate_properties:
  if isinstance(prop, RelationshipProperty):
if prop.parent==i.__mapper__:
  print (str(prop.key))
  print ('try to find '+prop.key+' in '+str(i.__dict__))
  if prop.key in i.__dict__:
print (inspect(i.__dict__[prop.key]))
  # for rel_attr in inspect(prop).attrs:
  #   if rel_attr.history.has_changes:
  # print (str(rel_attr))

  #create
  for i in db.session.new:
print ('\nNew   '+i.__class__.__name__+'  '+str(i.__dict__))
if getattr(i,'Document',False) is not False:
  doc=db.session.query(Document_).first()
  if doc is None:
doc=Document_(name='test', extension='txt')
  print ('added document property to'+str(i.__dict__))
  i.Document=doc

*Result* is
New   Group_  {'name': 'users', 'polymorphic_type': 'group_', 
'_sa_instance_state': }
added document property to{'_sa_instance_state': 
, 'name': 
'users', 'mRID': UUID('1c0a2e32-20b9-4ecf-af62-5cf919e16269'), 
'polymorphic_type': 'group_'}
now on user

Updated   Group_  {'_sa_instance_state': 
}
users
try to find users in {'_sa_instance_state': 
}
childrens
try to find childrens in {'_sa_instance_state': 
}
parents
try to find parents in {'_sa_instance_state': 
}

New   User_  {'login': 'trololo', 'groups': True, '_sa_instance_state': 
, 
'polymorphic_type': 'user_'}
added document property to{'login': 'trololo', 'groups': True, 
'_sa_instance_state': , 'mRID': UUID('c07fe890-8bb4-4b36-abe6-afd85148d005'), 
'polymorphic_type': 'user_'}

Thanks for read my answer, if you have minds how i can find this changes, 
or another path to complete this task i would like to read them

-- 
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 post to this group, send email to sqlalchemy@googlegroups.com.
Visit this group at https://groups.google.com/group/sqlalchemy.
For more options, visit https://groups.google.com/d/optout.


Re: [sqlalchemy] SQLALchemy lazy compile classes

2017-10-16 Thread Tolstov Sergey
Thanks for answer, but that's a flask application. And it will run with 
different args. If i tried to append objects with new relations python 
raise errors metadata

-- 
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 post to this group, send email to sqlalchemy@googlegroups.com.
Visit this group at https://groups.google.com/group/sqlalchemy.
For more options, visit https://groups.google.com/d/optout.


Re: [sqlalchemy] Strict many-to-many

2017-10-05 Thread Tolstov Sergey

>
> Thanks, that's really good


With thanks, Sergey Tolstov

-- 
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 post to this group, send email to sqlalchemy@googlegroups.com.
Visit this group at https://groups.google.com/group/sqlalchemy.
For more options, visit https://groups.google.com/d/optout.


[sqlalchemy] Strict many-to-many

2017-10-04 Thread Tolstov Sergey
I have some tables who have a strict many-to-many rules. But i can't 
undestand, how i can create rules for them. For strict on one point i use 
init check, such us:

def __init__(self,**kwargs):
for i in kwargs.items():setattr(self,i[0],i[1])
if 'AllocationResultValues' not in kwargs:
  raise RuntimeError('Need AllocationResultValues')

But if i use on both points - it's create error on another point. Can 
someone help me, please?

-- 
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 post to this group, send email to sqlalchemy@googlegroups.com.
Visit this group at https://groups.google.com/group/sqlalchemy.
For more options, visit https://groups.google.com/d/optout.


[sqlalchemy] Re: SQLAlchemy many-to-many Postgresql double delete

2017-09-30 Thread Tolstov Sergey
Mike, thanks for answer. But that's not true. I use them on project and it 
works. Ilja Everilä 
 on 
StackOverflow help me. Answer is:
I need a create functions.

In [6]: def class_name_collection(base, local_cls, referred_cls, constraint):
   ...: return referred_cls.__name__
   ...: 

and then

   ...: Base.prepare(engine, reflect=True,
   ...:  name_for_collection_relationship=class_name_collection)


Problem is - using Autobase with custom relationship preferences add 
objects to two collections, and try delete from all of them

-- 
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 post to this group, send email to sqlalchemy@googlegroups.com.
Visit this group at https://groups.google.com/group/sqlalchemy.
For more options, visit https://groups.google.com/d/optout.


[sqlalchemy] SQLAlchemy many-to-many Postgresql double delete

2017-09-29 Thread Tolstov Sergey
I try to delete data, but sqlalchemy tried to do it twice, and rollback
Base Postgresql
version 9.6
sqlalchemy 1.0.14
psycopg2 2.7.3.1


class IdentifiedObject(Base):
  __tablename__ = 'identifiedobject'
  mRID = Column(UUID, 
server_default=sqlalchemy.text("uuid_generate_v4()"), primary_key=True)
  name = Column(String)
  polymorphic_type = Column(String, nullable=False)
  
__mapper_args__={'polymorphic_identity':__tablename__,'polymorphic_on':polymorphic_type}
assoc_1 = Table("assoc_1", Base.metadata,
  Column("cars_mRID", None, ForeignKey("cars.mRID")),
  Column("games_mRID", None, ForeignKey("games.mRID")))
class Cars(IdentifiedObject):
  __tablename__='cars'
  mRID = Column(None, ForeignKey('identifiedobject.mRID'), 
primary_key=True)
  polymorphic_type = Column(String, nullable=False)
  
__mapper_args__={'polymorphic_identity':__tablename__,'inherit_condition': 
mRID == IdentifiedObject.mRID,'polymorphic_on':polymorphic_type}
  status = Column(String)
  Games = relationship("Games", secondary = "assoc_1", 
back_populates="Cars", primaryjoin="(cars.c.mRID==assoc_1.c.cars_mRID)")
class Games(IdentifiedObject):
  __tablename__='games'
  mRID = Column(None, ForeignKey('identifiedobject.mRID'), 
primary_key=True)
  polymorphic_type = Column(String, nullable=False)
  
__mapper_args__={'polymorphic_identity':__tablename__,'inherit_condition': 
mRID == IdentifiedObject.mRID,'polymorphic_on':polymorphic_type}
  status = Column(String)
  Cars = relationship("Cars", secondary = "assoc_1", 
back_populates="Games", primaryjoin="(games.c.mRID==assoc_1.c.games_mRID)")

Base.metadata.create_all(engine)
Base.prepare(engine, reflect=True)
session = Session(bind=engine)
session.add(IdentifiedObject())
games=Games(Cars=[Cars(),Cars()])
session.add (games)
session.commit()
session.close()
session.delete(games)
session.commit()

And now we found a exception


2017-09-29 09:17:44,996 INFO sqlalchemy.engine.base.Engine SELECT 
cars."mRID" AS "cars_mRID", identifiedobject."mRID" AS 
"identifiedobject_mRID", identifiedobject.name AS identifiedobject_name, 
cars.polymorphic_type AS cars_polymorphic_type, 
identifiedobject.polymorphic_type AS identifiedobject_polymorphic_type, 
cars.status AS cars_status 
FROM assoc_1, identifiedobject JOIN cars ON cars."mRID" = 
identifiedobject."mRID" 
WHERE %(param_1)s = assoc_1."games_mRID" AND cars."mRID" = 
assoc_1."cars_mRID"
2017-09-29 09:17:44,996 INFO sqlalchemy.engine.base.Engine {'param_1': 
UUID('7a960989-5e3e-45dc-87c1-1b62ffa3694a')}
2017-09-29 09:17:44,997 INFO sqlalchemy.engine.base.Engine DELETE FROM 
assoc_1 WHERE assoc_1."cars_mRID" = %(cars_mRID)s AND assoc_1."games_mRID" 
= %(games_mRID)s
2017-09-29 09:17:44,998 INFO sqlalchemy.engine.base.Engine 
({'games_mRID': UUID('7a960989-5e3e-45dc-87c1-1b62ffa3694a'), 'cars_mRID': 
UUID('a3135561-e416-45c0-b9f8-aead59ef6b34')}, {'games_mRID': 
UUID('7a960989-5e3e-45dc-87c1-1b62ffa3694a'), 'cars_mRID': 
UUID('b77b9dc4-65da-45ea-be52-dc53e2bcd74b')})
2017-09-29 09:17:44,998 INFO sqlalchemy.engine.base.Engine DELETE FROM 
assoc_1 WHERE assoc_1."cars_mRID" = %(cars_mRID)s AND assoc_1."games_mRID" 
= %(games_mRID)s
2017-09-29 09:17:44,999 INFO sqlalchemy.engine.base.Engine 
({'games_mRID': UUID('7a960989-5e3e-45dc-87c1-1b62ffa3694a'), 'cars_mRID': 
UUID('a3135561-e416-45c0-b9f8-aead59ef6b34')}, {'games_mRID': 
UUID('7a960989-5e3e-45dc-87c1-1b62ffa3694a'), 'cars_mRID': 
UUID('b77b9dc4-65da-45ea-be52-dc53e2bcd74b')})
2017-09-29 09:17:44,999 INFO sqlalchemy.engine.base.Engine ROLLBACK
Traceback (most recent call last):
  File "testing.py", line 98, in 
session.commit()

Exception data


sqlalchemy.orm.exc.StaleDataError: DELETE statement on table 'assoc_1' 
expected to delete 2 row(s); Only 0 were matched.

Haven't found on other answers

-- 
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 post to this group, send email to sqlalchemy@googlegroups.com.
Visit this group at https://groups.google.com/group/sqlalchemy.
For more options, visit https://groups.google.com/d/optout.


[sqlalchemy] SQLALchemy lazy compile classes

2017-09-28 Thread Tolstov Sergey


i haven't found solution for this. Problem in very load compile (40 sec).
 I have a :
 - more then 1200 classes
- 300 enums 
- and some custom primitive classes for working
- 7 levels of polymorphic inherits 
- some itself relationship, may one-to-many and many-to-many in one class 
to itself
- parents and childs may have somenamed relationship to one table

I undestand, that's big project, but in develop i need load ~100 classes. 
Do the product exists that can do it or i need to create custom class map 
and custom factory? 

-- 
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 post to this group, send email to sqlalchemy@googlegroups.com.
Visit this group at https://groups.google.com/group/sqlalchemy.
For more options, visit https://groups.google.com/d/optout.


Re: [sqlalchemy] Re: Postgres Composite Columns

2017-09-18 Thread Tolstov Sergey

>
> Thanks for answer. I don't think so. pg_composite haven't updates 1-3 
> years.

I already use another table for store data, that's more comfortable and 
> cross-pratform


понедельник, 18 сентября 2017 г., 17:12:13 UTC+3 пользователь Mike Bayer 
написал:
>
> On Mon, Sep 18, 2017 at 2:30 AM, Tolstov Sergey <whist...@gmail.com 
> > wrote: 
> >> Hi, i have some issue. I tried to replace namedtuple to dict and list 
> >> items (with adding hast function to them). But SQLAlchemy types returns 
> list 
> >> ordereddict, when i change items, session didn't see changes. Do you 
> found 
> >> solution? 
>
> looks like you are using 
>
> http://sqlalchemy-utils.readthedocs.io/en/latest/data_types.html#module-sqlalchemy_utils.types.pg_composite
>  
> , I'm not sure if the sqlalchemy-utils maintainer checks this list you 
> might want to try a github issue with that project. 
>
> > 
> > def make_hash(o): 
> >   if isinstance(o,(set,tuple,list)): 
> > for i in o: 
> >   i= tuple([make_hash(e) for e in o]) 
> >   return hash(i) 
> >   elif isinstance(o,dict): 
> > pass 
> > i=make_hash([make_hash(j)for j in o.items()]) 
> > return hash(i) 
> > 
> >   elif isinstance(o,(str,int)): 
> > return hash(o) 
> >   else: 
> > try: 
> >   return hash(o) 
> > except: 
> >   return make_hash(o.__dict__) 
> > return hash(o) 
> > 
> > 
> > # sys.exit() 
> > 
> > class hashabledict(dict): 
> >   def __key(self): 
> > return tuple((k,self[k]) for k in sorted(self)) 
> >   def __hash__(self): 
> > print 'try to make_hash'+str(self)+' result = '+ 
> str(make_hash(self)) 
> > return make_hash(self) 
> >   def __eq__(self, other): 
> > return make_hash(self) == make_hash(other) 
> > 
> > class hashablelist(list): 
> >   def __hash__(self): 
> > return make_hash(self) 
> >   def __eq__(self, other): 
> > return make_hash(self) == make_hash(other) 
> > 
> > class MyCompositeType(CompositeType): 
> >   pass 
> >   def __init__(self, name, columns): 
> > if psycopg2 is None: 
> > raise ImproperlyConfigured("'psycopg2' package is required in 
> order 
> > to use CompositeType.") 
> > sqlalchemy.types.SchemaType.__init__(self) 
> > self.name = name 
> > self.columns = columns 
> > if name in registered_composites: 
> > self.type_cls = registered_composites[name].type_cls 
> > else: 
> > temp=hashablelist() 
> > for c in columns: 
> >   temp.append(c.name) 
> >   self.__dict__.update({c.name:None}) 
> > self.type_cls=hashabledict({self.name:temp}) 
> > registered_composites[name] = self 
> > 
> > class Caster(psycopg2.extras.CompositeCaster): 
> >   def make(obj, values): 
> > my_dict=hashabledict() 
> > for index,data in enumerate(self.type_cls.items()[0][1]): 
> >   if isinstance(values[index], unicode): 
> > i= values[index].encode("utf-8") 
> > values[index]=i 
> >   my_dict.update({data:values[index]}) 
> > j=hashabledict() 
> > j.update({self.type_cls.items()[0][0]:my_dict}) 
> > return j 
> > 
> > self.caster = Caster 
> > attach_composite_listeners() 
> > 
> >   def bind_processor(self, dialect): 
> > print 'bind_processor' 
> > def process(value): 
> >   if value is None: 
> >   return None 
> >   out='' 
> >   out=out+ ' '.join('{name}'.format(name=i) 
> > for i in self.type_cls.items()[0][1]) 
> >   mylist=[] 
> >   for j in value.items(): 
> > mylist.append(j[1]) 
> >   i=collections.namedtuple(self.name,out) 
> >   return i(*mylist) 
> > return process 
> >   def result_processor(self, dialect, coltype): 
> > print 'result_processor' 
> > # print self.__dict__ 
> > def process(value): 
> >   print 'my values is'+str(value) 
> >   return value 
> >   self.type_cls=value 
> >   
> i=self.__class__(name=value.items()[0][0],columns=value.items()[0][1]) 
> >   # i.set_values(value.items()[0][1],name=value.items()[0][0]) 
> >   return i 
> > return process 
> > 
> >   def __hash__(self): 
> > return make_hash(self) 
> >   def __eq__(self, other): 
> > retu

[sqlalchemy] Re: Postgres Composite Columns

2017-09-18 Thread Tolstov Sergey

>
> Hi, i have some issue. I tried to replace namedtuple to dict and list 
> items (with adding hast function to them). But SQLAlchemy types returns 
> list ordereddict, when i change items, session didn't see changes. Do you 
> found solution?
>
def make_hash(o):
  if isinstance(o,(set,tuple,list)):
for i in o:
  i= tuple([make_hash(e) for e in o])
  return hash(i)
  elif isinstance(o,dict):
pass
i=make_hash([make_hash(j)for j in o.items()])
return hash(i)

  elif isinstance(o,(str,int)):
return hash(o)
  else:
try:
  return hash(o)
except:
  return make_hash(o.__dict__)
return hash(o)


# sys.exit()

class hashabledict(dict):
  def __key(self):
return tuple((k,self[k]) for k in sorted(self))
  def __hash__(self):
print 'try to make_hash'+str(self)+' result = '+ str(make_hash(self))
return make_hash(self)
  def __eq__(self, other):
return make_hash(self) == make_hash(other)

class hashablelist(list):
  def __hash__(self):
return make_hash(self)
  def __eq__(self, other):
return make_hash(self) == make_hash(other)

class MyCompositeType(CompositeType):
  pass
  def __init__(self, name, columns):
if psycopg2 is None:
raise ImproperlyConfigured("'psycopg2' package is required in order 
to use CompositeType.")
sqlalchemy.types.SchemaType.__init__(self)
self.name = name
self.columns = columns
if name in registered_composites:
self.type_cls = registered_composites[name].type_cls
else:
temp=hashablelist()
for c in columns:
  temp.append(c.name)
  self.__dict__.update({c.name:None})
self.type_cls=hashabledict({self.name:temp})
registered_composites[name] = self

class Caster(psycopg2.extras.CompositeCaster):
  def make(obj, values):
my_dict=hashabledict()
for index,data in enumerate(self.type_cls.items()[0][1]):
  if isinstance(values[index], unicode):
i= values[index].encode("utf-8")
values[index]=i
  my_dict.update({data:values[index]})
j=hashabledict()
j.update({self.type_cls.items()[0][0]:my_dict})
return j

self.caster = Caster
attach_composite_listeners()

  def bind_processor(self, dialect):
print 'bind_processor'
def process(value):
  if value is None:
  return None
  out=''
  out=out+ ' '.join('{name}'.format(name=i)
for i in self.type_cls.items()[0][1])
  mylist=[]
  for j in value.items():
mylist.append(j[1])
  i=collections.namedtuple(self.name,out)
  return i(*mylist)
return process
  def result_processor(self, dialect, coltype):
print 'result_processor'
# print self.__dict__
def process(value):
  print 'my values is'+str(value)
  return value
  self.type_cls=value
  i=self.__class__(name=value.items()[0][0],columns=value.items()[0][1])
  # i.set_values(value.items()[0][1],name=value.items()[0][0])
  return i
return process

  def __hash__(self):
return make_hash(self)
  def __eq__(self, other):
return make_hash(self) == make_hash(other)
  def __ne__(self, other):
return make_hash(self) != make_hash(other)


Composite_type = MyCompositeType(
'composite_type',
[
  sqlalchemy.Column('chislo', sqlalchemy.Integer),
  sqlalchemy.Column('slovo', sqlalchemy.String)
]
  ) 

-- 
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 post to this group, send email to sqlalchemy@googlegroups.com.
Visit this group at https://groups.google.com/group/sqlalchemy.
For more options, visit https://groups.google.com/d/optout.