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
|
"""
Base multicorn module.
This module contains all the python code needed by the multicorn C extension
to postgresql.
You should install it in the python path available to the user running
postgresql (usually, the system wide python installation).
"""
import sys
__version__ = '__VERSION__'
ANY = object()
ALL = object()
UNBOUND = object()
class Qual(object):
"""A Qual describes a postgresql qual.
Attributes
field_name -- The name of the column as defined in the postgresql
table.
operator_name -- The name of the operator.
Example: =, <=, ~~ (for a like clause)
"""
def __init__(self, field_name, operator, value):
"""Constructs a qual object.
Instantiated from the C extension with the field name, operator and
value extracted from the postgresql where clause.
"""
self.field_name = field_name
self.operator = operator
self.value = value
@property
def is_list_operator(self):
"""Returns True if this qual represents an array expr"""
return isinstance(self.operator, tuple)
@property
def list_any_or_all(self):
"""Returns ANY if and only if:
- this is a list operator
- the operator applies as an 'ANY' clause (eg, = ANY(1,2,3))
Returns ALL if and only if:
- this is a list operator
- the operator applies as an 'ALL' clause (eg, > ALL(1, 2, 3))
Else, returns None
"""
if self.is_list_operator:
return ANY if self.operator[1] else ALL
return None
def __repr__(self):
if self.is_list_operator:
value = '%s(%s)' % (
'ANY' if self.list_any_or_all == ANY
else 'ALL',
self.value)
operator = self.operator[0]
else:
value = self.value
operator = self.operator
return ("%s %s %s" % (self.field_name, operator, value))
def __eq__(self, other):
if isinstance(other, Qual):
return (self.field_name == other.field_name and
self.operator == other.operator and
self.value == other.value)
return False
def __hash__(self):
return hash((self.field_name, self.operator, self.value))
class ForeignDataWrapper(object):
"""Base class for all foreign data wrapper instances."""
_startup_cost = 20
def __init__(self, fdw_options, fdw_columns):
"""The foreign data wrapper is initialized on the first query.
Arguments
fdw_options -- The foreign data wrapper options. It is a dictionary
mapping keys from the sql "CREATE FOREIGN TABLE"
statement options. It is left to the implementor
to decide what should be put in those options, and what
to do with them.
fdw_columns -- The foreign datawrapper columns. It is a dictionary
mapping the column names to their types.
"""
pass
def get_rel_size(self, quals, columns):
"""Helps the planner by returning costs.
Returns a tuple of the form (nb_row, avg width)
"""
return (100000000, len(columns) * 100)
def get_path_keys(self):
"""Helps the planner by supplying a list of list of access keys."""
return []
def execute(self, quals, columns):
"""Execute a query in the foreign data wrapper.
Arguments
quals -- A list of :class:`Qual` instances, containing the basic
where clauses in the query.
Implementors are not expected to manage these quals,
since postgresql will check them anyway.
For an exemple of quals management, see the concrete
subclass :class:`multicorn.ldapfdw.LdapFdw`
columns -- A list of columns that postgresql is going to need.
You should return AT LEAST those columns when returning a
dict. If returning a sequence, every column from the table
should be in the sequence.
"""
pass
@property
def rowid_column(self):
"""Returns a column name which will act as a rowid column, for delete/update
operations. This can be either an existing column name, or a made-up one.
This column name should be subsequently present in every returned resultset.
"""
raise NotImplementedError("This FDW does not support the writable API")
def insert(self, values):
raise NotImplementedError("This FDW does not support the writable API")
def update(self, oldvalues, newvalues):
raise NotImplementedError("This FDW does not support the writable API")
def delete(self, oldvalues):
raise NotImplementedError("This FDW does not support the writable API")
def pre_commit(self):
pass
def rollback(self):
pass
def commit(self):
pass
def end_scan(self):
pass
def end_modify(self):
pass
def begin(self, serializable):
pass
def sub_begin(self, level):
pass
def sub_rollback(self, level):
pass
def sub_commit(self, level):
pass
class TransactionAwareForeignDataWrapper(ForeignDataWrapper):
def __init__(self, fdw_options, fdw_columns):
super(TransactionAwareForeignDataWrapper, self).__init__(fdw_options, fdw_columns)
self._init_transaction_state()
def _init_transaction_state(self):
self.current_transaction_state = []
def insert(self, values):
self.current_transaction_state.append(('insert', values))
def update(self, oldvalues, newvalues):
self.current_transaction_state.append(('update', (oldvalues, newvalues)))
def delete(self, oldvalues):
self.current_transaction_state.append(('delete', oldvalues))
def rollback(self):
self._init_transaction_state()
"""Code from python2.7 importlib.import_module."""
"""Backport of importlib.import_module from 3.x."""
# While not critical (and in no way guaranteed!), it would be nice to keep this
# code compatible with Python 2.3.
def _resolve_name(name, package, level):
"""Return the absolute name of the module to be imported."""
if not hasattr(package, 'rindex'):
raise ValueError("'package' not set to a string")
dot = len(package)
for x in range(level, 1, -1):
try:
dot = package.rindex('.', 0, dot)
except ValueError:
raise ValueError("attempted relative import beyond top-level "
"package")
return "%s.%s" % (package[:dot], name)
def import_module(name, package=None):
"""Import a module.
The 'package' argument is required when performing a relative import. It
specifies the package to use as the anchor point from which to resolve the
relative import to an absolute import.
"""
if name.startswith('.'):
if not package:
raise TypeError("relative imports require the 'package' argument")
level = 0
for character in name:
if character != '.':
break
level += 1
name = _resolve_name(name[level:], package, level)
__import__(name)
return sys.modules[name]
def get_class(module_path):
"""Internal function called from c code to import a foreign data wrapper.
Returns the class designated by module_path.
Arguments
module_path -- A fully qualified path to a foreign data wrapper.
Ex: multicorn.csvfdw.CsvFdw.
"""
module_path.split(".")
wrapper_class = module_path.split(".")[-1]
module_name = ".".join(module_path.split(".")[:-1])
module = import_module(module_name)
return getattr(module, wrapper_class)
class ColumnDefinition(object):
def __init__(self, column_name, type_oid, typmod, type_name,
base_type_name,
options):
self.column_name = column_name
self.type_oid = type_oid
self.typmod = typmod
self.type_name = type_name
self.base_type_name = base_type_name
self.options = options or {}
def __repr__(self):
return "%s(%s, %i, %s%s)" % (
self.__class__.__name__, self.column_name,
self.type_oid, self.type_name,
" options %s" % self.options if self.options else "")
|