1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280
|
import logging
from contextlib import contextmanager
from Orange.util import Registry
log = logging.getLogger(__name__)
class BackendError(Exception):
pass
class Backend(metaclass=Registry):
"""Base class for SqlTable backends. Implementations should define
all of the methods defined below.
Parameters
----------
connection_params: dict
connection params
"""
display_name = ""
def __init__(self, connection_params):
self.connection_params = connection_params
@classmethod
def available_backends(cls):
"""Return a list of all available backends"""
return cls.registry.values()
# "meta" methods
def list_tables_query(self, schema=None):
"""Return a list of tuples (schema, table_name)
Parameters
----------
schema : Optional[str]
If set, only tables from schema should be listed
Returns
-------
A list of tuples
"""
raise NotImplementedError
def list_tables(self, schema=None):
"""Return a list of tables in database
Parameters
----------
schema : Optional[str]
If set, only tables from given schema will be listed
Returns
-------
A list of TableDesc objects, describing the tables in the database
"""
query = self.list_tables_query(schema)
with self.execute_sql_query(query) as cur:
tables = []
for schema, name in cur.fetchall():
sql = "{}.{}".format(
self.quote_identifier(schema),
self.quote_identifier(name)) if schema else self.quote_identifier(name)
tables.append(TableDesc(name, schema, sql))
return tables
def n_tables_query(self, schema=None) -> str:
"""Return a query to count tables in database.
Parameters
----------
schema : Optional[str]
If set, only tables from schema should be listed
Returns
-------
Query string.
"""
raise NotImplementedError
def n_tables(self, schema=None) -> int:
"""Return number of tables in database.
Parameters
----------
schema : Optional[str]
If set, only tables from given schema will be listed.
Returns
-------
Number of tables in the database.
"""
query = self.n_tables_query(schema)
with self.execute_sql_query(query) as cur:
res = cur.fetchone()
return res[0]
def get_fields(self, table_name):
"""Return a list of field names and metadata in the given table
Parameters
----------
table_name: str
Returns
-------
a list of tuples (field_name, *field_metadata)
both will be passed to create_variable
"""
query = self.create_sql_query(table_name, ["*"], limit=0)
with self.execute_sql_query(query) as cur:
return cur.description
def distinct_values_query(self, field_name: str, table_name: str) -> str:
"""
Generate query for getting distinct values of field
Parameters
----------
field_name : name of the field
table_name : name of the table or query to search
Returns
-------
The query for getting distinct values of field
"""
raise NotImplementedError
def get_distinct_values(self, field_name, table_name):
"""Return a list of distinct values of field
Parameters
----------
field_name : name of the field
table_name : name of the table or query to search
Returns
-------
List[str] of values
"""
query = self.distinct_values_query(field_name, table_name)
with self.execute_sql_query(query) as cur:
values = cur.fetchall()
if len(values) > 20:
return ()
else:
return tuple(str(x[0]) for x in values)
def create_variable(self, field_name, field_metadata,
type_hints, inspect_table=None):
"""Create variable based on field information
Parameters
----------
field_name : str
name do the field
field_metadata : tuple
data to guess field type from
type_hints : Domain
domain with variable templates
inspect_table : Option[str]
name of the table to expect the field values or None
if no inspection is to be performed
Returns
-------
Variable representing the field
"""
raise NotImplementedError
def count_approx(self, query):
"""Return estimated number of rows returned by query.
Parameters
----------
query : str
Returns
-------
Approximate number of rows
"""
raise NotImplementedError
# query related methods
def create_sql_query(
self, table_name, fields, filters=(),
group_by=None, order_by=None, offset=None, limit=None,
use_time_sample=None):
"""Construct an sql query using the provided elements.
Parameters
----------
table_name : str
fields : List[str]
filters : List[str]
group_by: List[str]
order_by: List[str]
offset: int
limit: int
use_time_sample: int
Returns
-------
string containing sql query
"""
raise NotImplementedError
@contextmanager
def execute_sql_query(self, query, params=None):
"""Context manager for execution of sql queries
Usage:
```
with backend.execute_sql_query("SELECT * FROM foo") as cur:
cur.fetch_all()
```
Parameters
----------
query : string
query to be executed
params: tuple
parameters to be passed to the query
Returns
-------
yields a cursor that can be used to access the data
"""
raise NotImplementedError
def quote_identifier(self, name):
"""Quote identifier name so it can be safely used in queries
Parameters
----------
name: str
name of the parameter
Returns
-------
quoted parameter that can be used in sql queries
"""
raise NotImplementedError
def unquote_identifier(self, quoted_name):
"""Remove quotes from identifier name
Used when sql table name is used in where parameter to
query special tables
Parameters
----------
quoted_name : str
Returns
-------
unquoted name
"""
raise NotImplementedError
class TableDesc:
def __init__(self, name, schema, sql):
self.name = name
self.schema = schema
self.sql = sql
def __str__(self):
return self.name
class ToSql:
def __init__(self, sql):
self.sql = sql
def __call__(self):
return self.sql
|