Package gavo :: Package grammars :: Module odbcgrammar
[frames] | no frames]

Source Code for Module gavo.grammars.odbcgrammar

 1  """ 
 2  A Grammar feeding from an odbc connection. 
 3  """ 
 4   
 5  #c Copyright 2008-2019, the GAVO project 
 6  #c 
 7  #c This program is free software, covered by the GNU GPL.  See the 
 8  #c COPYING file in the source distribution. 
 9   
10   
11  import pyodbc 
12   
13  from gavo import base 
14  from gavo.grammars.common import Grammar, RowIterator 
15   
16   
17 -class ODBCIterator(RowIterator):
18 - def _iterRows(self):
19 with open(self.sourceToken) as f: 20 conn = pyodbc.connect(f.read().strip()) 21 cursor = conn.cursor() 22 cursor.execute(self.grammar.query) 23 keys = [d[0] for d in cursor.description] 24 for row in cursor: 25 yield dict(zip(keys, row))
26 27
28 -class ODBCGrammar(Grammar):
29 """A grammar that feeds from a remote database. 30 31 This works as a sort of poor man's foreign data wrapper: you pull 32 data from a remote database now and then, mogrifying it into whatever 33 format you want locally. 34 35 This expects files containing pyodbc connection strings as sources, 36 so you'll normally just have one source. Having the credentials 37 externally helps keeping RDs using this safe for public version control. 38 39 An example for an ODBC connection string:: 40 41 DRIVER={SQL Server};SERVER=localhost;DATABASE=testdb;UID=me;PWD=pass 42 43 See also http://www.connectionstrings.com/ 44 45 This will only work if pyodbc (debian: python-pyodbc) is installed. 46 Additionally, you will have to install the odbc driver corresponding 47 to your source database (e.g., odbc-postgresql). 48 """ 49 name_ = "odbcGrammar" 50 51 _query = base.UnicodeAttribute("query", 52 description="The query to run on the remote server. The keys of" 53 " the grammar will be the names of the result columns.", 54 copyable=True) 55 56 rowIterator = ODBCIterator
57