Debian Codegraph @

gavo/grammars/odbcgrammar.py

raw
1 """
2 A Grammar feeding from an odbc connection.
3 """
4
5 #c Copyright 2008-2025, the GAVO project <[email protected]>
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 from psycopg2.extensions import adapt
12
13 from gavo import base
14 from gavo import rscdef
15 from gavo import utils
16 from gavo.grammars.common import Grammar, RowIterator
17
18 pyodbc = utils.DeferredImport("pyodbc", "import pyodbc")
19
20
21 class QueryGenerator(rscdef.ProcApp):
22 """A generator of ODBC queries.
23
24 This is is mainly useful when doing ODBC queries to incrementally
25 havest some external resource.
26
27 The current ODBC iterator will be available as ``self``.
28
29 The procedures also see a function escapeSQL(val) that returns val
30 as a SQL literal (actually, it's psycopg2's adapt at the moment).
31
32 This is intended to be used somewhat like this with a monotonously
33 increasing column insertion_time::
34
35 <makeQuery>
36 <code>
37 # find to until when we have data locally
38 try:
39 with base.getTableConn() as conn:
40 localMax = next(conn.query(
41 "SELECT MAX(insertion_time) FROM \\schema.main"))[0]
42
43 fragment = " WHERE insertion_time>{}".format(
44 sqlEscape(localMax))
45 except base.DBError as msg:
46 base.ui.notifyWarning(f"{msg} while harvesting: full re-harvest")
47 fragment = ""
48
49 return f"SELECT * FROM remote_table{fragment}"
50 </code>
51 </makeQuery>
52 """
53 name_ = "makeQuery"
54 requiredType = "makeQuery"
55 formalArgs = "self"
56
57 additionalNamesForProcs = {
58 "escapeSQL": adapt,
59 }
60
61
62 class ODBCIterator(RowIterator):
63 def _iterRows(self):
64 with open(self.sourceToken) as f:
65 accessToken = f.read().strip()
66 conn = pyodbc.connect(accessToken)
67
68 if self.grammar.query:
69 remoteQuery = self.grammar.query
70 else:
71 remoteQuery = self.grammar.makeQuery.compile()(self)
72
73 cursor = conn.cursor()
74 cursor.execute(remoteQuery)
75 keys = [d[0] for d in cursor.description]
76 for row in cursor:
77 yield dict(list(zip(keys, row)))
78
79
80 class ODBCGrammar(Grammar):
81 """A grammar that feeds from a remote database.
82
83 This works as a sort of poor man's foreign data wrapper: you pull
84 data from a remote database now and then, mogrifying it into whatever
85 format you want locally.
86
87 This expects files containing pyodbc connection strings as sources,
88 so you'll normally just have one source. Having the credentials
89 externally helps keeping RDs using this safe for public version control.
90
91 An example for an ODBC connection string::
92
93 DRIVER={SQL Server};SERVER=localhost;DATABASE=testdb;UID=me;PWD=pass
94
95 See also http://www.connectionstrings.com/
96
97 This will only work if pyodbc (debian: python3-pyodbc) is installed.
98 Additionally, you will have to install the odbc driver corresponding
99 to your source database (e.g., odbc-postgresql).
100 """
101 name_ = "odbcGrammar"
102
103 _query = base.UnicodeAttribute("query",
104 description="The query to run on the remote server. The keys of"
105 " the grammar will be the names of the result columns.",
106 default=base.NotGiven,
107 copyable=True)
108 _makeQuery = base.StructAttribute("makeQuery",
109 childFactory=QueryGenerator,
110 default=base.NotGiven,
111 description="Code returning the query to execute on the remote"
112 " system.")
113
114 rowIterator = ODBCIterator
115
116 def validate(self):
117 super().validate()
118 if self.query and self.makeQuery:
119 raise base.StructureError("Cannot give both query and makeQuery"
120 " in an odbcGrammar.")
121 if not (self.query or self.makeQuery):
122 raise base.StructureError("Need to give at least one of query"
123 " and makeQuery in an odbcGrammar.")
124
125 def completeElement(self, ctx):
126 if ctx.restricted and self.makeQuery:
127 raise base.RestrictedElement("makeQuery")
128
129 super().completeElement(ctx)