Re: [sqlalchemy] maximum number of expressions in a list is 1000

2013-01-03 Thread Michael Bayer

On Jan 3, 2013, at 2:40 AM, jo wrote:

 Hi all,
 
 I need to use in_(), but in oracle it has a limit of 1000 values,
 there's an alternative syntax that can be used successful in oracle and it is:
 (field,-1) in ( (123,-1), (333,-1), ... )
 
 I tryed this:
 session.query(Mytable).filter((Mytable.c.id,-1).in_([(123,-1),(333,-1)]) )
 
 AttributeError: 'tuple' object has no attribute 'in_'
 
 How can I use this syntax with sa?


I usually handle the Oracle 1000 value limit by running the same query multiple 
times, then merging in memory.

But if you want to do (a, b) IN ((x1, y1), (x2, y2), ...) there's a construct 
called tuple_() that should do it:

 from sqlalchemy import tuple_
 print tuple_(mytable.c.id, -1).in_([tuple_(1, -1), tuple_(2, -1)])
(t.x, :param_1) IN ((:param_2, :param_3), (:param_4, :param_5))


-- 
You received this message because you are subscribed to the Google Groups 
sqlalchemy group.
To post to this group, send email to sqlalchemy@googlegroups.com.
To unsubscribe from this group, send email to 
sqlalchemy+unsubscr...@googlegroups.com.
For more options, visit this group at 
http://groups.google.com/group/sqlalchemy?hl=en.



Re: [sqlalchemy] Got a problem when sqlalchemy 0.8.0b1 works with alembic 0.3.6

2013-01-03 Thread Michael Bayer
PG doesn't allow a length for the TEXT type.

you might want to go with this approach:

mytype = Text().with_variant(MEDIUMTEXT(), 'mysql')

http://docs.sqlalchemy.org/en/rel_0_8/core/types.html?highlight=with_variant#sqlalchemy.types.TypeEngine.with_variant



On Jan 3, 2013, at 9:58 AM, junepeach wrote:

 When I updated sqlalchemy from version 0.7.9 to current one, my mediumtext 
 text type works in Sqlite and Mysql, but doesn't work for Postgresql DB 
 server anymore. I defined:
 mediumtextsize = 2**24 - 1 in my data module. When I run: alembic upgrade 
 head, I got
 
 sqlalchemy.exc.ProgrammingError: (ProgrammingError) type modifier is not 
 allowed for type text
 LINE 6:  status TEXT(16777215),
 
 Not sure what is going on there, does anybody else here has some issue?
 
 Thanks and Happy New Year!
 
 LYH
 
 -- 
 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/-/xfPxnx2TCT4J.
 To post to this group, send email to sqlalchemy@googlegroups.com.
 To unsubscribe from this group, send email to 
 sqlalchemy+unsubscr...@googlegroups.com.
 For more options, visit this group at 
 http://groups.google.com/group/sqlalchemy?hl=en.
 

-- 
You received this message because you are subscribed to the Google Groups 
sqlalchemy group.
To post to this group, send email to sqlalchemy@googlegroups.com.
To unsubscribe from this group, send email to 
sqlalchemy+unsubscr...@googlegroups.com.
For more options, visit this group at 
http://groups.google.com/group/sqlalchemy?hl=en.



[sqlalchemy] automatic company_id insertion

2013-01-03 Thread sjoerd
Hi, 

I have one set of tables and I want to automate the insertion of the 
company_id in queries at certain tables. So I need to define in the models 
which tables are effected, no worries there, but where do I need to 
implement the query manipulation? The SQLAlchemy object is shared between 
different requests (as the configuration remains te same). But the session 
is different, as the company_id differs between sessions. 

Where and how do I implement the query manipulation?!

Thanks

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



Re: [sqlalchemy] automatic company_id insertion

2013-01-03 Thread Michael Bayer

On Jan 3, 2013, at 12:51 PM, sjo...@congressus.nl wrote:

 Hi, 
 
 I have one set of tables and I want to automate the insertion of the 
 company_id in queries at certain tables. So I need to define in the models 
 which tables are effected, no worries there, but where do I need to implement 
 the query manipulation? The SQLAlchemy object is shared between different 
 requests (as the configuration remains te same). But the session is 
 different, as the company_id differs between sessions. 
 
 Where and how do I implement the query manipulation?!

its not clear what usage pattern you're looking for here.   Lets start with the 
obvious, putting company_id in a query:


session.query(SomeObject).filter(SomeObject.company_id == 5)

easy enough.

Now what exactly do you want it to look like?

Like,

session_one.query(SomeClassOne)  - automatically put company_id = 8
session_two.query(SomeClassTwo)   - automatically put company_id = 15

?

if I'm given session_one and SomeClassOne, what is the company_id for 
that ?

There's a pattern for auto-querying of a certain column at 
http://www.sqlalchemy.org/trac/wiki/UsageRecipes/PreFilteredQuery .   But this 
doesn't get into how to determine where the custom criterion would come from.


-- 
You received this message because you are subscribed to the Google Groups 
sqlalchemy group.
To post to this group, send email to sqlalchemy@googlegroups.com.
To unsubscribe from this group, send email to 
sqlalchemy+unsubscr...@googlegroups.com.
For more options, visit this group at 
http://groups.google.com/group/sqlalchemy?hl=en.



Re: [sqlalchemy] Got a problem when sqlalchemy 0.8.0b1 works with alembic 0.3.6

2013-01-03 Thread junepeach
Thank you! I will try :)

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



Re: [sqlalchemy] automatic company_id insertion

2013-01-03 Thread sjoerd


On Thursday, January 3, 2013 8:05:29 PM UTC+1, Michael Bayer wrote:


 On Jan 3, 2013, at 12:51 PM, sjo...@congressus.nl javascript: wrote:

 Hi, 

 I have one set of tables and I want to automate the insertion of the 
 company_id in queries at certain tables. So I need to define in the models 
 which tables are effected, no worries there, but where do I need to 
 implement the query manipulation? The SQLAlchemy object is shared between 
 different requests (as the configuration remains te same). But the session 
 is different, as the company_id differs between sessions. 

 Where and how do I implement the query manipulation?!


 its not clear what usage pattern you're looking for here.   Lets start 
 with the obvious, putting company_id in a query:


 session.query(SomeObject).filter(SomeObject.company_id == 5)

 easy enough.

 Now what exactly do you want it to look like?

 Like,

 session_one.query(SomeClassOne)  - automatically put company_id = 8
 session_two.query(SomeClassTwo)   - automatically put company_id 
 = 15

 ?

 if I'm given session_one and SomeClassOne, what is the company_id 
 for that ?

 There's a pattern for auto-querying of a certain column at 
 http://www.sqlalchemy.org/trac/wiki/UsageRecipes/PreFilteredQuery .   But 
 this doesn't get into how to determine where the custom criterion would 
 come from.


Thanks for your guided questions and the example pattern. Indeed the basic 
query would be
session.query(SomeObject).filter(SomeObject.loginname.like(example)).filter(SomeObject.company_id
 
== SomeHTTPSessionGlobal.company_id)

As this query is extension is used many times in my codebase (due to the 
multi-tentancy nature of the concept) I want to automate this. I have 
implemented and new Query-class;

session = sessionmaker(bind=engine, query_cls=MyQuery)


In this MyQuery two things need to happen; A) check whether the queried table 
has the certain company_id field and B) automatically implement the additional 
filter to add the SomeHTTPSessionGlobal.company_id (which is based on the 
sub-domain)
= Is by altering the get(), __ite__ and from_self() functions enough to effect 
all queries?
= How to get the adjusted table and detect whether an company_id field exists?

In such that when the SomeObject has an field company_id, it automatically 
applies an additional filter. So that my query in the code may be;

session.query(SomeObject).filter(SomeObject.loginname.like(example))

Thanks





 

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



Re: [sqlalchemy] automatic company_id insertion

2013-01-03 Thread Michael Bayer

On Jan 3, 2013, at 3:17 PM, sjo...@congressus.nl wrote:

 In this MyQuery two things need to happen; A) check whether the queried table 
 has the certain company_id field and B) automatically implement the 
 additional filter to add the SomeHTTPSessionGlobal.company_id (which is based 
 on the sub-domain)
 = Is by altering the get(), __ite__ and from_self() functions enough to 
 effect all queries?
 = How to get the adjusted table and detect whether an company_id field 
 exists?


the vast majority of queries go through __iter__(), so that's probably all you 
need.from_self() and get() are not as common - though get() will be used 
for a many-to-one lazy load in most cases, if this class is the target of a 
many-to-one relationship().

If you're dealing with mapped classes, a simple enough check is 
hasattr(MyClass, 'company_id').Within Query, calling _mapper_zero().class_ 
gives you this class, assuming the query is against a single full entity like 
query(MyClass).


-- 
You received this message because you are subscribed to the Google Groups 
sqlalchemy group.
To post to this group, send email to sqlalchemy@googlegroups.com.
To unsubscribe from this group, send email to 
sqlalchemy+unsubscr...@googlegroups.com.
For more options, visit this group at 
http://groups.google.com/group/sqlalchemy?hl=en.



[sqlalchemy] Filter expression in an association proxy?

2013-01-03 Thread Chuck Bearden
Python 2.7.2
SQLAlchemy 0.8.0b2
Ubuntu 11.10

Consider the script below. The idea is that I have a medical record, and I 
want to store diagnoses of two kinds: referring diagnoses and 
post-evaluation diagnoses. I want to store them in a single table (this 
constraint is given by the project I inherited). By means of the 
relationships  association proxies defined below, I can correctly store 
diagnoses of both sorts. However, I am unable to retrieve only the 
diagnoses of one sort or the other by means of the proxy. Is there a way to 
incorporate a filter expression in a relationship/association_proxy to 
enable retrieval of only certain values from the proxied table? Or are 
there other techniques (short of creating separate tables for referring  
post-evaluation diagnoses)?

Thanks for any suggestions!
Chuck

#- script --#
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
from sqlalchemy import (
Column,
Integer,
ForeignKey,
String,
)
from sqlalchemy.ext.associationproxy import association_proxy

from sqlalchemy.orm import relationship
Base = declarative_base()

class MedicalRecord(Base):
__tablename__ = 'medicalrecord'
id = Column(Integer, primary_key=True)
patientname = Column(String(80))
# Use the Diagnoses table with dxtype='referring'
rel_referring_diagnoses = relationship(
  Diagnoses, 
  cascade=all,delete-orphan
)
referring_diagnoses = association_proxy(
  'rel_referring_diagnoses',
  'diagnosis',
  creator=lambda dx: Diagnoses(diagnosis=dx, dxtype='referring')
)
# Use the Diagnoses table with dxtype='posteval'
rel_posteval_diagnoses = relationship(
  Diagnoses,
  cascade=all,delete-orphan
)
posteval_diagnoses = association_proxy(
  'rel_posteval_diagnoses',
  'diagnosis',
  creator=lambda dx: Diagnoses(diagnosis=dx, dxtype='posteval')
)


class Diagnoses(Base):
__tablename__ = 'diagnoses'
id = Column(Integer, primary_key=True)
patient_id = Column(Integer, ForeignKey('medicalrecord.id', \
  ondelete='cascade'))
diagnosis = Column(String(80))
dxtype = Column(String(40))

if __name__ == '__main__':
engine = create_engine('postgresql://foo:bar@localhost/baz')
Session = sessionmaker(bind=engine)
session = Session()
Base.metadata.create_all(engine)

new_record = MedicalRecord()
new_record.patientname = 'Fred'
session.add(new_record)
new_record.referring_diagnoses.append('runny nose')
session.commit()
# This will print 'runny nose'; I want it to print nothing
print new_record.posteval_diagnoses
# Database has:
# baz= select * from diagnoses;
#  id | patient_id | diagnosis  |  dxtype   
# +++---
#   1 |  1 | runny nose | referring
# (1 row)

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



Re: [sqlalchemy] automatic company_id insertion

2013-01-03 Thread sjoerd


On Thursday, January 3, 2013 9:31:37 PM UTC+1, Michael Bayer wrote:


 On Jan 3, 2013, at 3:17 PM, sjo...@congressus.nl javascript: wrote:

 In this MyQuery two things need to happen; A) check whether the queried table 
 has the certain company_id field and B) automatically implement the 
 additional filter to add the SomeHTTPSessionGlobal.company_id (which is based 
 on the sub-domain)
 = Is by altering the get(), __ite__ and from_self() functions enough to 
 effect all queries?
 = How to get the adjusted table and detect whether an company_id field 
 exists?



 the vast majority of queries go through __iter__(), so that's probably all 
 you need.from_self() and get() are not as common - though get() will be 
 used for a many-to-one lazy load in most cases, if this class is the target 
 of a many-to-one relationship().

 If you're dealing with mapped classes, a simple enough check is 
 hasattr(MyClass, 'company_id').Within Query, calling 
 _mapper_zero().class_ gives you this class, assuming the query is against a 
 single full entity like query(MyClass).



It is working, thanks for your help and additional explanation! 

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



Re: [sqlalchemy] Filter expression in an association proxy?

2013-01-03 Thread Michael Bayer

On Jan 3, 2013, at 4:01 PM, Chuck Bearden wrote:

 Python 2.7.2
 SQLAlchemy 0.8.0b2
 Ubuntu 11.10
 
 Consider the script below. The idea is that I have a medical record, and I 
 want to store diagnoses of two kinds: referring diagnoses and post-evaluation 
 diagnoses. I want to store them in a single table (this constraint is given 
 by the project I inherited). By means of the relationships  association 
 proxies defined below, I can correctly store diagnoses of both sorts. 
 However, I am unable to retrieve only the diagnoses of one sort or the other 
 by means of the proxy. Is there a way to incorporate a filter expression in a 
 relationship/association_proxy to enable retrieval of only certain values 
 from the proxied table? Or are there other techniques (short of creating 
 separate tables for referring  post-evaluation diagnoses)?
 
 Thanks for any suggestions!


the ultimate relationship() that's being proxied needs to filter on the 
dxtype attribute using a custom primaryjoin condition.   See 
http://docs.sqlalchemy.org/en/rel_0_8/orm/relationships.html#specifying-alternate-join-conditions
 for an example of how this looks.



 Chuck
 
 #- script --#
 from sqlalchemy.ext.declarative import declarative_base
 from sqlalchemy import create_engine
 from sqlalchemy.orm import sessionmaker
 from sqlalchemy import (
 Column,
 Integer,
 ForeignKey,
 String,
 )
 from sqlalchemy.ext.associationproxy import association_proxy
 
 from sqlalchemy.orm import relationship
 Base = declarative_base()
 
 class MedicalRecord(Base):
 __tablename__ = 'medicalrecord'
 id = Column(Integer, primary_key=True)
 patientname = Column(String(80))
 # Use the Diagnoses table with dxtype='referring'
 rel_referring_diagnoses = relationship(
   Diagnoses, 
   cascade=all,delete-orphan
 )
 referring_diagnoses = association_proxy(
   'rel_referring_diagnoses',
   'diagnosis',
   creator=lambda dx: Diagnoses(diagnosis=dx, dxtype='referring')
 )
 # Use the Diagnoses table with dxtype='posteval'
 rel_posteval_diagnoses = relationship(
   Diagnoses,
   cascade=all,delete-orphan
 )
 posteval_diagnoses = association_proxy(
   'rel_posteval_diagnoses',
   'diagnosis',
   creator=lambda dx: Diagnoses(diagnosis=dx, dxtype='posteval')
 )
 
 
 class Diagnoses(Base):
 __tablename__ = 'diagnoses'
 id = Column(Integer, primary_key=True)
 patient_id = Column(Integer, ForeignKey('medicalrecord.id', \
   ondelete='cascade'))
 diagnosis = Column(String(80))
 dxtype = Column(String(40))
 
 if __name__ == '__main__':
 engine = create_engine('postgresql://foo:bar@localhost/baz')
 Session = sessionmaker(bind=engine)
 session = Session()
 Base.metadata.create_all(engine)
 
 new_record = MedicalRecord()
 new_record.patientname = 'Fred'
 session.add(new_record)
 new_record.referring_diagnoses.append('runny nose')
 session.commit()
 # This will print 'runny nose'; I want it to print nothing
 print new_record.posteval_diagnoses
 # Database has:
 # baz= select * from diagnoses;
 #  id | patient_id | diagnosis  |  dxtype   
 # +++---
 #   1 |  1 | runny nose | referring
 # (1 row)
 
 -- 
 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/-/WEfhR1WcGosJ.
 To post to this group, send email to sqlalchemy@googlegroups.com.
 To unsubscribe from this group, send email to 
 sqlalchemy+unsubscr...@googlegroups.com.
 For more options, visit this group at 
 http://groups.google.com/group/sqlalchemy?hl=en.

-- 
You received this message because you are subscribed to the Google Groups 
sqlalchemy group.
To post to this group, send email to sqlalchemy@googlegroups.com.
To unsubscribe from this group, send email to 
sqlalchemy+unsubscr...@googlegroups.com.
For more options, visit this group at 
http://groups.google.com/group/sqlalchemy?hl=en.



Re: [sqlalchemy] Filter expression in an association proxy?

2013-01-03 Thread Chuck Bearden
On Thursday, January 3, 2013 3:13:58 PM UTC-6, Michael Bayer wrote:


 On Jan 3, 2013, at 4:01 PM, Chuck Bearden wrote:

 Python 2.7.2
 SQLAlchemy 0.8.0b2
 Ubuntu 11.10

 Consider the script below. The idea is that I have a medical record, and I 
 want to store diagnoses of two kinds: referring diagnoses and 
 post-evaluation diagnoses. I want to store them in a single table (this 
 constraint is given by the project I inherited). By means of the 
 relationships  association proxies defined below, I can correctly store 
 diagnoses of both sorts. However, I am unable to retrieve only the 
 diagnoses of one sort or the other by means of the proxy. Is there a way to 
 incorporate a filter expression in a relationship/association_proxy to 
 enable retrieval of only certain values from the proxied table? Or are 
 there other techniques (short of creating separate tables for referring  
 post-evaluation diagnoses)?

 Thanks for any suggestions!



 the ultimate relationship() that's being proxied needs to filter on the 
 dxtype attribute using a custom primaryjoin condition.   See 
 http://docs.sqlalchemy.org/en/rel_0_8/orm/relationships.html#specifying-alternate-join-conditionsfor
  an example of how this looks.


Perfect! Thank you for the pointer.

Chuck

#- script --#
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
from sqlalchemy import (
Column,
Integer,
ForeignKey,
String,
)
from sqlalchemy.ext.associationproxy import association_proxy

from sqlalchemy.orm import relationship
Base = declarative_base()

class MedicalRecord(Base):
__tablename__ = 'medicalrecord'
id = Column(Integer, primary_key=True)
patientname = Column(String(80))
# Use the Diagnoses table with dxtype='referring'
rel_referring_diagnoses = relationship(
  Diagnoses, 
  cascade=all,delete-orphan
)
referring_diagnoses = association_proxy(
  'rel_referring_diagnoses',
  'diagnosis',
  creator=lambda dx: Diagnoses(diagnosis=dx, dxtype='referring')
)
# Use the Diagnoses table with dxtype='posteval'
rel_posteval_diagnoses = relationship(
  Diagnoses,
  cascade=all,delete-orphan
)
posteval_diagnoses = association_proxy(
  'rel_posteval_diagnoses',
  'diagnosis',
  creator=lambda dx: Diagnoses(diagnosis=dx, dxtype='posteval')
)


class Diagnoses(Base):
__tablename__ = 'diagnoses'
id = Column(Integer, primary_key=True)
patient_id = Column(Integer, ForeignKey('medicalrecord.id', \
  ondelete='cascade'))
diagnosis = Column(String(80))
dxtype = Column(String(40))

if __name__ == '__main__':
engine = create_engine('postgresql://foo:bar@localhost/baz')
Session = sessionmaker(bind=engine)
session = Session()
Base.metadata.create_all(engine)

new_record = MedicalRecord()
new_record.patientname = 'Fred'
session.add(new_record)
new_record.referring_diagnoses.append('runny nose')
session.commit()
# This will print 'runny nose'; I want it to print nothing
print new_record.posteval_diagnoses
# Database has:
# baz= select * from diagnoses;
#  id | patient_id | diagnosis  |  dxtype   
# +++---
#   1 |  1 | runny nose | referring
# (1 row)

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




-- 
You received this message because you are subscribed to the Google Groups 
sqlalchemy group.
To view this discussion on the web visit 
https://groups.google.com/d/msg/sqlalchemy/-/aBICNiOX-yYJ.
To post to this group, send email to sqlalchemy@googlegroups.com.
To unsubscribe from this group, send email to 
sqlalchemy+unsubscr...@googlegroups.com.
For more options, visit this group at 
http://groups.google.com/group/sqlalchemy?hl=en.



[sqlalchemy] max() min() string lengths?

2013-01-03 Thread James Hartley
 Embarrassingly, I'm gotten lost in calling SQL functions in SQLAlchemy
0.7.1.

I can boil the problem down to the following table structure:

CREATE TABLE words (
id INTEGER NOT NULL,
timestamp DATETIME NOT NULL,
word TEXT NOT NULL,
PRIMARY KEY (id),
UNIQUE (word)
);

...where I would like to find the maximum  minimum stored string lengths.
eg.

SELECT MAX(LENGTH(word), MAX(LENGTH(word)) FROM words;

The code below constructs  populates the table correctly, but translating
the above SQL into something more Pythonic is eluding me.  Any suggestions
would be welcomed, as I'm in a rut.

Thanks.

#8

#!/usr/bin/env python

from datetime import datetime

from sqlalchemy import create_engine, Column, func
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker
from sqlalchemy.dialects.sqlite import INTEGER, DATETIME, TEXT

Base = declarative_base()

def get_dbname():
return 'test.db'

class Word(Base):
__tablename__ = 'words'

id = Column(INTEGER, primary_key=True)
timestamp = Column(DATETIME, nullable=False, default=datetime.now())
word = Column(TEXT, nullable=False, unique=True)

def __init__(self, word):
self.word = word

def __repr__(self):
return 'Word(%d, %s, %s)' % (self.id, self.timestamp, self.word)

if __name__ == '__main__':
engine = create_engine('sqlite:///' + get_dbname(), echo=True)
Base.metadata.create_all(engine)
Session = sessionmaker(bind=engine)
session = Session()

words = THE OF AND TO A IN THAT IS WAS HE FOR IT WITH AS HIS ON BE AT
SAME ANOTHER KNOW WHILE LAST.split()

for w in words:
session.add(Word(w))
session.commit()

print 'total words = %d' % session.query(Word).count()

# minimum length = ?
# maximum length = ?

-- 
You received this message because you are subscribed to the Google Groups 
sqlalchemy group.
To post to this group, send email to sqlalchemy@googlegroups.com.
To unsubscribe from this group, send email to 
sqlalchemy+unsubscr...@googlegroups.com.
For more options, visit this group at 
http://groups.google.com/group/sqlalchemy?hl=en.



[sqlalchemy] How to handle 'sub-commits'?

2013-01-03 Thread Ken Lareau
I recently (today) ran into an issue that has me perplexed as to how to
resolve it,
so I'm asking here to see if anyone can shed some insight.  Hopefully I can
ex-
plain it clearly enough to make me not sound completely incompetent...

I currently have an application that during it's run starts a session via
SQLAlchemy
to one of our databases and keeps it available until the program exits.
During this
time it does multiple changes (primarily inserts and updates) to the
database, but
of course nothing is actually written to the database until a commit() is
done.  The
problem is that there are times when I have a single change that must be
available
in the database immediately due to external resources needing to access to
that
updated/new information.

Initially I thought that using 'begin_nested()' .. 'commit()' would
accomplish this
(possibly naively), but found out today in a very bad way that it did not;
after re-
reading the documentation this became abundantly clear.  Further analysis
of my
current code revealed that I actually do not need to have 'isolated'
commits from
within a transaction, but I have this feeling as I expand my usage of the
library
I've created to deal with the database access I may find a need for this;
the only
other option is to keep track of every single change in any application
that re-
quires this and create a 'reverse' set of changes if I need to rollback.

So this leads to the question: is there any way to do an 'isolated' commit
from
within a session and if so, how is it done?  As an alternative, is there a
way to
use temporary new sessions to accomplish the same thing?  My current use
in my application is I have a 'Session = scoped_session(sessionmaker())'
line
in a module which I import wherever I need it (essentially as a singleton)
to be
able to access the same session throughout the code.  This would of course
need to change, at least with an application requiring such 'sub commits'.

If any further clarification is needed on the above, please don't hesitate
to ask,
and I thank folks in advance for any assistance they can give.

-- 
- Ken Lareau

-- 
You received this message because you are subscribed to the Google Groups 
sqlalchemy group.
To post to this group, send email to sqlalchemy@googlegroups.com.
To unsubscribe from this group, send email to 
sqlalchemy+unsubscr...@googlegroups.com.
For more options, visit this group at 
http://groups.google.com/group/sqlalchemy?hl=en.



Re: [sqlalchemy] maximum number of expressions in a list is 1000

2013-01-03 Thread jo

_tuple() is fine,
Thanks Michael :-)
j

Michael Bayer wrote:

On Jan 3, 2013, at 2:40 AM, jo wrote:

  

Hi all,

I need to use in_(), but in oracle it has a limit of 1000 values,
there's an alternative syntax that can be used successful in oracle and it is:
(field,-1) in ( (123,-1), (333,-1), ... )

I tryed this:
session.query(Mytable).filter((Mytable.c.id,-1).in_([(123,-1),(333,-1)]) )

AttributeError: 'tuple' object has no attribute 'in_'

How can I use this syntax with sa?




I usually handle the Oracle 1000 value limit by running the same query multiple 
times, then merging in memory.

But if you want to do (a, b) IN ((x1, y1), (x2, y2), ...) there's a construct 
called tuple_() that should do it:

  

from sqlalchemy import tuple_
print tuple_(mytable.c.id, -1).in_([tuple_(1, -1), tuple_(2, -1)])


(t.x, :param_1) IN ((:param_2, :param_3), (:param_4, :param_5))


  



--
Jose Soares Da Silva _/_/
Sferacarta Net
Via Bazzanese 69   _/_/_/_/_/
40033 Casalecchio di Reno _/_/  _/_/  _/_/
Bologna - Italy  _/_/  _/_/  _/_/
Ph  +39051591054  _/_/  _/_/  _/_/  _/_/
fax +390516131537_/_/  _/_/  _/_/  _/_/
web:www.sferacarta.com_/_/_/  _/_/_/

Le informazioni contenute nella presente mail ed in ogni eventuale file 
allegato sono riservate e, comunque, destinate esclusivamente alla persona o 
ente sopraindicati, ai sensi del decreto legislativo 30 giugno 2003, n. 196. La 
diffusione, distribuzione e/o copiatura della mail trasmessa, da parte di 
qualsiasi soggetto diverso dal destinatario, sono vietate. La correttezza, 
l’integrità e la sicurezza della presente mail non possono essere garantite. Se 
avete ricevuto questa mail per errore, Vi preghiamo di contattarci 
immediatamente e di eliminarla. Grazie.

This communication is intended only for use by the addressee, pursuant to 
legislative decree 30 June 2003, n. 196. It may contain confidential or 
privileged information. You should not copy or use it to disclose its contents 
to any other person. Transmission cannot be guaranteed to be error-free, 
complete and secure. If you are not the intended recipient and receive this 
communication unintentionally, please inform us immediately and then delete 
this message from your system. Thank you.

--
You received this message because you are subscribed to the Google Groups 
sqlalchemy group.
To post to this group, send email to sqlalchemy@googlegroups.com.
To unsubscribe from this group, send email to 
sqlalchemy+unsubscr...@googlegroups.com.
For more options, visit this group at 
http://groups.google.com/group/sqlalchemy?hl=en.



[sqlalchemy] Query about exception being raised on violating uniqueness constraint

2013-01-03 Thread Gurjar, Unmesh
Hi,

I have installed SQLAlchemy 0.7.9 (backend - MySQL, Python 2.7). I have a 
defined a table having a uniqueness constraint. On inserting a record which 
violates this constraint, my application gets a 'TypeError' exception instead 
of 'IntegrityError'.

After debugging the issue, I found that it can be resolved by replacing the 
'raise' statement by 'raise exc' in _flush( ) method of 
sqlalchemy/orm/session.py. Can someone please confirm if this should be the 
expected behavior?

Thanks  Regards,
Unmesh Gurjar.


__
Disclaimer:This email and any attachments are sent in strictest confidence for 
the sole use of the addressee and may contain legally privileged, confidential, 
and proprietary data.  If you are not the intended recipient, please advise the 
sender by replying promptly to this email and then delete and destroy this 
email and any attachments without any further use, copying or forwarding

-- 
You received this message because you are subscribed to the Google Groups 
sqlalchemy group.
To post to this group, send email to sqlalchemy@googlegroups.com.
To unsubscribe from this group, send email to 
sqlalchemy+unsubscr...@googlegroups.com.
For more options, visit this group at 
http://groups.google.com/group/sqlalchemy?hl=en.