[dataimport] new 'lazydbtable' generator function to feed data from a database table stable
authorSylvain Thénault <sylvain.thenault@logilab.fr>
Fri, 01 Apr 2011 01:06:41 +0200
branchstable
changeset 7160 923013173031
parent 7159 3bcccd3ab6b6
child 7162 62561ea082d2
child 7163 d6d905d0344f
[dataimport] new 'lazydbtable' generator function to feed data from a database table
dataimport.py
--- a/dataimport.py	Fri Apr 01 01:06:37 2011 +0200
+++ b/dataimport.py	Fri Apr 01 01:06:41 2011 +0200
@@ -146,6 +146,19 @@
     for row in reader:
         yield dict(zip(header, row))
 
+def lazydbtable(cu, table, headers):
+    """return an iterator on rows of a sql table. On each row, fetch columns
+    defined in headers and return values as a dictionary.
+
+    >>> data = lazydbtable(cu, 'experimentation', ('id', 'nickname', 'gps'))
+    """
+    cu.execute('SELECT %s FROM %s' % (','.join(headers), table,))
+    while True:
+        row = cu.fetchone()
+        if row is None:
+            break
+        yield dict(zip(headers, row))
+
 def mk_entity(row, map):
     """Return a dict made from sanitized mapped values.