[sqlalchemy] Unicode URL error

2007-03-30 Thread Andrew Stromnov

ascii-encoded string:

 url = 'mysql://login:[EMAIL PROTECTED]/adverts?charset=cp1251'
 engine = sqlalchemy.create_engine(url, convert_unicode=True, pool_recycle=4)
 metadata = sqlalchemy.BoundMetaData(engine)
 ad_table = sqlalchemy.Table('adverts', metadata, autoload=True)


unicode string:

 url = u'mysql://login:[EMAIL PROTECTED]/adverts?charset=cp1251'
 engine = sqlalchemy.create_engine(url, convert_unicode=True, pool_recycle=4)
 metadata = sqlalchemy.BoundMetaData(engine)
 ad_table = sqlalchemy.Table('adverts', metadata, autoload=True)
Traceback (most recent call last):
  File interactive input, line 1, in ?
  File c:\python24\develop\sqlalchemy\lib\sqlalchemy\schema.py, line
167, in __call__
metadata.get_engine().reflecttable(table)
  File c:\python24\develop\sqlalchemy\lib\sqlalchemy\engine\base.py,
line 754, in reflecttable
conn = self.contextual_connect()
  File c:\python24\develop\sqlalchemy\lib\sqlalchemy\engine\base.py,
line 748, in contextual_connect
return Connection(self, close_with_result=close_with_result,
**kwargs)
  File c:\python24\develop\sqlalchemy\lib\sqlalchemy\engine\base.py,
line 374, in __init__
self.__connection = connection or engine.raw_connection()
  File c:\python24\develop\sqlalchemy\lib\sqlalchemy\engine\base.py,
line 769, in raw_connection
return self.connection_provider.get_connection()
  File c:\python24\develop\sqlalchemy\lib\sqlalchemy\engine
\default.py, line 19, in get_connection
return self._pool.connect()
  File c:\python24\develop\sqlalchemy\lib\sqlalchemy\pool.py, line
147, in connect
return _ConnectionFairy(self).checkout()
  File c:\python24\develop\sqlalchemy\lib\sqlalchemy\pool.py, line
232, in __init__
self._connection_record = pool.get()
  File c:\python24\develop\sqlalchemy\lib\sqlalchemy\pool.py, line
160, in get
return self.do_get()
  File c:\python24\develop\sqlalchemy\lib\sqlalchemy\pool.py, line
429, in do_get
con = self.create_connection()
  File c:\python24\develop\sqlalchemy\lib\sqlalchemy\pool.py, line
143, in create_connection
return _ConnectionRecord(self)
  File c:\python24\develop\sqlalchemy\lib\sqlalchemy\pool.py, line
180, in __init__
self.connection = self.__connect()
  File c:\python24\develop\sqlalchemy\lib\sqlalchemy\pool.py, line
210, in __connect
connection = self.__pool._creator()
  File c:\python24\develop\sqlalchemy\lib\sqlalchemy\engine
\strategies.py, line 71, in connect
raise exceptions.DBAPIError(Connection failed, e)
DBAPIError: (Connection failed) (TypeError) Connect() keywords must be
strings



--~--~-~--~~~---~--~~
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 [EMAIL PROTECTED]
For more options, visit this group at 
http://groups.google.com/group/sqlalchemy?hl=en
-~--~~~~--~~--~--~---



[sqlalchemy] order_by computed on wrong table with many-to-many

2007-03-30 Thread Alexandre CONRAD

Hello,

I have a problem with order_by on a many-to-many relationship (using 
assign_mapper):


--
attachment_table = Table('attachments', meta,
 Column('id', Integer, primary_key=True),
 Column('file', Binary, nullable=False),
 Column('name', Unicode(40), nullable=False),
 Column('type', Unicode(30)),
 Column('date', DateTime, default=datetime.now),
 Column('size', Integer, nullable=False),
 Column('description', Unicode(40)),
)

attachments_has_sites = Table('attachments_has_sites', meta,
 Column('id_attachment', None, ForeignKey('attachments.id'), 
primary_key=True),
 Column('id_site', None, ForeignKey('sites.id'), primary_key=True),
)

class Attachment(object):
 pass

attachment_mapper = assign_mapper(ctx, Attachment, attachment_table,
 properties={
 'file':deferred(attachment_table.c.file),
 'sites':relation(Site, backref=attachments, 
secondary=attachments_has_sites, cascade=save-update),
 },
 order_by=attachment_table.c.name,
)
--



So I have a Site object where I can ask for it's attachments:

   s = model.Site.get(1)
   attachment_list = s.attachments

But it fires the following QUERY:

SELECT attachments.name AS attachments_name, attachments.description AS 
attachments_description, attachments.date AS attachments_date, 
attachments.type AS attachments_type, attachments.id AS attachments_id, 
attachments.size AS attachments_size
FROM attachments, attachments_has_sites
WHERE %s = attachments_has_sites.id_site AND attachments.id = 
attachments_has_sites.id_attachment ORDER BY 
attachments_has_sites.id_attachment

the ORDER BY is computed against the weak table (secondary) 
attachments_has_sites.

Regards,
-- 
Alexandre CONRAD


--~--~-~--~~~---~--~~
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 [EMAIL PROTECTED]
For more options, visit this group at 
http://groups.google.com/group/sqlalchemy?hl=en
-~--~~~~--~~--~--~---



[sqlalchemy] Re: alias not used with relationship to arbitary select

2007-03-30 Thread hdmail

Thanks Michael. it works as you've described.

Huy
 put the order_by in your status relation.

 On Mar 26, 2007, at 12:23 PM, HD Mail wrote:

   
 
 I think the issue is you cant put a task_status ordering in your
 Task mapper since that table is not part of its mapping.

 http://www.sqlalchemy.org/trac/wiki/
 FAQ#ImusinglazyFalsetocreateaJOINOUTERJOINandSQLAlchemyisnotconstruct 
 ing
 thequerywhenItrytoaddaWHEREORDERBYLIMITetc.whichreliesupontheOUTERJOI 
 N


   
 I'm a bit confused. So with a mapping as follows.

 db.mapper(TaskStatus, db.sys_task_status)
 db.mapper(Task, db.task,
properties = {
'status': relation(TaskStatus, lazy=False),
}
 )

 Is the only way for me to order by a column in sys_task_status is with
 an explicit join like in this example ?

 query = db.query(model.Task).select_from(
db.task.join(db.sys_task_status)
 ).order_by(db.sys_task_status.c.seq_no)

 which results in the following SQL:

 SELECT sys_task_status_cf27.*, task.*
 FROM task JOIN sys_task_status ON sys_task_status.status_code =
 task.status_code
 LEFT OUTER JOIN sys_task_status AS sys_task_status_cf27 ON
 sys_task_status_cf27.status_code = task.status_code
 ORDER BY sys_task_status.seq_no, sys_task_status_cf27.status_code

 I'm trying to get to the following query. It takes half the time of  
 the
 first query.

 SELECT sys_task_status_cf27.*, task.*
 FROM task LEFT OUTER JOIN sys_task_status AS sys_task_status_cf27 ON
 sys_task_status_cf27.status_code = task.status_code
 ORDER BY sys_task_status_cf27.seq_no, sys_task_status_cf27.status_code


 





--~--~-~--~~~---~--~~
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 [EMAIL PROTECTED]
For more options, visit this group at 
http://groups.google.com/group/sqlalchemy?hl=en
-~--~~~~--~~--~--~---



[sqlalchemy] Subselect is preventing additional where conditions--help

2007-03-30 Thread Paul Kippes

I'm trying to create a subselect that has a where condition using an
identically named column as the outer select.  I'm not able to figure
out how to tell SQLAlchemy that I need two parameters--one for each
query.  Here is what my SQL would look like if I wrote it by hand:

SELECT signals.*
FROM module_outputs
WHERE module_id = :module_id
AND signal_id NOT IN (
SELECT signal_id
FROM module_inputs
WHERE module_id = :module_id)

This is how the joining tables are defined:

self.module_inputs = sqla.Table('module_inputs', metadata,
sqla.Column('module_id',
sqla.Integer,
sqla.ForeignKey('modules.module_id'),
nullable = False),
sqla.Column('signal_id',
sqla.Integer,
sqla.ForeignKey('signals.signal_id'),
nullable = False),
sqla.PrimaryKeyConstraint('module_id', 'signal_id')
)

self.module_outputs = sqla.Table('module_outputs', metadata,
sqla.Column('module_id',
sqla.Integer,
sqla.ForeignKey('modules.module_id'),
nullable = False),
sqla.Column('signal_id',
sqla.Integer,
sqla.ForeignKey('signals.signal_id'),
nullable = False),
sqla.PrimaryKeyConstraint('module_id', 'signal_id')
)

Below is some code that attempts to pass the necessary parameters.
I'd like to place both parameters in the execute() line, but it seems
I may need alias one or both parameters.  So far, I'm stumped on what
to and what I'm doing wrong.

db = model.db.tables

# Construct the subselect
not_in_join = sql.join(db.signals, db.module_outputs)
not_in_sel = sql.select([db.signals.c.signal_id],
db.module_outputs.c.module_id == m.module_id,
from_obj=[not_in_join])

# Construct the primary query to return signal_ids
sel = sql.select([db.signals.c.signal_id],
 sql.not_(db.signals.c.signal_id.in_(not_in_sel)),
 from_obj=[sql.join(db.signals, db.module_inputs)])

#  print sel
# SELECT signals.signal_id
# FROM signals
# JOIN module_inputs ON signals.signal_id =
#   module_inputs.signal_id
# WHERE signals.signal_id NOT IN (
# SELECT signals.signal_id AS signal_id
# FROM signals
# JOIN module_outputs ON signals.signal_id =
#module_outputs.signal_id
# WHERE module_outputs.module_id = ?)

# The above generated query would be fine if execute() would work.

id_res = sel.execute(module_id = m.module_id)

# This does not add an extra
#   AND module_inputs.module_id = ?

sel = sql.select([db.signals.c.signal_id],
 sql.and_(sql.not_(db.signals.c.signal_id.in_(not_in_sel)),
  db.module_inputs.c.module_id == m.module_id),
 from_obj=[sql.join(db.signals, db.module_inputs)])

# The above doesn't work either

--~--~-~--~~~---~--~~
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 [EMAIL PROTECTED]
For more options, visit this group at 
http://groups.google.com/group/sqlalchemy?hl=en
-~--~~~~--~~--~--~---



[sqlalchemy] print SQL only

2007-03-30 Thread ml

Hi!

I want meta.create_all() to generate and print the SQL only and don't
query the DB. Is there any way?

Thanks for advices.

David

--~--~-~--~~~---~--~~
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 [EMAIL PROTECTED]
For more options, visit this group at 
http://groups.google.com/group/sqlalchemy?hl=en
-~--~~~~--~~--~--~---



[sqlalchemy] Re: order_by computed on wrong table with many-to-many

2007-03-30 Thread Michael Bayer

use 'sites':relation(Site, backref=backref('attachments',
order_by=attachment_table.c.name)) for now.

On Mar 30, 5:50 am, Alexandre CONRAD [EMAIL PROTECTED] wrote:
 Hello,

 I have a problem with order_by on a many-to-many relationship (using
 assign_mapper):

 --
 attachment_table = Table('attachments', meta,
  Column('id', Integer, primary_key=True),
  Column('file', Binary, nullable=False),
  Column('name', Unicode(40), nullable=False),
  Column('type', Unicode(30)),
  Column('date', DateTime, default=datetime.now),
  Column('size', Integer, nullable=False),
  Column('description', Unicode(40)),
 )

 attachments_has_sites = Table('attachments_has_sites', meta,
  Column('id_attachment', None, ForeignKey('attachments.id'),
 primary_key=True),
  Column('id_site', None, ForeignKey('sites.id'), primary_key=True),
 )

 class Attachment(object):
  pass

 attachment_mapper = assign_mapper(ctx, Attachment, attachment_table,
  properties={
  'file':deferred(attachment_table.c.file),
  'sites':relation(Site, backref=attachments,
 secondary=attachments_has_sites, cascade=save-update),
  },
  order_by=attachment_table.c.name,
 )
 --

 So I have a Site object where I can ask for it's attachments:

s = model.Site.get(1)
attachment_list = s.attachments

 But it fires the following QUERY:

 SELECT attachments.name AS attachments_name, attachments.description AS
 attachments_description, attachments.date AS attachments_date,
 attachments.type AS attachments_type, attachments.id AS attachments_id,
 attachments.size AS attachments_size
 FROM attachments, attachments_has_sites
 WHERE %s = attachments_has_sites.id_site AND attachments.id =
 attachments_has_sites.id_attachment ORDER BY
 attachments_has_sites.id_attachment

 the ORDER BY is computed against the weak table (secondary)
 attachments_has_sites.

 Regards,
 --
 Alexandre CONRAD


--~--~-~--~~~---~--~~
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 [EMAIL PROTECTED]
For more options, visit this group at 
http://groups.google.com/group/sqlalchemy?hl=en
-~--~~~~--~~--~--~---



[sqlalchemy] Re: Subselect is preventing additional where conditions--help

2007-03-30 Thread Michael Bayer

On Mar 30, 10:54 am, Paul Kippes [EMAIL PROTECTED]
wrote:
 I'm trying to create a subselect that has a where condition using an
 identically named column as the outer select.  I'm not able to figure
 out how to tell SQLAlchemy that I need two parameters--one for each
 query.  Here is what my SQL would look like if I wrote it by hand:

 SELECT signals.*
 FROM module_outputs
 WHERE module_id = :module_id
 AND signal_id NOT IN (
 SELECT signal_id
 FROM module_inputs
 WHERE module_id = :module_id)

thats an invalid query - the signals table is not in the FROM
condition.  also your code below seems to indicate you want the outer
query to join on module_inputs but up here you put module_outputs
in your  main FROM clause.   construct your SQL query as plain text,
run it and make sure it returns what you want,  then send it back here
if youre still stumped.


--~--~-~--~~~---~--~~
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 [EMAIL PROTECTED]
For more options, visit this group at 
http://groups.google.com/group/sqlalchemy?hl=en
-~--~~~~--~~--~--~---



[sqlalchemy] Re: Unicode URL error

2007-03-30 Thread Michael Bayer

fix in changeset 2475

On Mar 30, 5:19 am, Andrew Stromnov [EMAIL PROTECTED] wrote:
 ascii-encoded string:

  url = 'mysql://login:[EMAIL PROTECTED]/adverts?charset=cp1251'
  engine = sqlalchemy.create_engine(url, convert_unicode=True, 
  pool_recycle=4)
  metadata = sqlalchemy.BoundMetaData(engine)
  ad_table = sqlalchemy.Table('adverts', metadata, autoload=True)

 unicode string:

  url = u'mysql://login:[EMAIL PROTECTED]/adverts?charset=cp1251'
  engine = sqlalchemy.create_engine(url, convert_unicode=True, 
  pool_recycle=4)
  metadata = sqlalchemy.BoundMetaData(engine)
  ad_table = sqlalchemy.Table('adverts', metadata, autoload=True)

 Traceback (most recent call last):
   File interactive input, line 1, in ?
   File c:\python24\develop\sqlalchemy\lib\sqlalchemy\schema.py, line
 167, in __call__
 metadata.get_engine().reflecttable(table)
   File c:\python24\develop\sqlalchemy\lib\sqlalchemy\engine\base.py,
 line 754, in reflecttable
 conn = self.contextual_connect()
   File c:\python24\develop\sqlalchemy\lib\sqlalchemy\engine\base.py,
 line 748, in contextual_connect
 return Connection(self, close_with_result=close_with_result,
 **kwargs)
   File c:\python24\develop\sqlalchemy\lib\sqlalchemy\engine\base.py,
 line 374, in __init__
 self.__connection = connection or engine.raw_connection()
   File c:\python24\develop\sqlalchemy\lib\sqlalchemy\engine\base.py,
 line 769, in raw_connection
 return self.connection_provider.get_connection()
   File c:\python24\develop\sqlalchemy\lib\sqlalchemy\engine
 \default.py, line 19, in get_connection
 return self._pool.connect()
   File c:\python24\develop\sqlalchemy\lib\sqlalchemy\pool.py, line
 147, in connect
 return _ConnectionFairy(self).checkout()
   File c:\python24\develop\sqlalchemy\lib\sqlalchemy\pool.py, line
 232, in __init__
 self._connection_record = pool.get()
   File c:\python24\develop\sqlalchemy\lib\sqlalchemy\pool.py, line
 160, in get
 return self.do_get()
   File c:\python24\develop\sqlalchemy\lib\sqlalchemy\pool.py, line
 429, in do_get
 con = self.create_connection()
   File c:\python24\develop\sqlalchemy\lib\sqlalchemy\pool.py, line
 143, in create_connection
 return _ConnectionRecord(self)
   File c:\python24\develop\sqlalchemy\lib\sqlalchemy\pool.py, line
 180, in __init__
 self.connection = self.__connect()
   File c:\python24\develop\sqlalchemy\lib\sqlalchemy\pool.py, line
 210, in __connect
 connection = self.__pool._creator()
   File c:\python24\develop\sqlalchemy\lib\sqlalchemy\engine
 \strategies.py, line 71, in connect
 raise exceptions.DBAPIError(Connection failed, e)
 DBAPIError: (Connection failed) (TypeError) Connect() keywords must be
 strings




--~--~-~--~~~---~--~~
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 [EMAIL PROTECTED]
For more options, visit this group at 
http://groups.google.com/group/sqlalchemy?hl=en
-~--~~~~--~~--~--~---



[sqlalchemy] Re: [PATCH] Filtered one_to_many relationships (Experimental)

2007-03-30 Thread Gaetan de Menten
On 3/26/07, Michael Bayer [EMAIL PROTECTED] wrote:

  (and whether that be a .query() or Query() or SelectResults not big
  difference imo.)
 

 i vote Query().

I tried to implement it but I couldn't do it the way I wanted to. The
problem is: how do I construct a clause from a clause with bind
parameters + a dictionary containing the values for said bind
parameters? I've only seen bind parameters resolved at execution time.
Is it possible to resolve them earlier? In the attached patch, I used
a workaround which is to store the bind parameters in the query
itself, and then use them whenever the query is executed.

Two remarks:

* I've implemented Query.from_attr, instead of adding new keywords to
the Query constructor, because I think:

Query.from_attr(someuser, 'addresses')

looks better, is shorter and is more readable than:

Query('Address', instance=someuser, attr_name='addresses')

* It only works for lazy attributes. I don't think there is any reason
we couldn't make it work for eager attributes, but by looking at the
eagerloader code, I couldn't figure how to do it.

-- 
Gaƫtan de Menten
http://openhex.org

--~--~-~--~~~---~--~~
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 [EMAIL PROTECTED]
For more options, visit this group at 
http://groups.google.com/group/sqlalchemy?hl=en
-~--~~~~--~~--~--~---

Index: orm/query.py
===
--- orm/query.py(revision 2444)
+++ orm/query.py(working copy)
@@ -42,12 +42,32 @@
 self._distinct = kwargs.pop('distinct', False)
 self._offset = kwargs.pop('offset', None)
 self._limit = kwargs.pop('limit', None)
-self._criterion = None
+self._criterion = kwargs.pop('criterion', None)
+self._params = kwargs.pop('params', {})
 self._joinpoint = self.mapper
 self._from_obj = [self.table]
 
 for opt in util.flatten_iterator(self.with_options):
 opt.process_query(self)
+
+def from_attr(cls, instance, attr_name):
+prop = instance.mapper.props[attr_name]
+loader = prop.strategy
+#TODO: make it work for eager loader too.
+# code taken from strategies.py
+params = {}
+allparams = True
+for col, bind in loader.lazybinds.iteritems():
+params[bind.key] = loader.parent.get_attr_by_column(instance, col)
+if params[bind.key] is None:
+allparams = False
+break
+
+if not allparams:
+return None
+
+return Query(prop.mapper, criterion=loader.lazywhere, params=params)
+from_attr = classmethod(from_attr)
 
 def _clone(self):
 q = Query.__new__(Query)
@@ -71,6 +91,7 @@
 q._from_obj = list(self._from_obj)
 q._joinpoint = self._joinpoint
 q._criterion = self._criterion
+q._params = self._params
 return q
 
 def _get_session(self):
@@ -690,8 +711,10 @@
 method, which takes the executed statement's ResultProxy
 directly.
 
-
-result = self.session.execute(self.mapper, clauseelement, 
params=params)
+final_params = self._params.copy()
+if params is not None:
+final_params.update(params)
+result = self.session.execute(self.mapper, clauseelement, 
params=final_params)
 try:
 return self.instances(result, **kwargs)
 finally:


[sqlalchemy] Re: print SQL only

2007-03-30 Thread Michael Bayer

this approach should work for now, but will need some small  
modifications in the next release of SA (i.e. it should be easier):

from sqlalchemy import *

class FakeDBAPI(object):
 def __init__(self):
 self.paramstyle = 'named'

e = create_engine('oracle://', module=FakeDBAPI())   # or  
postgres://, mysql://, etc.

def proxy(statement, params):
 print statement

gen = e.dialect.schemagenerator(e, proxy, None)

m = MetaData()
t = Table('table1', m, Column('id', Integer, primary_key=True))
t2 = Table('table2', m, Column('id', Integer, primary_key=True),  
Column('t1id', Integer, ForeignKey('table1.id')))

m.accept_visitor(gen)


On Mar 30, 2007, at 4:34 AM, ml wrote:


 Hi!

 I want meta.create_all() to generate and print the SQL only and don't
 query the DB. Is there any way?

 Thanks for advices.

 David

 


--~--~-~--~~~---~--~~
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 [EMAIL PROTECTED]
For more options, visit this group at 
http://groups.google.com/group/sqlalchemy?hl=en
-~--~~~~--~~--~--~---



[sqlalchemy] Re: Inserting a node in basic_tree.py

2007-03-30 Thread Michael Bayer

the treenodes table has no explicit sorting field, so by default it
will sort by either the row ID of the table or the primary key field.
the only operation that can be issued to the database when you add an
item to the list is INSERT, so this will always assemble new nodes as
the last element in the collection regardless of where they appear in
your python collection.

to have custom ordering of your list other than insert order, a new
column will need to be added to treenodes with which to sort by, and
your Node class will have to populate this field with an ordering
corresponding to its desired order in its parent collection.

this population can be performed pretty easily with this example by
just altering NodeList to additionally populate child items with a
sort field.

you then specify this column on the children relationship as the
order_by field.


On Mar 30, 11:51 am, Andrea Gavana [EMAIL PROTECTED] wrote:
 Hi All,

 I am working on a modified version of basic_tree.py.  The base
 demo simply appends nodes to a parent node. What I would like to do,
 is to be able to prepend nodes on a parent node, i.e. appending
 nodes before other nodes in the tree structure. For example, if a
 parent node has this structure:

 Parent
   |--- Child 1
   |--- Child 2

 I would like to insert a new item like that:

 Parent
   |--- NewItem
   |--- Child 1
   |--- Child 2

 So, I have modified the basic demo NodeList class like this:

 class NodeList(OrderedDict):
 subclasses OrderedDict to allow usage as a list-based property.

 def append(self, node):
 self[node.name] = node

 def insert(self, indx, node):

 self[node.name] = node
 self.move(node.name, indx)

 And then, to prepend an item, I simply do:

 node = TreeNode('rootnode')
 node.append('Child 1')
 node.append('Child 2')
 # More actions here...
 node.insert('NewItem')

 But this newitem gets inserted at the end (like it does when you use
 append() ). This happens if I call session.clear(), if I don't do that
 the item looks correctly inserted as a first item. I attach a small
 demo that shows my problem.
 Does anyone know what I am doing wrong or what I have misunderstood?

 Thank you for your suggestions.

 Andrea.

 Imagination Is The Only Weapon In The War Against 
 Reality.http://xoomer.virgilio.it/infinity77/

 [basic_tree.py]a basic Adjacency List model tree.

 from sqlalchemy import *
 from sqlalchemy.util import OrderedDict

 class NodeList(OrderedDict):
 subclasses OrderedDict to allow usage as a list-based property.
 def append(self, node):
 self[node.name] = node
 def insert(self, indx, node):
 self[node.name] = node
 self.move(node.name, indx)
 def __iter__(self):
 return iter(self.values())

 class TreeNode(object):
 a rich Tree class which includes path-based operations
 def __init__(self, name):
 self.children = NodeList()
 self.name = name
 self.parent = None
 self.id = None
 self.parent_id = None
 def append(self, node):
 if isinstance(node, str):
 node = TreeNode(node)
 node.parent = self
 self.children.append(node)
 def insert(self, node):
 if isinstance(node, str):
 node = TreeNode(node)
 node.parent = self
 self.children.insert(0, node)
 def __repr__(self):
 return self._getstring(0, False)
 def __str__(self):
 return self._getstring(0, False)
 def _getstring(self, level, expand = False):
 s = ('  ' * level) + %s (%s,%s, %d) % (self.name, 
 self.id,self.parent_id,id(self)) + '\n'
 if expand:
 s += ''.join([n._getstring(level+1, True) for n in 
 self.children.values()])
 return s
 def print_nodes(self):
 return self._getstring(0, True)

 def RunBasicTree(clearSession=False):

 metadata = BoundMetaData('sqlite:///', echo=False)

 trees = Table('treenodes', metadata,
 Column('node_id', Integer, 
 Sequence('treenode_id_seq',optional=False), primary_key=True),
 Column('parent_node_id', Integer, ForeignKey('treenodes.node_id'), 
 nullable=True),
 Column('node_name', String(50), nullable=False),
 )

 mapper(TreeNode, trees, properties=dict(
 id=trees.c.node_id,
 name=trees.c.node_name,
 parent_id=trees.c.parent_node_id,
 children=relation(TreeNode, cascade=all, backref=backref(parent, 
 remote_side=[trees.c.node_id]), collection_class=NodeList),
 ))

 trees.create()

 node2 = TreeNode('node2')
 node2.append('subnode1')
 nodea = TreeNode('rootnode')
 nodea.append('node1')
 nodea.append(node2)
 nodea.append('node3')
 nodea.children['node2'].append('subnode2')

 session = create_session()
 session.save(nodea)
 session.flush()

 nodea.append('node4')
 nodea.children['node4'].append('subnode3')
 

[sqlalchemy] Re: Is there an easy way to convert a ResultProxy object (returned back from an execute) to a dict

2007-03-30 Thread Rick Morrison
Fetched resultproxy objects have dictionary semantics, and most things that
expect dictionaries will work fine with them.
Make sure you've fetched all your results (via .fetchall()) before handing
them off for processing.

Rick

On 3/30/07, vinjvinj [EMAIL PROTECTED] wrote:


 I'm putting the rows returned back from the db in a cache and that is
 not supported by the ResultProxy object. I get the error:

 InterfaceError: not open

 Is there an easy way to convert the ResultProxy object back to a dict
 which I can then put in a cache or get some form of ResultProxy object
 which works in a non-connected way?

 Thanks,

 Vineet


 


--~--~-~--~~~---~--~~
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 [EMAIL PROTECTED]
For more options, visit this group at 
http://groups.google.com/group/sqlalchemy?hl=en
-~--~~~~--~~--~--~---