Re: [sqlalchemy] Convert Declarative definitions to Table definitions

2010-12-06 Thread Thadeus Burgess
I use ENUM types for postgres. Reflection does not preserve the ENUM name
within its sequence. Name is required on postgres. I don't want to edit my
50+ tables and add names to them just for a migration, this is why
reflection does not work in my case.

--
Thadeus




On Mon, Dec 6, 2010 at 4:29 PM, Chris Withers ch...@simplistix.co.ukwrote:

 rate, you're better off reflecting the tables to be migrated rather than
 using any script to try and turn declarative models into table definitio

-- 
You received this message because you are subscribed to the Google Groups 
sqlalchemy group.
To post to this group, send email to sqlalch...@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] finding if a table is already join in a query

2010-12-05 Thread Thadeus Burgess
What if your query already has a join yet you need to add another WHERE
clause to the join? This fails with This query already has a join for Table
xxx. Any way to modify your join to a query after you join it?

--
Thadeus




On Wed, Dec 1, 2010 at 8:08 AM, Michael Bayer mike...@zzzcomputing.comwrote:


 On Dec 1, 2010, at 1:28 AM, James Neethling wrote:

 
  if you would like multiple references to Address to all work from the
 same join, your routine needs to track which entities have already been
 joined as a destination in a separate collection:
 
 
  def search(columns):
   already_joined = set()
 ...
 if class_ not in already_joined:
   q = q.join(destination)
   already_joined.add(class_)
 
  Hi Michael,
 
  Thank you for the quick response.
 
  Unfortunately we don't always know where this query comes from (my
  example was a little contrived :( )
 
  Is there any way to get the tables that are currently in the join for a
  query?

 You can iterate through q._from_obj(), and for each object that is a
 join(), recursively descend through j.left and j.right looking for Table
 objects. Table objects can be embedded in subqueries and alias objects
 too but I'm assuming your query buildup here is simple enough that gray
 areas like that aren't expected.

 If it were me, I'd not be passing a raw Query around, I'd have it wrapped
 inside a facade that is doing the abovementioned tracking of important state
 explicitly (and also ensuring that those more grayish areas aren't occurring
 with this particular Query).   That way any other interesting facts about
 the query as built so far can be tracked as well.   Also easier to unit
 test.



 
 
  Here is a cut down sample implementation that will hopefully remove any
  confusion... Note the TODO: in Employee.search()
 
 
 ---8---8---8
 
  from sqlalchemy import create_engine, Column, ForeignKey, or_
  from sqlalchemy.ext.declarative import declarative_base
  from sqlalchemy.orm import scoped_session, sessionmaker, relationship,
  joinedload
  from sqlalchemy.types import Integer, String, Text
  from sqlalchemy.sql.expression import cast
 
  engine = create_engine('sqlite:///:memory:', echo=True)
  Base = declarative_base(bind=engine)
  Session = scoped_session(sessionmaker(bind=engine))
 
 
  class Employee(Base):
__tablename__ = 'employee'
id = Column(Integer, primary_key=True)
name = Column(String)
 
def search(self, value, columns):
  query = Session.query(Employee)
for i, column in enumerate(columns):
model = column.parententity.class_
if Employee is not model:
  #TODO: Are we already joined from Employee onto model?
query = query.outerjoin(model)
args = [cast(c, Text).ilike('%%%s%%' % value) for c in columns]
return query.filter(or_(*args))
 
  class Address(Base):
__tablename__ = 'address'
id = Column(Integer, primary_key=True)
employee_id = Column(Integer, ForeignKey(Employee.id))
street1 =  Column(String(50))
street2 =  Column(String(50))
employee = relationship(Employee)
 
  Base.metadata.create_all()
 
 
  #e = Employee(name='Bob')
  #a = Address(employee=e, street1='street1', street2='street2')
  #Session.add(a)
  #Session.commit()
 
 
  q = Employee().search('stree', [Employee.name, Address.street1,
  Address.street2])
  print q
  
  SELECT employee.id AS employee_id, employee.name AS employee_name
  FROM employee LEFT OUTER JOIN address ON employee.id =
  address.employee_id LEFT OUTER JOIN address ON employee.id =
  address.employee_id
  WHERE lower(CAST(employee.name AS TEXT)) LIKE lower(?) OR
  lower(CAST(address.street1 AS TEXT)) LIKE lower(?) OR
  lower(CAST(address.street2 AS TEXT)) LIKE lower(?)
  
 
 ---8---8---8
 
  TIA
  Jim
 
 
  --
  You received this message because you are subscribed to the Google
 Groups sqlalchemy group.
  To post to this group, send email to sqlalch...@googlegroups.com.
  To unsubscribe from this group, send email to
 sqlalchemy+unsubscr...@googlegroups.comsqlalchemy%2bunsubscr...@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 sqlalch...@googlegroups.com.
  To unsubscribe from this group, send email to
 sqlalchemy+unsubscr...@googlegroups.comsqlalchemy%2bunsubscr...@googlegroups.com
 .
  For more options, visit this group at
 http://groups.google.com/group/sqlalchemy?hl=en.
 
 
 
  --
  James Neethling
  Development Manager
  XO Africa Safari
  (t) +27 21 486 2700 (ext. 127)
  (e) jam...@xoafrica.com
 
 
  --
  You received this message because you are subscribed to the Google Groups
 sqlalchemy group.
  To post to this 

[sqlalchemy] Convert Declarative definitions to Table definitions

2010-12-03 Thread Thadeus Burgess
I'm about to use sqlalchemy-migrate, however all of my tables are already in
a declarative format.

Is there a script out there that will convert a declarative model syntax to
table model? I'm looking to just paste my model in declarative and it spit
out a tablename = Table(...) format for me to paste into the migration
versioning files.

--
Thadeus

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



[sqlalchemy] Re: Convert Declarative definitions to Table definitions

2010-12-03 Thread Thadeus Burgess
Ok, it was easier I thought with much thanks to the great __repr__() strings
that SQLAlchemy uses... made life so much easier

Here is the script I used, just pass the class object to the function and it
returns a string in table_name = Table(...) form.

Since this is just being used for sqlalchemy-migrate there is no need for
default or onupdate definitions, which contain function pointers in the
repr() anyways so they didn't work 100%



import re

def convert_model_to_table(model):
out = %s = Table('%s', meta,\n % (model.__tablename__,
model.__tablename__)

columns = model._sa_class_manager.mapper.local_table.c

for k in columns.keys():
c = columns.get(k)

declr = c.__repr__()

declr = declr.replace('table=%s' % model.__tablename__, '')

declr = re.sub('default=.*?\)', '', declr)
declr = re.sub('onupdate=.*?\)', '', declr)
declr = declr.replace(' ,', '')

out += '%s,\n' % declr

out += ')'

return out

def get_tables(models):
print 
print #, - * 79
print 
for m in models:
print convert_model_to_table(m)
print 
print #, - * 79
print 

--
Thadeus




On Fri, Dec 3, 2010 at 1:02 PM, Thadeus Burgess thade...@thadeusb.comwrote:

 I'm about to use sqlalchemy-migrate, however all of my tables are already
 in a declarative format.

 Is there a script out there that will convert a declarative model syntax to
 table model? I'm looking to just paste my model in declarative and it spit
 out a tablename = Table(...) format for me to paste into the migration
 versioning files.

 --
 Thadeus




-- 
You received this message because you are subscribed to the Google Groups 
sqlalchemy group.
To post to this group, send email to sqlalch...@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] How can I change manually the value of field with onupdate option ? I would like override onupdate mechanism

2010-10-28 Thread Thadeus Burgess
I actually have this same issue as well..

I have a field that means the record has been tested. Any updates to the
field make tested = False, all except for one other field. However when I
updated that field and this field it still gets reset to false..


record.approved=True
record.tested=True

db.session.commit()

record.approved is True
record.tested is False

--
Thadeus




On Thu, Oct 28, 2010 at 10:15 AM, Alexandre Conrad 
alexandre.con...@gmail.com wrote:

 Not sure on this one, but are you passing a formatted date string? Maybe
 you should set a datetime object directly and let SA do the string
 conversion during flush.

 Alex

 Sent from my fantastic HTC Hero

 On Oct 28, 2010 1:41 AM, KLEIN Stéphane klein.steph...@gmail.com
 wrote:

 Hi,

 in my project, I use onupdate attribute :

 foobar_table = Table(FooBar, meta.metadata,
 ...
Column(created, DateTime(), default=datetime.datetime.now),
Column(modified, DateTime(), default=datetime.datetime.now,
 onupdate=datetime.datetime.now),
 ...
 )

 All work great.

 However, my project have an importation feature and I need to set
 original modified field value.

 To do that, I've try this solution :

 my_foobar_obj.modifield =
 datetime.datetime.strptime(source_date_value, '%Y-%m-%d %H:%M:%S')
 session.commit()

 = not success, modified field not contain source_date_value but
 current date

 Other solution :

 foobar_table.update().\
where(foobar_table.c.id==my_foobar_obj.id).\

 values(modified=datetime.datetime.strptime(source_date_value, '%Y-%m-
 %d %H:%M:%S'))

 = not success, modified field not contain source_date_value but
 current date

 Have you a tips to manually change modified field value ?

 Thanks for your help,
 Stephane

 --
 You received this message because you are subscribed to the Google Groups
 sqlalchemy group.
 To post to this group, send email to sqlalch...@googlegroups.com.
 To unsubscribe from this group, send email to
 sqlalchemy+unsubscr...@googlegroups.comsqlalchemy%2bunsubscr...@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 sqlalch...@googlegroups.com.
 To unsubscribe from this group, send email to
 sqlalchemy+unsubscr...@googlegroups.comsqlalchemy%2bunsubscr...@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 sqlalch...@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] How can I change manually the value of field with onupdate option ? I would like override onupdate mechanism

2010-10-28 Thread Thadeus Burgess
The only way around this is to do two separate commits

record.approved = True
db.session.commit()
record.tested = True
db.session.commit()

record.approved is True
record.tested is True

--
Thadeus




On Thu, Oct 28, 2010 at 2:22 PM, Thadeus Burgess thade...@thadeusb.comwrote:

 I actually have this same issue as well..

 I have a field that means the record has been tested. Any updates to the
 field make tested = False, all except for one other field. However when I
 updated that field and this field it still gets reset to false..


 record.approved=True
 record.tested=True

 db.session.commit()

 record.approved is True
 record.tested is False

 --
 Thadeus





 On Thu, Oct 28, 2010 at 10:15 AM, Alexandre Conrad 
 alexandre.con...@gmail.com wrote:

 Not sure on this one, but are you passing a formatted date string? Maybe
 you should set a datetime object directly and let SA do the string
 conversion during flush.

 Alex

 Sent from my fantastic HTC Hero

 On Oct 28, 2010 1:41 AM, KLEIN Stéphane klein.steph...@gmail.com
 wrote:

 Hi,

 in my project, I use onupdate attribute :

 foobar_table = Table(FooBar, meta.metadata,
 ...
Column(created, DateTime(), default=datetime.datetime.now),
Column(modified, DateTime(), default=datetime.datetime.now,
 onupdate=datetime.datetime.now),
 ...
 )

 All work great.

 However, my project have an importation feature and I need to set
 original modified field value.

 To do that, I've try this solution :

 my_foobar_obj.modifield =
 datetime.datetime.strptime(source_date_value, '%Y-%m-%d %H:%M:%S')
 session.commit()

 = not success, modified field not contain source_date_value but
 current date

 Other solution :

 foobar_table.update().\
where(foobar_table.c.id==my_foobar_obj.id).\

 values(modified=datetime.datetime.strptime(source_date_value, '%Y-%m-
 %d %H:%M:%S'))

 = not success, modified field not contain source_date_value but
 current date

 Have you a tips to manually change modified field value ?

 Thanks for your help,
 Stephane

 --
 You received this message because you are subscribed to the Google Groups
 sqlalchemy group.
 To post to this group, send email to sqlalch...@googlegroups.com.
 To unsubscribe from this group, send email to
 sqlalchemy+unsubscr...@googlegroups.comsqlalchemy%2bunsubscr...@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 sqlalch...@googlegroups.com.
 To unsubscribe from this group, send email to
 sqlalchemy+unsubscr...@googlegroups.comsqlalchemy%2bunsubscr...@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 sqlalch...@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] Checking the availablity of a booked Item

2010-10-20 Thread Thadeus Burgess
Here is an example of how I use outerjoin to perform a similar query.


class Survey, def get_apps(self):

Get all persons who are over 18 and do not have an appointment but have this
survey.

qry = Person.query.filter(Person.age  18)

qry = qry.outerjoin((Appointment,
(Appointment.id_person == Person.id)
(Appointment.id_survey == self.id))). \
  filter(Appointment.id == None) #: Or != None, depending on the
type of join.

#: I go and append a few more outer joins here as well,# but they look
exactly the same just different tables.

The syntax of the outerjoin arguments is a tuple containing (Table to join
to, whereclause to join on).

Hopefully this helps you. Basically, I just look at the coding horror site
for the kind of join I want to perform, and modify the syntax above to make
it match the SQL.

--
Thadeus




On Mon, Oct 18, 2010 at 10:38 AM, chaouche yacine
yacinechaou...@yahoo.comwrote:

 Hello,

 I think outerjoin is just a join with an isouter = True, and above all the
 problem was not there anyway. The problem was only about ordering the joins.
 The correct python code was :

 Face.query.outerjoin(Face.bookings).filter(cond).all()

 instead of

 Face.query.outerjoin(Booking.faces).filter(cond).all()

 Which looks more intuitive to me, because I'm doing joins between Face and
 Booking (thus putting Booking in the outerjoin, not Face again as in the
 first code). I can't understand the logic of the (correct) first one, but it
 works ! Or is it two errors cancelling each other ?

 Y.Chaouche





 --- On *Thu, 10/14/10, Thadeus Burgess thade...@thadeusb.com* wrote:


 From: Thadeus Burgess thade...@thadeusb.com
 Subject: Re: [sqlalchemy] Checking the availablity of a booked Item
 To: sqlalchemy@googlegroups.com
 Date: Thursday, October 14, 2010, 8:42 AM

 http://www.sqlalchemy.org/docs/reference/orm/query.html#sqlalchemy.orm.join

 isouter = True

 --
 Thadeus




 On Thu, Oct 14, 2010 at 10:26 AM, chaouche yacine 
 yacinechaou...@yahoo.com 
 http://mc/compose?to=yacinechaou...@yahoo.comwrote:

 Here's the SQL I got :

 SELECT face.id AS face_id
 FROM face
 LEFT OUTER JOIN face_bookings__booking_faces AS
 face_bookings__booking_faces_1
 ON face.id = face_bookings__booking_faces_1.face_id
 LEFT OUTER JOIN booking
 ON booking.id = face_bookings__booking_faces_1.booking_id
 JOIN time_period ON booking.time_period_id = time_period.id
 WHERE
   time_period.start_date  %(start_date_1)s
   OR
   time_period.end_date  %(end_date_1)s


 With the following code :


 class Booking(BaseModel):
 
 
 using_options(tablename=booking)

 reprattr=  time_period
 faces   = ManyToMany(Face)
 # A client has one and only one booking per time period
 time_period = ManyToOne(TimePeriod)

 @classmethod
 def get_available_faces(self,time_period):
 
 Return faces that are not booked during the given time_period.
 
 from timeperiod import TimePeriod
 from face   import Face

 start_date_cond = TimePeriod.start_date  time_period.end_date
 end_date_cond   = TimePeriod.end_date   
 time_period.start_date
 unbooked= or_(start_date_cond,end_date_cond)

 # query =
 Face.query.filter(Face.bookings.any(Booking.time_period.has(unbooked)))
 # return query.all()

 query = Face.query.filter(unbooked)
 #return query.all()
 query = query.outerjoin(Face.bookings)
 #return query.all()
 query = query.join(Booking.time_period)
 return query.all()


 And still not the expected results (it should return faces with no bookings
 at all but it doesen't).

 Thanks for any help.

 Y.Chaouche

 --- On *Wed, 10/13/10, chaouche yacine 
 yacinechaou...@yahoo.comhttp://mc/compose?to=yacinechaou...@yahoo.com
 * wrote:


 From: chaouche yacine 
 yacinechaou...@yahoo.comhttp://mc/compose?to=yacinechaou...@yahoo.com
 

 Subject: Re: [sqlalchemy] Checking the availablity of a booked Item
 To: 
 sqlalchemy@googlegroups.comhttp://mc/compose?to=sqlalch...@googlegroups.com
 Date: Wednesday, October 13, 2010, 5:25 AM


 Thank you Thadeus, I believe
 Face.query.filter(filter_cond).outerjoin(join_clause).all() does a full
 outerjoin, or is there another way to do it ?

 Y.Chaouche





 --- On *Wed, 10/13/10, Thadeus Burgess 
 thade...@thadeusb.comhttp://mc/compose?to=thade...@thadeusb.com
 * wrote:


 From: Thadeus Burgess 
 thade...@thadeusb.comhttp://mc/compose?to=thade...@thadeusb.com
 
 Subject: Re: [sqlalchemy] Checking the availablity of a booked Item
 To: 
 sqlalchemy@googlegroups.comhttp://mc/compose?to=sqlalch...@googlegroups.com
 Date: Wednesday, October 13, 2010, 12:04 AM

 For outer joins you need a where clause on the joined tables.


 http://www.codinghorror.com/blog/2007/10/a-visual-explanation-of-sql-joins.html

 Using a full outer join should return

Re: [sqlalchemy] Checking the availablity of a booked Item

2010-10-14 Thread Thadeus Burgess
http://www.sqlalchemy.org/docs/reference/orm/query.html#sqlalchemy.orm.join

isouter = True

--
Thadeus




On Thu, Oct 14, 2010 at 10:26 AM, chaouche yacine
yacinechaou...@yahoo.comwrote:

 Here's the SQL I got :

 SELECT face.id AS face_id
 FROM face
 LEFT OUTER JOIN face_bookings__booking_faces AS
 face_bookings__booking_faces_1
 ON face.id = face_bookings__booking_faces_1.face_id
 LEFT OUTER JOIN booking
 ON booking.id = face_bookings__booking_faces_1.booking_id
 JOIN time_period ON booking.time_period_id = time_period.id
 WHERE
   time_period.start_date  %(start_date_1)s
   OR
   time_period.end_date  %(end_date_1)s


 With the following code :


 class Booking(BaseModel):
 
 
 using_options(tablename=booking)

 reprattr=  time_period
 faces   = ManyToMany(Face)
 # A client has one and only one booking per time period
 time_period = ManyToOne(TimePeriod)

 @classmethod
 def get_available_faces(self,time_period):
 
 Return faces that are not booked during the given time_period.
 
 from timeperiod import TimePeriod
 from face   import Face

 start_date_cond = TimePeriod.start_date  time_period.end_date
 end_date_cond   = TimePeriod.end_date   
 time_period.start_date
 unbooked= or_(start_date_cond,end_date_cond)

 # query =
 Face.query.filter(Face.bookings.any(Booking.time_period.has(unbooked)))
 # return query.all()

 query = Face.query.filter(unbooked)
 #return query.all()
 query = query.outerjoin(Face.bookings)
 #return query.all()
 query = query.join(Booking.time_period)
 return query.all()


 And still not the expected results (it should return faces with no bookings
 at all but it doesen't).

 Thanks for any help.

 Y.Chaouche

 --- On *Wed, 10/13/10, chaouche yacine yacinechaou...@yahoo.com* wrote:


 From: chaouche yacine yacinechaou...@yahoo.com

 Subject: Re: [sqlalchemy] Checking the availablity of a booked Item
 To: sqlalchemy@googlegroups.com
 Date: Wednesday, October 13, 2010, 5:25 AM


 Thank you Thadeus, I believe
 Face.query.filter(filter_cond).outerjoin(join_clause).all() does a full
 outerjoin, or is there another way to do it ?

 Y.Chaouche





 --- On *Wed, 10/13/10, Thadeus Burgess thade...@thadeusb.com* wrote:


 From: Thadeus Burgess thade...@thadeusb.com
 Subject: Re: [sqlalchemy] Checking the availablity of a booked Item
 To: sqlalchemy@googlegroups.com
 Date: Wednesday, October 13, 2010, 12:04 AM

 For outer joins you need a where clause on the joined tables.


 http://www.codinghorror.com/blog/2007/10/a-visual-explanation-of-sql-joins.html

 Using a full outer join should return the expected results.
 --
 Thadeus




 On Tue, Oct 12, 2010 at 1:41 PM, chaouche yacine yacinechaou...@yahoo.com
  wrote:

 Hello,

 Here's my simple model (For simplification, consider Face as a Billboard) :

 +-+  +---+   +--+
 |Face |..   |Campaign   |   ...|TimePeriod|
 +-+  .   +---+   .   +--+
 |code |  .   |time_period|   |start_time|
 +-+  .   +---+   +--+
 |faces  |   |end_time  |
 +---+   +--+

 One way to read this model is : A campaign can book multiple faces during a
 certain period of time.

 What I want to do is get all the available Faces for a given period of
 time, to see what faces can I book for a new campaign that longs for that
 particular period of time. I would typically have a
 Face.get_available(time_period) class method that does the job. This method
 would look for all the faces that don't have an ongoing booking. My question
 is : how to write such a method ?

 Here's how I figured it out (couldn't get it to work) :

 class Face(Entity):
using_options(tablename=faces)
@classmethod
def get_available(self,time_period):

Return faces that are not booked (not in any campaign) during the
 given time_period.

# start_date_cond = TimePeriod.start_date  time_period.end_date
# end_date_cond   = TimePeriod.end_date   
 time_period.start_date
# available_periods   =
 Campaign.time_period.has(or_(start_date_cond,end_date_cond))
# unavailable_periods = not(available_periods)

# I am pretty sure that the time conditions are good.
# Here's a good way to convince yourself (read from bottom to top) :

# L1
  0---
# L2 --|
# L3
 0[]--

# L3 represents the desired period (passed as argument) going from
 [ to ]
# place the start date of the booked face anywhere on L2
# place the end date of the booked face anywhere on L1

Re: [sqlalchemy] Checking the availablity of a booked Item

2010-10-13 Thread Thadeus Burgess
For outer joins you need a where clause on the joined tables.

http://www.codinghorror.com/blog/2007/10/a-visual-explanation-of-sql-joins.html

Using a full outer join should return the expected results.
--
Thadeus




On Tue, Oct 12, 2010 at 1:41 PM, chaouche yacine
yacinechaou...@yahoo.comwrote:

 Hello,

 Here's my simple model (For simplification, consider Face as a Billboard) :

 +-+  +---+   +--+
 |Face |..   |Campaign   |   ...|TimePeriod|
 +-+  .   +---+   .   +--+
 |code |  .   |time_period|   |start_time|
 +-+  .   +---+   +--+
 |faces  |   |end_time  |
 +---+   +--+

 One way to read this model is : A campaign can book multiple faces during a
 certain period of time.

 What I want to do is get all the available Faces for a given period of
 time, to see what faces can I book for a new campaign that longs for that
 particular period of time. I would typically have a
 Face.get_available(time_period) class method that does the job. This method
 would look for all the faces that don't have an ongoing booking. My question
 is : how to write such a method ?

 Here's how I figured it out (couldn't get it to work) :

 class Face(Entity):
using_options(tablename=faces)
@classmethod
def get_available(self,time_period):

Return faces that are not booked (not in any campaign) during the
 given time_period.

# start_date_cond = TimePeriod.start_date  time_period.end_date
# end_date_cond   = TimePeriod.end_date   
 time_period.start_date
# available_periods   =
 Campaign.time_period.has(or_(start_date_cond,end_date_cond))
# unavailable_periods = not(available_periods)

# I am pretty sure that the time conditions are good.
# Here's a good way to convince yourself (read from bottom to top) :

# L1
  0---
# L2 --|
# L3
 0[]--

# L3 represents the desired period (passed as argument) going from
 [ to ]
# place the start date of the booked face anywhere on L2
# place the end date of the booked face anywhere on L1
# of course, end date must be after start date...
# Anyway you do it, your face isn't available for the period of time
 in L3.

start_date_cond = TimePeriod.start_date = time_period.end_date
end_date_cond   = TimePeriod.end_date   =
 time_period.start_date
unavailable_periods =
 Campaign.time_period.has(and_(start_date_cond,end_date_cond))
# I am not sure about what follows...
filter_cond = not_(unavailable_periods)
join_clause = Campaign.faces

return Face.query.filter(filter_cond).outerjoin(join_clause).all()


 This code returns only faces that have already been booked before or have a
 future booking, and are free for the moment. But faces with no bookings at
 all are not returned. This may be due to an incorrect outerjoin ? (I also
 tried a simple join with no success)

 Here's the generated sql for one query :

 2010-10-12 19:34:22,837 INFO sqlalchemy.engine.base.Engine.0x...f4ec
 SELECT faces.id AS faces_id
 FROM campaigns LEFT OUTER JOIN campaigns_faces__faces AS
 campaigns_faces__faces_1 ON campaigns.id =
 campaigns_faces__faces_1.campaigns_id
 LEFT OUTER JOIN faces ON faces.id = campaigns_faces__faces_1.faces_id
 WHERE NOT (EXISTS (SELECT 1
  FROM time_periods
  WHERE campaigns.time_period_id = time_periods.id
  AND time_periods.start_date = %(start_date_1)s
  AND time_periods.end_date = %(end_date_1)s))

 2010-10-12 19:34:22,837 INFO sqlalchemy.engine.base.Engine.0x...f4ec
 {'start_date_1': datetime.date(2010, 10, 30), 'end_date_1':
 datetime.date(2010, 10, 20)}
 [Face id=1 at 0x932218c  ]


 Any help would be very appreciated.

 Y.Chaouche

 PS : and please, don't give me that lame it's elixir excuse. The question
 is about how to construct the proper query for the desired operation in a
 sqlalchemy way. Elixir is only another Declarative approach + mapping,
 that's it.




 --
 You received this message because you are subscribed to the Google Groups
 sqlalchemy group.
 To post to this group, send email to sqlalch...@googlegroups.com.
 To unsubscribe from this group, send email to
 sqlalchemy+unsubscr...@googlegroups.comsqlalchemy%2bunsubscr...@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 sqlalch...@googlegroups.com.
To unsubscribe from this group, send email to 
sqlalchemy+unsubscr...@googlegroups.com.

[sqlalchemy] Column data representation

2010-09-03 Thread Thadeus Burgess
Is there a way to specify the way a column represents itself when
converted to string?

For example, I would like to automatically get all columns from
table.c, and iterate over a record printing its fields. However when I
come across a FK field, I would like to instead of printing out the
integer value, query the database and print out the value from the
referenced record.

The key problem is I am getting my columns from table.c, so I don't
know about the class mapper relationships that are defined.

--
Thadeus

-- 
You received this message because you are subscribed to the Google Groups 
sqlalchemy group.
To post to this group, send email to sqlalch...@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] Easy way to referesh .__dict__

2010-09-03 Thread Thadeus Burgess
If I have a record object.

me = Person.query.get(id)

and I access me.__dict__ everything looks good.

However when I execute a db.session.commit()

the me.__dict__ disappears and only contains _sa_state_instance

The second I access an attribute of the me instance, __dict__ comes back.

What is the best way to always make sure the __dict__ instance is
always populated with the object data without knowing any of the
column names ahead of time ?

--
Thadeus

-- 
You received this message because you are subscribed to the Google Groups 
sqlalchemy group.
To post to this group, send email to sqlalch...@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.