Package recsql :: Module sqlutil
[hide private]
[frames] | no frames]

Source Code for Module recsql.sqlutil

 1  # $Id: sqlutil.py 2346 2008-10-06 19:36:21Z oliver $ 
 2  # Copyright (C) 2009 Oliver Beckstein <orbeckst@gmail.com> 
 3  # Released under the GNU Public License, version 3 or higher (your choice) 
 4   
 5  """ 
 6  :mod:`sqlutils` -- Helper functions 
 7  =================================== 
 8   
 9  Helper functions that are used throughout the :mod:`recsql` package. 
10   
11  How to use the sql converters and adapters: 
12     Declare types as 'NumpyArray':: 
13   
14        cur.execute("CREATE TABLE test(a NumpyArray)") 
15        cur.execute("INSERT INTO test(a) values (?)", (my_array,)) 
16   
17     or as column types:: 
18   
19        cur.execute('SELECT a as "a [NumpyArray]" from test') 
20   
21  Module content 
22  -------------- 
23  .. See the autogenerated content in the online docs or the source code. 
24  """ 
25   
26  import cPickle 
27   
28  # storing numpy arrays in the db as pickles 
29 -def adapt_numpyarray(a):
30 """adapter: store numpy arrays in the db as ascii pickles""" 31 return cPickle.dumps(a,protocol=0) # must use text protocol for use with sqlite
32
33 -def convert_numpyarray(s):
34 """converter: retrieve numpy arrays from the db as ascii pickles""" 35 return cPickle.loads(s)
36
37 -def adapt_object(a):
38 """adapter: store python objects in the db as ascii pickles""" 39 return cPickle.dumps(a,protocol=0) # must use text protocol for use with sqlite
40
41 -def convert_object(s):
42 """convertor: retrieve python objects from the db as ascii pickles""" 43 return cPickle.loads(s)
44 45 46 # Fake* not needed anymore since SQLarray takes an iterable + columns descriptors 47 # Use FakeRecArray to load the db from an iterable 48
49 -class FakeDtype(object):
50 - def __init__(self,**kwargs):
51 self.__dict__.update(kwargs)
52
53 -class FakeRecArray(object):
54 """Pseudo recarray that is used to feed SQLarray: 55 56 Must only implement: 57 58 recarray.dtype.names sequence of column names 59 iteration yield records 60 """
61 - def __init__(self, iterable, columns):
62 self.dtype = FakeDtype(names=columns) 63 self.iterable = iterable
64
65 - def __iter__(self):
66 for rec in self.iterable: 67 yield rec
68