| 1 |
""" |
| 2 |
Conversions between type systems. |
| 3 |
|
| 4 |
The DC software has to deal with a quite a few type systems: |
| 5 |
|
| 6 |
- Python |
| 7 |
- SQL |
| 8 |
- Postgres pg_type |
| 9 |
- VOTable |
| 10 |
- XSD |
| 11 |
- Twisted formal |
| 12 |
- numpy |
| 13 |
|
| 14 |
Based on the (stinking) framework of utils.typeconversions, this |
| 15 |
module contains converters between them as necessary. The |
| 16 |
linuga franca of our type systems is SQL+extensions as laid |
| 17 |
down in utils.typeconversions. |
| 18 |
""" |
| 19 |
|
| 20 |
#c Copyright 2008-2025, the GAVO project <[email protected]> |
| 21 |
#c |
| 22 |
#c This program is free software, covered by the GNU GPL. See the |
| 23 |
#c COPYING file in the source distribution. |
| 24 |
|
| 25 |
|
| 26 |
import re |
| 27 |
|
| 28 |
import numpy |
| 29 |
|
| 30 |
from gavo import utils |
| 31 |
from gavo.base import literals |
| 32 |
from gavo.utils.typeconversions import (FromSQLConverter, |
| 33 |
sqltypeToVOTable, voTableToSQLType, ConversionError) |
| 34 |
|
| 35 |
|
| 36 |
def scalarify(sqlType): |
| 37 |
"""returns the scalar of sqlType. |
| 38 |
|
| 39 |
This will basically cut away any array markers; the main use for this |
| 40 |
right now is when turning min/max in column/values to typed python |
| 41 |
values, as values for arrays is defined on the cells. |
| 42 |
|
| 43 |
Except of course for polygons in VOTables. We shouldn't see that |
| 44 |
problem here because our sqlType is spoly, but let's see what the |
| 45 |
VOTable designers will yet come up with. |
| 46 |
|
| 47 |
We don't touch any y(x) types here. There's no valid point to use them in |
| 48 |
DaCHS, and I believe essentially all of them are python scalars to |
| 49 |
begin with. |
| 50 |
""" |
| 51 |
subscriptStart = sqlType.find('[') |
| 52 |
if subscriptStart>0: |
| 53 |
return sqlType[:subscriptStart] |
| 54 |
return sqlType |
| 55 |
|
| 56 |
|
| 57 |
class FromVOTableConverter(object): |
| 58 |
typeSystem = "db" |
| 59 |
|
| 60 |
simpleMap = { |
| 61 |
("short", '1'): "smallint", |
| 62 |
("int", '1'): "integer", |
| 63 |
("long", '1'): "bigint", |
| 64 |
("float", '1'): "real", |
| 65 |
("boolean", '1'): "boolean", |
| 66 |
("double", '1'): "double precision", |
| 67 |
("char", "*"): "text", |
| 68 |
("char", '1'): "char", |
| 69 |
("unsignedByte", '1'): "smallint", |
| 70 |
("raw", '1'): "raw", |
| 71 |
} |
| 72 |
|
| 73 |
xtypeMap = { |
| 74 |
"adql:POINT": "spoint", |
| 75 |
"adql:REGION": "spoly", |
| 76 |
"adql:TIMESTAMP": "timestamp", |
| 77 |
"timestamp": "timestamp", |
| 78 |
"point": "spoint", |
| 79 |
"circle": "scirle", |
| 80 |
"polygon": "spoly", |
| 81 |
} |
| 82 |
|
| 83 |
def convert(self, type, arraysize, xtype=None): |
| 84 |
if self.xtypeMap.get(xtype): |
| 85 |
return self.xtypeMap[xtype] |
| 86 |
if arraysize=="1" or arraysize=="" or arraysize is None: |
| 87 |
arraysize = "1" |
| 88 |
if (type, arraysize) in self.simpleMap: |
| 89 |
return self.simpleMap[type, arraysize] |
| 90 |
else: |
| 91 |
return self.mapComplex(type, arraysize) |
| 92 |
|
| 93 |
def mapComplex(self, type, arraysize): |
| 94 |
if arraysize=="*": |
| 95 |
arraysize = "" |
| 96 |
if type=="char": |
| 97 |
return "text" |
| 98 |
if type=="unicodeChar": |
| 99 |
return "unicode" |
| 100 |
if type=="unsignedByte" and arraysize!="1": |
| 101 |
return "bytea" |
| 102 |
if (type, '1') in self.simpleMap: |
| 103 |
return "%s[%s]"%(self.simpleMap[type, '1'], arraysize) |
| 104 |
raise ConversionError("No SQL type for %s, %s"%(type, arraysize)) |
| 105 |
|
| 106 |
|
| 107 |
class ToXSDConverter(FromSQLConverter): |
| 108 |
|
| 109 |
typeSystem = "XSD" |
| 110 |
simpleMap = { |
| 111 |
"smallint": "short", |
| 112 |
"integer": "int", |
| 113 |
"bigint": "long", |
| 114 |
"real": "float", |
| 115 |
"boolean": "boolean", |
| 116 |
"double precision": "double", |
| 117 |
"text": "string", |
| 118 |
"unicode": "string", |
| 119 |
"char": "string", |
| 120 |
"date": "date", |
| 121 |
"timestamp": "dateTime", |
| 122 |
"time": "time", |
| 123 |
"raw": "string", |
| 124 |
"vexpr-mjd": "string", |
| 125 |
"vexpr-date": "string", |
| 126 |
"vexpr-float": "string", |
| 127 |
"vexpr-string": "string", |
| 128 |
} |
| 129 |
|
| 130 |
def mapComplex(self, type, length): |
| 131 |
if type in self._charTypes: |
| 132 |
return "string" |
| 133 |
|
| 134 |
|
| 135 |
class ToNumpyConverter(FromSQLConverter): |
| 136 |
|
| 137 |
typeSystem = "numpy" |
| 138 |
simpleMap = { |
| 139 |
"smallint": numpy.int16, |
| 140 |
"integer": numpy.int32, |
| 141 |
"bigint": numpy.int64, |
| 142 |
"real": numpy.float32, |
| 143 |
"boolean": numpy.bool_, |
| 144 |
"double precision": numpy.float64, |
| 145 |
"text": numpy.str_, |
| 146 |
"unicode": numpy.str_, |
| 147 |
"char": numpy.str_, |
| 148 |
"date": numpy.float32, |
| 149 |
"timestamp": numpy.float64, |
| 150 |
"time": numpy.float32, |
| 151 |
} |
| 152 |
|
| 153 |
def mapComplex(self, type, length): |
| 154 |
if type in self._charTypes: |
| 155 |
return numpy.str |
| 156 |
|
| 157 |
|
| 158 |
class ToPythonBase(FromSQLConverter): |
| 159 |
"""The base for converters turning dealing with turning "simple" literals |
| 160 |
into python values. |
| 161 |
|
| 162 |
These return the identity for most "complex" types that do not have |
| 163 |
plain literals. |
| 164 |
|
| 165 |
What is returned here is a name of a function turning a single literal |
| 166 |
into an object of the desired type; all those reside within base.literals. |
| 167 |
|
| 168 |
All such functions should be transparent to None (null value) and to |
| 169 |
objects that already are of the desired type. |
| 170 |
""" |
| 171 |
simpleMap = { |
| 172 |
"smallint": "parseInt", |
| 173 |
"integer": "parseInt", |
| 174 |
"bigint": "parseInt", |
| 175 |
"real": "parseFloat", |
| 176 |
"boolean": "parseBooleanLiteral", |
| 177 |
"double precision": "parseFloat", |
| 178 |
"text": "parseUnicode", |
| 179 |
"char": "parseUnicode", |
| 180 |
"unicode": "parseUnicode", |
| 181 |
"date": "parseDefaultDate", |
| 182 |
"timestamp": "parseDefaultDatetime", |
| 183 |
"time": "parseDefaultTime", |
| 184 |
"spoint": "parseSPoint", |
| 185 |
"scircle": "parseSimpleSTCS", |
| 186 |
"spoly": "parseSimpleSTCS", |
| 187 |
"sbox": "identity", # hmha, there's no STC-S for this kind of box... |
| 188 |
"smoc": "identity", # use pgsphere.SMoc.fromASCII |
| 189 |
"bytea": "parseBytes", |
| 190 |
# the following two have provisions for web.BinaryItem |
| 191 |
"raw": "originalOrIdentity", |
| 192 |
"file": "originalOrIdentity", |
| 193 |
"box": "identity", |
| 194 |
"vexpr-mjd": "identity", |
| 195 |
"vexpr-string": "identity", |
| 196 |
"vexpr-float": "identity", |
| 197 |
"vexpr-date": "identity", |
| 198 |
"pql-string": "identity", |
| 199 |
"pql-float": "identity", |
| 200 |
"pql-int": "identity", |
| 201 |
"pql-date": "identity", |
| 202 |
"pql-upload": "identity", |
| 203 |
"int4range": "parseInterval", |
| 204 |
"json": "parseJSON", |
| 205 |
"jsonb": "parseJSON", |
| 206 |
} |
| 207 |
|
| 208 |
def mapComplex(self, type, length): |
| 209 |
if type in self._charTypes and not "x" in length: |
| 210 |
# a plain sequence of chars is close enough to a string |
| 211 |
return "parseUnicode" |
| 212 |
else: |
| 213 |
return "identity" # Anything sufficiently complex is python anyway :-) |
| 214 |
|
| 215 |
|
| 216 |
class ToPythonCodeConverter(ToPythonBase): |
| 217 |
"""returns code templates to turn literals in variables to python objects. |
| 218 |
|
| 219 |
This is for the rowmakers' src="xx" specification, where no fancy literal |
| 220 |
processing needs to be done. |
| 221 |
|
| 222 |
The values of the map are simple string interpolation templates, with a |
| 223 |
single %s for the name of the variable to be converted. |
| 224 |
|
| 225 |
The code assumes whatever executes those literals has done the equvialent |
| 226 |
of gavo.base.literals import * or use gavo.base.literals.defaultParsers() |
| 227 |
""" |
| 228 |
typeSystem = "pythonsrc" |
| 229 |
|
| 230 |
def convert(self, sqlType): |
| 231 |
funcName = ToPythonBase.convert(self, sqlType) |
| 232 |
if funcName=="identity": # probably pointless performance hack |
| 233 |
return "%s" |
| 234 |
return funcName+"(%s)" |
| 235 |
|
| 236 |
|
| 237 |
class ToPythonConverter(ToPythonBase): |
| 238 |
"""returns constructors making python values from strings. |
| 239 |
|
| 240 |
This is only for non-fancy applications with controlled input. For |
| 241 |
more general circumstances, you'll want to use the parsing infrastructure. |
| 242 |
|
| 243 |
In particular, this will return the identity for most non-trivial stuff. |
| 244 |
Maybe that's wrong, but it will only change as sane literals are defined. |
| 245 |
""" |
| 246 |
typeSystem = "python" |
| 247 |
|
| 248 |
def convert(self, sqlType): |
| 249 |
funcName = ToPythonBase.convert(self, sqlType) |
| 250 |
return getattr(literals, funcName) |
| 251 |
|
| 252 |
|
| 253 |
class ToLiteralConverter(object): |
| 254 |
"""returns a function taking some python value and returning stuff that |
| 255 |
can be parsed using ToPythonCodeConverter. |
| 256 |
""" |
| 257 |
typeSystem = "literal" |
| 258 |
simpleMap = { |
| 259 |
"smallint": str, |
| 260 |
"integer": str, |
| 261 |
"bigint": str, |
| 262 |
"real": str, |
| 263 |
"boolean": str, |
| 264 |
"double precision": str, |
| 265 |
"text": str, |
| 266 |
"char": str, |
| 267 |
"unicode": str, |
| 268 |
"date": lambda v: v.isoformat(), |
| 269 |
"timestamp": lambda v: utils.formatISODT(v), |
| 270 |
"time": lambda v: v.isoformat(), |
| 271 |
"spoint": lambda v: "%f,%f"%(v.x/utils.DEG, v.y/utils.DEG), |
| 272 |
# XXX TODO Fix those |
| 273 |
# "scircle": str, |
| 274 |
# "spoly": str, |
| 275 |
# "sbox": str, |
| 276 |
# "smoc": str, |
| 277 |
} |
| 278 |
|
| 279 |
def convert(self, type): |
| 280 |
if type in self.simpleMap: |
| 281 |
return self.simpleMap[type] |
| 282 |
return utils.identity |
| 283 |
|
| 284 |
|
| 285 |
class ToPgTypeValidatorConverter(FromSQLConverter): |
| 286 |
"""returns a callable that takes a type code from postgres' pg_type |
| 287 |
that will raise a TypeError if the to types are deemed incompatible. |
| 288 |
""" |
| 289 |
typeSystem = "Postgres pg_types validators" |
| 290 |
|
| 291 |
def checkInt(pgcode): |
| 292 |
if pgcode not in frozenset(['int2', 'int4', 'int8']): |
| 293 |
raise TypeError("%s is not compatible with an integer column"%pgcode) |
| 294 |
|
| 295 |
def checkFloat(pgcode): |
| 296 |
if pgcode not in frozenset(['float4', 'float8', 'numeric']): |
| 297 |
raise TypeError("%s is not compatible with a float column"%pgcode) |
| 298 |
|
| 299 |
def makeChecker(expectedCode): |
| 300 |
def checker(pgcode): |
| 301 |
if expectedCode!=pgcode: |
| 302 |
raise TypeError("Incompatible type in DB: Expected %s, found %s"%( |
| 303 |
expectedCode, pgcode)) |
| 304 |
return checker |
| 305 |
|
| 306 |
def dontCheck(pgcode): |
| 307 |
# should we give a warning that we didn't check a column? |
| 308 |
pass |
| 309 |
|
| 310 |
def makeAlarmer(typeName): |
| 311 |
def beAlarmed(pgcode): |
| 312 |
raise TypeError("Column with a non-db type %s mapped to db type %s"%( |
| 313 |
typeName, pgcode)) |
| 314 |
return beAlarmed |
| 315 |
|
| 316 |
simpleMap = { |
| 317 |
"smallint": checkInt, |
| 318 |
"integer": checkInt, |
| 319 |
"bigint": checkInt, |
| 320 |
"real": checkFloat, |
| 321 |
"boolean": makeChecker("bool"), |
| 322 |
"double precision": checkFloat, |
| 323 |
"text": makeChecker("text"), |
| 324 |
"char": makeChecker("bpchar"), |
| 325 |
"date": makeChecker("date"), |
| 326 |
"timestamp": makeChecker("timestamp"), |
| 327 |
"time": makeChecker("time"), |
| 328 |
"int4range": makeChecker("int4range"), |
| 329 |
"box": dontCheck, # box is on the way out -- don't bother |
| 330 |
"vexpr-mjd": makeAlarmer("vexpr-mjd"), |
| 331 |
"vexpr-string": makeAlarmer("vexpr-string"), |
| 332 |
"vexpr-date": makeAlarmer("vexpr-date"), |
| 333 |
"vexpr-float": makeAlarmer("vexpr-float"), |
| 334 |
"file": makeAlarmer("file"), |
| 335 |
"pql-float": makeAlarmer("pql-float"), |
| 336 |
"pql-string": makeAlarmer("pql-string"), |
| 337 |
"pql-date": makeAlarmer("pql-date"), |
| 338 |
"pql-int": makeAlarmer("pql-int"), |
| 339 |
"pql-upload": makeAlarmer("pql-upload"), |
| 340 |
"raw": makeAlarmer("raw"), |
| 341 |
"bytea": makeChecker("bytea"), |
| 342 |
"spoint": makeChecker("spoint"), |
| 343 |
"scircle": makeChecker("scircle"), |
| 344 |
"sbox": makeChecker("sbox"), |
| 345 |
"spoly": makeChecker("spoly"), |
| 346 |
"smap": makeChecker("smap"), |
| 347 |
"smoc": makeChecker("smoc"), |
| 348 |
"unicode": makeChecker("text"), |
| 349 |
"json": makeChecker("json"), |
| 350 |
"jsonb": makeChecker("jsonb"), |
| 351 |
} |
| 352 |
|
| 353 |
def mapComplex(self, type, length): |
| 354 |
if (length is None or length==1) and type in self.simpleMap: |
| 355 |
return self.simpleMap[type] |
| 356 |
|
| 357 |
# it seems postgres always has a _ in front of arrays, but char(*) |
| 358 |
# doesn't have it. We pretend we don't care for now. |
| 359 |
def check(pgcode): |
| 360 |
if pgcode.startswith("_"): |
| 361 |
pgcode = pgcode[1:] |
| 362 |
self.simpleMap[type](pgcode) |
| 363 |
|
| 364 |
return check |
| 365 |
|
| 366 |
|
| 367 |
def sqltypeToPG(type): |
| 368 |
"""returns a postgres type for one of our internal SQL types. |
| 369 |
|
| 370 |
This is really only because of VOTable's terrible string features. |
| 371 |
For one, we map UNICODE to TEXT as long as VOTable char can't be UTF-8. |
| 372 |
And then, VOTable needs fixed-length strings in string arrays, whereas |
| 373 |
postgres doesn't accept char(something) as a stand-in for text in such |
| 374 |
arrays. We hence map any char() in the first place to text. |
| 375 |
|
| 376 |
Actual char arrays of >1d can still be done with square brackets. |
| 377 |
Yeah... it would be nice if we could do this better. |
| 378 |
|
| 379 |
>>> sqltypeToPG("INT[23, 42]") |
| 380 |
'INT[23, 42]' |
| 381 |
>>> sqltypeToPG("uniCode[23]") |
| 382 |
'TEXT[23]' |
| 383 |
>>> sqltypeToPG("char(5)[4][7]") |
| 384 |
'TEXT[4][7]' |
| 385 |
>>> |
| 386 |
""" |
| 387 |
if type.upper().startswith("UNICODE"): |
| 388 |
type = "TEXT"+type[7:] |
| 389 |
|
| 390 |
mat = re.match(r"char\((?:\*|\d+)\)(.*)", type.lower()) |
| 391 |
if mat: |
| 392 |
type = "TEXT"+mat.group(1) |
| 393 |
|
| 394 |
return type |
| 395 |
|
| 396 |
|
| 397 |
sqltypeToXSD = ToXSDConverter().convert |
| 398 |
sqltypeToNumpy = ToNumpyConverter().convert |
| 399 |
sqltypeToPython = ToPythonConverter().convert |
| 400 |
sqltypeToPythonCode = ToPythonCodeConverter().convert |
| 401 |
sqltypeToPgValidator = ToPgTypeValidatorConverter().convert |
| 402 |
pythonToLiteral = ToLiteralConverter().convert |
| 403 |
|
| 404 |
|
| 405 |
if __name__=="__main__": # pragma: no cover |
| 406 |
import doctest |
| 407 |
doctest.testmod() |
| 408 |
|
| 409 |
__all__ = ["sqltypeToVOTable", "sqltypeToXSD", "sqltypeToNumpy", |
| 410 |
"sqltypeToPython", "sqltypeToPythonCode", "voTableToSQLType", |
| 411 |
"ConversionError", "FromSQLConverter", "pythonToLiteral", |
| 412 |
"sqltypeToPgValidator", "sqltypeToPG"] |