| 1 |
""" |
| 2 |
Tests for ADQL parsing and reasoning about query results. |
| 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 |
import datetime |
| 12 |
import functools |
| 13 |
import re |
| 14 |
import unittest |
| 15 |
|
| 16 |
from gavo.helpers import testhelpers |
| 17 |
|
| 18 |
from gavo import adql |
| 19 |
from gavo import base |
| 20 |
from gavo import stc |
| 21 |
from gavo import rsc |
| 22 |
from gavo import rscdef |
| 23 |
from gavo import rscdesc #noflake: for registration |
| 24 |
from gavo import utils |
| 25 |
from gavo.adql import annotations |
| 26 |
from gavo.adql import fieldinfos |
| 27 |
from gavo.adql import morphpg |
| 28 |
from gavo.adql import nodes |
| 29 |
from gavo.adql import ufunctions #noflake: for registration |
| 30 |
from gavo.protocols import adqlglue |
| 31 |
from gavo.protocols import tap |
| 32 |
from gavo.stc import tapstc |
| 33 |
from gavo.utils import pgsphere |
| 34 |
from gavo.utils import parsetricks |
| 35 |
|
| 36 |
import tresc |
| 37 |
|
| 38 |
MS = base.makeStruct |
| 39 |
|
| 40 |
class Error(Exception): |
| 41 |
pass |
| 42 |
|
| 43 |
|
| 44 |
# The resources below are used elsewhere (e.g., taptest). |
| 45 |
class _ADQLQuerier(testhelpers.TestResource): |
| 46 |
resources = [("conn", tresc.dbConnection)] |
| 47 |
|
| 48 |
def make(self, deps): |
| 49 |
class ADQLQuerier(base.UnmanagedQuerier): |
| 50 |
def queryADQL(self, query, timeout=10, maxrec=20000): |
| 51 |
qtable = adqlglue.runTAPQuery( |
| 52 |
query, timeout, self.connection, [], maxrec, False) |
| 53 |
res = rsc.InMemoryTable( |
| 54 |
qtable.tableDef, |
| 55 |
rows=list(qtable)) |
| 56 |
res.meta_ = qtable.meta_ |
| 57 |
qtable.cleanup() |
| 58 |
return res |
| 59 |
|
| 60 |
return ADQLQuerier(deps["conn"]) |
| 61 |
|
| 62 |
def cleanup(self, deps): |
| 63 |
deps["conn"].rollback() |
| 64 |
|
| 65 |
|
| 66 |
adqlQuerier = _ADQLQuerier() |
| 67 |
|
| 68 |
|
| 69 |
class _ADQLTestTable(testhelpers.TestResource): |
| 70 |
resources = [("conn", tresc.dbConnection)] |
| 71 |
|
| 72 |
def make(self, deps): |
| 73 |
self.rd = testhelpers.getTestRD() |
| 74 |
ds = rsc.makeData(self.rd.getById("ADQLTest"), |
| 75 |
connection=deps["conn"]) |
| 76 |
tap.publishToTAP(self.rd, deps["conn"]) |
| 77 |
return ds |
| 78 |
|
| 79 |
def clean(self, ds): |
| 80 |
conn = list(ds.tables.values())[0].connection |
| 81 |
conn.rollback() |
| 82 |
ds.dropTables(rsc.parseNonValidating) |
| 83 |
conn.commit() |
| 84 |
adqlTestTable = _ADQLTestTable() |
| 85 |
|
| 86 |
|
| 87 |
|
| 88 |
class MatchLimitTest(testhelpers.VerboseTest, metaclass=testhelpers.SamplesBasedAutoTest): |
| 89 |
def _runTest(self, sample): |
| 90 |
topClause, maxrec, hardLimit, expectedInQuery, expectedLimit = sample |
| 91 |
tree = parseWithArtificialTable( |
| 92 |
"SELECT %s * FROM spatial"%topClause) |
| 93 |
overflowLimit = adqlglue._updateMatchLimits(tree, maxrec, hardLimit) |
| 94 |
self.assertEqual(tree.setLimit, expectedInQuery) |
| 95 |
self.assertEqual(overflowLimit, expectedLimit) |
| 96 |
|
| 97 |
samples = [ |
| 98 |
("", 2000, 200000, 2000, 2000), |
| 99 |
("TOP 10", 2000, 200000, 10, 2000), |
| 100 |
("TOP 10000", 2000, 200000, 2001, 2001), |
| 101 |
("TOP 30000", None, 200000, 20001, 20001), |
| 102 |
("TOP 30000", None, None, 20001, 20001), |
| 103 |
# 05 |
| 104 |
("TOP 10000", 99999999999, None, 10000, 20000000), |
| 105 |
("TOP 10000", 99999999999, None, 10000, 20000000), |
| 106 |
("", 99999999999, None, 20000000, 20000000), |
| 107 |
("", 99999999999, 50000, 50000, 50000), |
| 108 |
("TOP 1", 1, 50000, 1, 2), |
| 109 |
] |
| 110 |
|
| 111 |
|
| 112 |
class _SymbolsParseTestBase(testhelpers.VerboseTest): |
| 113 |
def setUp(self): |
| 114 |
self.symbols, _ = adql.getRawGrammar() |
| 115 |
|
| 116 |
def _assertParses(self, symbol, literal): |
| 117 |
try: |
| 118 |
(self.symbols[symbol]+parsetricks.StringEnd()).parseString(literal) |
| 119 |
except adql.ParseException: |
| 120 |
raise AssertionError("%s doesn't parse %s but should."%(symbol, |
| 121 |
repr(literal))) |
| 122 |
|
| 123 |
def _assertDoesntParse(self, symbol, literal): |
| 124 |
try: |
| 125 |
(self.symbols[symbol]+parsetricks.StringEnd()).parseString(literal) |
| 126 |
except (adql.ParseException, adql.ParseSyntaxException): |
| 127 |
pass |
| 128 |
else: |
| 129 |
raise AssertionError("%s parses %s but shouldn't."%(symbol, |
| 130 |
repr(literal))) |
| 131 |
|
| 132 |
|
| 133 |
class _GoodExamplesBase(_SymbolsParseTestBase, metaclass=testhelpers.SamplesBasedAutoTest): |
| 134 |
def _runTest(self, sample): |
| 135 |
self._assertParses(*sample) |
| 136 |
|
| 137 |
|
| 138 |
class _BadExamplesBase(_SymbolsParseTestBase, metaclass=testhelpers.SamplesBasedAutoTest): |
| 139 |
def _runTest(self, sample): |
| 140 |
self._assertDoesntParse(*sample) |
| 141 |
|
| 142 |
|
| 143 |
class MiscBadSymbolsTest(_BadExamplesBase): |
| 144 |
samples = [ |
| 145 |
("dateValueExpression", "TIMESTAMP('1992-03-01', a)"), |
| 146 |
("dateValueExpression", "TIMESTAMP(b, a)"), |
| 147 |
("castSpecification", "cast(char)"), |
| 148 |
("castSpecification", "cast(x as y)"), |
| 149 |
("castSpecification", "cast(x as national bank)"), |
| 150 |
# 5 |
| 151 |
("numericValueExpression", "BITWISE_NOT()"), |
| 152 |
("numericValueExpression", "BITWISE_AND(a)"), |
| 153 |
("numericValueExpression", "BITWISE_AND(a, b, c)"), |
| 154 |
("joinedTable", "foo natural join (t1, t2)"), |
| 155 |
("joinedTable", "(t1 join t2) using (foo)"), |
| 156 |
# 10 |
| 157 |
("joinedTable", "(t1 join t2) on (t1.foo=t2.bar)"), |
| 158 |
("possiblyAliasedTable", "t1 tablesample(a)"), |
| 159 |
("numericValueFunction", "arr_map(POWER, a)"), |
| 160 |
("caseExpression", "case x 'a' then 8 when 'b' then 9 end"), |
| 161 |
("caseExpression", "case x when 'a'=x then 8 end"), |
| 162 |
# 15 |
| 163 |
("caseExpression", "case when 'a' then 8 end"), |
| 164 |
] |
| 165 |
|
| 166 |
|
| 167 |
class MiscGoodSymbolsTest(_GoodExamplesBase): |
| 168 |
samples = [ |
| 169 |
("searchCondition", "5+9<'b' || 'foo'"), |
| 170 |
("delimitedIdentifier", '"a"'), |
| 171 |
("delimitedIdentifier", '"a""b"'), |
| 172 |
("comparisonPredicate", '"ja ja"<"Umph"'), |
| 173 |
("comparisonPredicate", "a<b"), |
| 174 |
# 5 |
| 175 |
("comparisonPredicate", "'a'<'b'"), |
| 176 |
("comparisonPredicate", "'a'<'b' || 'foo'"), |
| 177 |
("comparisonPredicate", "5+9<'b' || 'foo'"), |
| 178 |
("characterStringLiteral", "'abc'"), |
| 179 |
("characterValueExpression", "'abc' || 'def'"), |
| 180 |
# 10 |
| 181 |
("stringValueExpression", "'abc' || 'def' || '78%%'"), |
| 182 |
("dateValueExpression", "TIMESTAMP('1992-03-01' || 'T12:33')"), |
| 183 |
("dateValueExpression", "TIMESTAMP(b)"), |
| 184 |
("castSpecification", "CAST(x+23.0 AS INTEGER)"), |
| 185 |
("castSpecification", "CAST('230' AS BIGINT)"), |
| 186 |
# 15 |
| 187 |
("castSpecification", "CAST(230 AS NATIONAL CHAR ( 10 ))"), |
| 188 |
("castSpecification", 'CAST("My stupid col" || \'x\' AS CHAR(1230))'), |
| 189 |
("castSpecification", "CAST(230 AS CHAR)"), |
| 190 |
("castSpecification", "CAST(230+PI() AS REAL)"), |
| 191 |
("castSpecification", "CAST(SQRT(honk) AS DOUBLE PRECISION)"), |
| 192 |
# 20 |
| 193 |
("castSpecification", "CAST('2017-02-30' AS TIMESTAMP)"), |
| 194 |
("castSpecification", "CAST(NULL AS TIMESTAMP)"), |
| 195 |
("numericValueExpression", "BitWISE_NOT(x)"), |
| 196 |
("numericValueExpression", "BITWISE_and(x, 2)"), |
| 197 |
("numericValueExpression", "BITWISE_OR(x, y+2)"), |
| 198 |
# 25 |
| 199 |
("numericValueExpression", "BITWISE_XOR(5, 2)"), |
| 200 |
("withSpecification", "WITH foobar as (select a,b,c from x)," |
| 201 |
" knatter as (select cos(d)+13 as foo from y)"), |
| 202 |
("valueExpressionPrimary", "arr[15]"), |
| 203 |
("valueExpressionPrimary", "arr[ROUND(x/10)+3]"), |
| 204 |
("derivedColumn", "98x"), |
| 205 |
#30 |
| 206 |
("derivedColumn", "(A+B)X"), |
| 207 |
("possiblyAliasedTable", '"gnott" as g tablesample (0.1)'), |
| 208 |
("possiblyAliasedTable", '"gnott" tablesample(1e-7)'), |
| 209 |
("setGeneratingFunction", "generate_series ( 3 , 4 )"), |
| 210 |
("castSpecification", "CAST(foo as char(*))"), |
| 211 |
#35 |
| 212 |
("castSpecification", "CAST(foo as varchar(4))"), |
| 213 |
("coalesceExpression", "COALESCE(x)"), |
| 214 |
("coalesceExpression", "COALESCE(round(x/10+3), NULL, 3)"), |
| 215 |
("numericPrimary", "PI()"), |
| 216 |
("castSpecification", "CAST(NULL AS DOUBLE PRECISION[])"), |
| 217 |
#40 |
| 218 |
("castSpecification", "CAST(NULL AS CHAR(39)[30])"), |
| 219 |
("numericValueFunction", "arr_map(sin(x), a)"), |
| 220 |
("numericValueFunction", "arr_map(4*power(x, 3)-3, a)"), |
| 221 |
("orderByClause", "order by z"), |
| 222 |
("orderByClause", "order by 23"), |
| 223 |
#45 |
| 224 |
("orderByClause", "order by z desc"), |
| 225 |
("orderByClause", "order by z desc, x asc"), |
| 226 |
("orderByClause", "order by z-1 desc, log10(x) asc"), |
| 227 |
("groupByClause", "group by z"), |
| 228 |
("groupByClause", "group by z, s"), |
| 229 |
#50 |
| 230 |
("groupByClause", "group by z[3], s+z"), |
| 231 |
("havingClause", "having x=z AND 7<u"), |
| 232 |
("caseExpression", "case x when 'a' then 8 when 'b' then 9 end"), |
| 233 |
("caseExpression", "case x when 'a' then 8*9 else 8*9 end"), |
| 234 |
("caseExpression", "case when x='a' then power(y,2)" |
| 235 |
" when 4<y then y-2 else 'u' end"), |
| 236 |
# 55 |
| 237 |
] |
| 238 |
|
| 239 |
|
| 240 |
class GoodBooleanTermsTest(_GoodExamplesBase): |
| 241 |
samples = [ |
| 242 |
("searchCondition", "z BETWEEN 8 AND 9"), |
| 243 |
("searchCondition", "z BETWEEN 'a' AND 'b'"), |
| 244 |
("searchCondition", "z BEtWEEN x+8 AnD x*8"), |
| 245 |
("searchCondition", "z NOT BETWEEN x+8 AND x*8"), |
| 246 |
("searchCondition", "z iN (a)"), |
| 247 |
("searchCondition", "z NoT In (a)"), |
| 248 |
("searchCondition", "z NOT IN (a, 4, 'xy')"), |
| 249 |
("searchCondition", "z IN (select x from foo)"), |
| 250 |
("searchCondition", "u LIKE '%'"), |
| 251 |
("searchCondition", "u NoT LiKE '%'"), |
| 252 |
("searchCondition", "u ILIKE '%'"), |
| 253 |
("searchCondition", "u Not ILIKE '%'"), |
| 254 |
("searchCondition", "u || 'foo' NOT LIKE '%'"), |
| 255 |
("searchCondition", "u NOT LIKE '%' || 'xy'"), |
| 256 |
("searchCondition", "k IS NULL"), |
| 257 |
("searchCondition", "k IS NOT NULL"), |
| 258 |
] |
| 259 |
|
| 260 |
|
| 261 |
class BadGeometriesTest(_BadExamplesBase): |
| 262 |
samples = [ |
| 263 |
("point", "POINT(x,y,z)"), |
| 264 |
("circle", "circle('ICRS', x)"), |
| 265 |
("circle", "circle(5, y)"), |
| 266 |
("geometryExpression", "circle('ICRS', x)"), |
| 267 |
("polygon", "POLYGON(2, 3)"), |
| 268 |
#5 |
| 269 |
("polygon", "POLYGON(2, 4, 3)"), |
| 270 |
("polygon", "POLYGON('', 2, 4, 3)"), |
| 271 |
("polygon", "POLYGON(POINT(2, 4), POINT(3, 5), 3, 6)"), |
| 272 |
("region", "REGION(23, 'CIRCLE ICRS 2 3 4)"), |
| 273 |
("booleanTerm", "Point('fk5',2,3)"), |
| 274 |
#10 |
| 275 |
("booleanTerm", "CIRCLE('fk5', 2, 3)=x"), |
| 276 |
("booleanTerm", "POLYGON('fk5', 2, 3, 3, 0, 23, 0, 45)=x"), |
| 277 |
("booleanTerm", "CENTROID(3)=x"), |
| 278 |
("booleanTerm", "CENTROID(COUNT(*))=x"), |
| 279 |
("nonPredicateGeometryFunction", "DISTANCE()"), |
| 280 |
#15 |
| 281 |
("nonPredicateGeometryFunction", "DISTANCE(a, b, c)"), |
| 282 |
("nonPredicateGeometryFunction", "DISTANCE(POINT(a,b), c, d)"), |
| 283 |
("nonPredicateGeometryFunction", "DISTANCE(POINT(a,b), POINT(c, d), e)"), |
| 284 |
("nonPredicateGeometryFunction", "DISTANCE(a, CENTROID(CIRCLE(b, c, d)))"), |
| 285 |
] |
| 286 |
|
| 287 |
|
| 288 |
class GoodGeometriesTest(_GoodExamplesBase): |
| 289 |
samples = [ |
| 290 |
("point", "pOint('ICRS', x,y)"), |
| 291 |
("point", "point(NULL, x,y)"), |
| 292 |
("point", "POINT(x,y)"), |
| 293 |
("circle", "circle('ICRS', x,y, r)"), |
| 294 |
("circle", "CIRCLE(NULL, 1,2, 4)"), |
| 295 |
#5 |
| 296 |
("circle", "CIRCLE(1,2, 4)"), |
| 297 |
("circle", "CIRCLE('', c, r)"), |
| 298 |
("circle", "CIRCLE(c, 5)"), |
| 299 |
("polygon", "POLYGON(NULL, 1, 2, 4, 3, 4, 4)"), |
| 300 |
("polygon", "POLYGON('', 1, 2, 4, 3, 4, 4)"), |
| 301 |
#10 |
| 302 |
("polygon", "POLYGON(1, 2, 4, 3, 4, 4)"), |
| 303 |
("polygon", "POLYGON(a, b, c)"), |
| 304 |
("polygon", "POLYGON(POINT(2,3), b, c)"), |
| 305 |
("polygon", "POLYGON(a, b, POINT(2,3))"), |
| 306 |
("box", "BOX(1, 2, 0.2, 0.1)"), |
| 307 |
#15 |
| 308 |
("box", "BOX('GALACTIC', 1, 2, 0.2, 0.1)"), |
| 309 |
("region", "REGION('CIRCLE ICRS 2 3 4)')"), |
| 310 |
("geometryExpression", "CIRCLE('ICRS', 1,2, 4)"), |
| 311 |
("predicateGeometryFunction", |
| 312 |
"Contains(pOint('ICRS', x,y),CIRCLE('ICRS', 1,2, 4))"), |
| 313 |
("booleanTerm", "Point(NULL, 2, 3)=x"), |
| 314 |
#20 |
| 315 |
("booleanTerm", "Point('fk5', 2, 3)=x"), |
| 316 |
("booleanTerm", "CIRCLE('fk5', 2, 3, 3)=x"), |
| 317 |
("booleanTerm", "box('fk5', 2, 3, 3, 0)=x"), |
| 318 |
("booleanTerm", "POLYGON('fk5', 2, 3, 3, 0, 23, 0, 45, 34)=x"), |
| 319 |
("booleanTerm", "REGION('mainfranken')=x"), |
| 320 |
#25 |
| 321 |
("booleanTerm", "CENTROID(CIRCLE('fk4', 2, 3, 3))=x"), |
| 322 |
("nonPredicateGeometryFunction", "DISTANCE(a, b)"), |
| 323 |
("nonPredicateGeometryFunction", "DISTANCE(POINT(a, b), POINT(c,d))"), |
| 324 |
("nonPredicateGeometryFunction", "DISTANCE(a, POINT(c, d))"), |
| 325 |
] |
| 326 |
|
| 327 |
|
| 328 |
class GoodUnitsTest(_GoodExamplesBase): |
| 329 |
samples = [ |
| 330 |
("unitLiteral", "{km/s**2}"), |
| 331 |
("literalWithUnit", "4{km}"), |
| 332 |
("literalWithUnit", "4.5e-9{J/pc**2}"), |
| 333 |
("numericValueExpression", "4.5e-9{J/pc**2}@{eV/m**2}"), |
| 334 |
("numericValueExpression", "(col1/col2/col2)@{eV/m**2}"), |
| 335 |
#05 |
| 336 |
# the following will fail in semantics, but it's correct grammar |
| 337 |
("numericValueExpression", "4.5e-9@{J/pc**2}"), |
| 338 |
("numericValueExpression", "4.5e-9@{J/pc**2}/44.3@{mm**-2}"), |
| 339 |
] |
| 340 |
|
| 341 |
|
| 342 |
class BadUnitsTest(_BadExamplesBase): |
| 343 |
samples = [ |
| 344 |
("unitLiteral", "{km/s**2"), |
| 345 |
("literalWithUnit", "4{quatsch}"), |
| 346 |
("literalWithUnit", "'53'{kW}"), |
| 347 |
("numericValueExpression", "4.5e-9{J/pc**2}@{ev/m**2}"), |
| 348 |
("literalWithUnit", "4.5e-9@{J/pc**2}"), # (that's a coercion, not a literal) |
| 349 |
] |
| 350 |
|
| 351 |
|
| 352 |
@unittest.skipUnless(testhelpers.hasUDF("GAVO_MOCUNION"), "pgsphere too old") |
| 353 |
class GoodMOCTest(_GoodExamplesBase): |
| 354 |
samples = [ |
| 355 |
("geometryValueExpression", "MOC('3/2,3')"), |
| 356 |
("moc", "MOC(3, point('ICRS', 3, 4))"), |
| 357 |
("moc", "MOC(3, POLYGON(3, 4, 5, 6, 7,8))"), |
| 358 |
("moc", "MOC(ordr, CIRCLE(3, 4, 8))"), |
| 359 |
("moc", "MOC(ordr, s_region)"), |
| 360 |
("moc", "MOC(ordr, MOC('4/6,7'))"), |
| 361 |
("moc", "MOC(ordr, MOC(4, CIRCLE(3,4,5)))"), |
| 362 |
("moc", "MOC(ordr, gavo_moc_union(MOC(3, CIRCLE(3,4,5)), MOC('0/1')))"), |
| 363 |
] |
| 364 |
|
| 365 |
|
| 366 |
class GoodStatementTests(_GoodExamplesBase): |
| 367 |
samples = [("statement", s) for s in [ |
| 368 |
"SELECT ivo_foo(6) || 9\n from Y", |
| 369 |
"SELECT ivo_foo('11') || 11 from Y", |
| 370 |
"SELECT 'text'*1323\n from Y", |
| 371 |
"select * from foo where 1=CONTAINS(\n" |
| 372 |
" REGION('Union ICRS (Position 1 2 Intersection" |
| 373 |
" (circle 1 2 3 box 1 2 3 4 circle 30 40 2))'),\n" |
| 374 |
" REGION('circle GALACTIC 1 2 3'))", |
| 375 |
"SELECT count(*) FROM x\nWHERE COALESCE(a, b, c) = 0", |
| 376 |
# 5 |
| 377 |
"select top 4* from (select * from amanda.nucand)x", |
| 378 |
"select * from bar order by foo asc, 2desc", |
| 379 |
"(SELECT TOP 10 id, ra, dec FROM atable ORDER BY id ASC)" |
| 380 |
" UNION (SELECT TOP 10 id, ra, dec FROM atable ORDER BY id DESC)", |
| 381 |
]] |
| 382 |
|
| 383 |
|
| 384 |
class BadStatementTests(_BadExamplesBase): |
| 385 |
samples = [("statement", s) for s in [ |
| 386 |
"SELECT point('icrs', 3, 4) || 'aaaa'\n from Y", |
| 387 |
]] |
| 388 |
|
| 389 |
|
| 390 |
class _ADQLParsesTest(testhelpers.VerboseTest): |
| 391 |
"""an abstract base for tests checking whether ADQL expressions parse. |
| 392 |
""" |
| 393 |
def setUp(self): |
| 394 |
_, self.grammar = adql.getRawGrammar() |
| 395 |
testhelpers.VerboseTest.setUp(self) |
| 396 |
|
| 397 |
def _assertGoodADQL(self, statement): |
| 398 |
try: |
| 399 |
self.grammar.parseString(statement) |
| 400 |
except (adql.ParseException, adql.ParseSyntaxException): |
| 401 |
raise AssertionError("%s doesn't parse but should."%statement) |
| 402 |
except RuntimeError: |
| 403 |
raise Error("%s causes an infinite recursion"%statement) |
| 404 |
|
| 405 |
def _assertBadADQL(self, statement): |
| 406 |
try: |
| 407 |
self.assertRaisesVerbose( |
| 408 |
(adql.ParseException,adql.ParseSyntaxException), |
| 409 |
self.grammar.parseString, (statement,), |
| 410 |
"Parses but shouldn't: %s"%statement) |
| 411 |
except RuntimeError: |
| 412 |
raise Error("%s causes an infinite recursion"%statement) |
| 413 |
|
| 414 |
|
| 415 |
class NodeTest(_ADQLParsesTest): |
| 416 |
def setUp(self): |
| 417 |
self.grammar = adql.getGrammar() |
| 418 |
|
| 419 |
def testNoChild(self): |
| 420 |
node = self.grammar.parseString("SELECT a, b, c FROM x") |
| 421 |
fields = node[0].children[0].children[0].selectList.selectFields |
| 422 |
self.assertRaisesWithMsg( |
| 423 |
adql.NoChild, |
| 424 |
"No ab child found in [<ADQL Node derivedColumn>," |
| 425 |
" <ADQL Node derivedColumn>, <ADQL Node derivedColumn>]", |
| 426 |
nodes.getChildOfType, |
| 427 |
(fields, "ab")) |
| 428 |
|
| 429 |
def testMoreChild(self): |
| 430 |
node = self.grammar.parseString("SELECT a, b, c FROM x") |
| 431 |
fields = node[0].children[0].children[0].selectList.selectFields |
| 432 |
self.assertRaisesWithMsg( |
| 433 |
adql.MoreThanOneChild, |
| 434 |
"Multiple derivedColumn children found in [<ADQL Node derivedColumn>," |
| 435 |
" <ADQL Node derivedColumn>, <ADQL Node derivedColumn>]", |
| 436 |
nodes.getChildOfType, |
| 437 |
(fields, "derivedColumn")) |
| 438 |
|
| 439 |
|
| 440 |
class NakedParseTest(_ADQLParsesTest): |
| 441 |
"""tests for plain parsing (without tree building). |
| 442 |
""" |
| 443 |
def _assertParse(self, correctStatements): |
| 444 |
for stmt in correctStatements: |
| 445 |
self._assertGoodADQL(stmt) |
| 446 |
|
| 447 |
def _assertDontParse(self, badStatements): |
| 448 |
for stmt in badStatements: |
| 449 |
self._assertBadADQL(stmt) |
| 450 |
|
| 451 |
def testPlainSelects(self): |
| 452 |
"""tests for non-errors on some elementary select expressions parse. |
| 453 |
""" |
| 454 |
self._assertParse([ |
| 455 |
"SELECT x FROM y", |
| 456 |
"SELECT x FROM y WHERE z=0", |
| 457 |
"SELECT x, v FROM y WHERE z=0 AND v>2", |
| 458 |
"SELECT 89 FROM X", |
| 459 |
"SELECT 89 FROM X AS Y", |
| 460 |
"SELECT 89 FROM X Y", |
| 461 |
]) |
| 462 |
|
| 463 |
def testDelimited(self): |
| 464 |
self._assertParse([ |
| 465 |
'SELECT "f-bar", "c""ho" FROM "nons-ak" WHERE "ja ja"<"Umph"']) |
| 466 |
|
| 467 |
def testSimpleSyntaxErrors(self): |
| 468 |
"""tests for rejection of gross syntactic errors. |
| 469 |
""" |
| 470 |
self._assertDontParse([ |
| 471 |
"W00T", |
| 472 |
"SELECT A", |
| 473 |
"SELECT A FROM", |
| 474 |
"SELECT A FROM B WHERE", |
| 475 |
"SELECT FROM", |
| 476 |
"SELECT 89! FROM z", |
| 477 |
]) |
| 478 |
|
| 479 |
def testCaseInsensitivity(self): |
| 480 |
"""tests for case being ignored in SQL keywords. |
| 481 |
""" |
| 482 |
self._assertParse([ |
| 483 |
"select z as U From n", |
| 484 |
"seLect z AS U FROM n", |
| 485 |
]) |
| 486 |
|
| 487 |
def testJoins(self): |
| 488 |
"""tests for JOIN syntax. |
| 489 |
""" |
| 490 |
self._assertParse([ |
| 491 |
"select x from t1, t2", |
| 492 |
"select x from t1, t2, t3", |
| 493 |
"select x from t1, t2, t3 WHERE t1.x=t2.y", |
| 494 |
"select x from t1 JOIN t2", |
| 495 |
"select x from t1 NATURAL JOIN t2", |
| 496 |
"select x from t1 LEFT OUTER JOIN t2", |
| 497 |
"select x from t1 RIGHT OUTER JOIN t2", |
| 498 |
"select x from t1 FULL OUTER JOIN t2", |
| 499 |
"select x from t1 FULL OUTER JOIN t2 ON (x=y)", |
| 500 |
"select x from t1 FULL OUTER JOIN t2 USING (x,y)", |
| 501 |
"select x from t1 INNER JOIN (t2 JOIN t3)", |
| 502 |
"select x from (t1 JOIN t4) FULL OUTER JOIN (t2 JOIN t3)", |
| 503 |
"select x from t1 NATURAL JOIN t2, t3", |
| 504 |
]) |
| 505 |
|
| 506 |
def testBadJoins(self): |
| 507 |
"""tests for syntax error detection in JOINs. |
| 508 |
""" |
| 509 |
self._assertDontParse([ |
| 510 |
"select x from t1 JOIN", |
| 511 |
"select x from JOIN t1", |
| 512 |
"select x from t1 join JOIN t1", |
| 513 |
"select x from t1 NATURAL JOIN t2, t3 OUTER", |
| 514 |
"select x from t1 NATURAL JOIN t2, t3 ON", |
| 515 |
"select x from t1, t2, t3 ON", |
| 516 |
]) |
| 517 |
|
| 518 |
def testBadDetritus(self): |
| 519 |
"""tests for syntax errors in ORDER BY and friends. |
| 520 |
""" |
| 521 |
self._assertDontParse([ |
| 522 |
"select x from t1 having y", |
| 523 |
]) |
| 524 |
|
| 525 |
def testBadBooleanTerms(self): |
| 526 |
p = "select x from y where " |
| 527 |
self._assertDontParse([ |
| 528 |
p+"z BETWEEN", |
| 529 |
p+"z BETWEEN AND", |
| 530 |
p+"z BETWEEN AND 5", |
| 531 |
p+"z 7 BETWEEN 5 AND ", |
| 532 |
p+"x IN", |
| 533 |
p+"x IN 5", |
| 534 |
p+"x IN (23, 3,)", |
| 535 |
p+"x Is None", |
| 536 |
]) |
| 537 |
|
| 538 |
def testsBadFunctions(self): |
| 539 |
"""tests for rejection of bad function calls. |
| 540 |
""" |
| 541 |
p = "select x from y where " |
| 542 |
self._assertDontParse([ |
| 543 |
p+"ABS()<3", |
| 544 |
p+"ABS(y,z)<3", |
| 545 |
p+"ATAN2(x)<3", |
| 546 |
p+"PI==3", |
| 547 |
]) |
| 548 |
|
| 549 |
def testFunkyIds(self): |
| 550 |
"""tests for parsing quoted identifiers. |
| 551 |
""" |
| 552 |
p = "select x from y where " |
| 553 |
self._assertParse([ |
| 554 |
p+'"some weird column">0', |
| 555 |
p+'"some even ""weirder"" column">0', |
| 556 |
p+'"SELECT">0', |
| 557 |
]) |
| 558 |
|
| 559 |
def testMiscGood(self): |
| 560 |
"""tests for parsing of various legal statements. |
| 561 |
""" |
| 562 |
self._assertParse([ |
| 563 |
"select a, b from (select * from x) AS q", |
| 564 |
]) |
| 565 |
|
| 566 |
def testMiscBad(self): |
| 567 |
"""tests for rejection of various bad statements. |
| 568 |
""" |
| 569 |
self._assertDontParse([ |
| 570 |
"select a, b from (select * from x) q r", |
| 571 |
"select a, b from (select * from x)", |
| 572 |
"select x.y.z.a.b from a", |
| 573 |
"select x from a.b.c.d", |
| 574 |
]) |
| 575 |
|
| 576 |
def testStringExpressionSelect(self): |
| 577 |
self._assertParse([ |
| 578 |
"select m || 'ab' from q",]) |
| 579 |
|
| 580 |
|
| 581 |
class FunctionsParseTest(_ADQLParsesTest, metaclass=testhelpers.SamplesBasedAutoTest): |
| 582 |
def _runTest(self, sample): |
| 583 |
self._assertGoodADQL("select x from y where "+sample) |
| 584 |
|
| 585 |
samples = [ |
| 586 |
"ABS(-3)<3", |
| 587 |
"ABS(-3.0)<3", |
| 588 |
"ABS(-3.0E4)<3", |
| 589 |
"ABS(-3.0e-4)<3", |
| 590 |
"ABS(x)<3", |
| 591 |
"ATAN2(-3.0e-4, 4.5)=x", |
| 592 |
"RAND(4)=x", |
| 593 |
"RAND()=x", |
| 594 |
"ROUND(23)=x", |
| 595 |
"ROUND(23,2)=x", |
| 596 |
"ROUND(PI(),2)=3.14", |
| 597 |
"POWER(x,10)=3.14", |
| 598 |
"POWER(10,x)=3.14", |
| 599 |
] |
| 600 |
|
| 601 |
|
| 602 |
class SetExpressionsTest(_ADQLParsesTest, metaclass=testhelpers.SamplesBasedAutoTest): |
| 603 |
def _runTest(self, sample): |
| 604 |
self._assertGoodADQL(sample) |
| 605 |
|
| 606 |
samples = [ |
| 607 |
"select x from t1 union select x from t2", |
| 608 |
"select x from t1 intersect select x from t2", |
| 609 |
"select x from t1 except select x from t2", |
| 610 |
"select x from t1 where x>2 union select x from t2", |
| 611 |
"select * from t1 union select x from t2 intersect select x from t3" |
| 612 |
" except select x from t4", |
| 613 |
# 5 |
| 614 |
"select * from (select * from t1 except select * from t2) as q union" |
| 615 |
" select * from t3", |
| 616 |
"select * from t1 union select foo from (select * from t2 except select * from t1) as q", |
| 617 |
] |
| 618 |
|
| 619 |
|
| 620 |
class AsTreeTest(testhelpers.VerboseTest): |
| 621 |
"""tests for asTree() |
| 622 |
""" |
| 623 |
def testSimple(self): |
| 624 |
t = adql.parseToTree("SELECT * FROM t WHERE 1=CONTAINS(" |
| 625 |
"CIRCLE('ICRS', 4, 4, 2), POINT('', ra, dec))").asTree() |
| 626 |
self.assertEqual(t[1][1][1][1][1][0], 'possiblyAliasedTable') |
| 627 |
self.assertEqual(t[1][1][1][3][0], 'whereClause') |
| 628 |
self.assertEqual(t[1][1][1][3][1][2][1][0], 'circle') |
| 629 |
|
| 630 |
|
| 631 |
class _TreeParseTestBase(testhelpers.VerboseTest): |
| 632 |
def setUp(self): |
| 633 |
self.grammar = adql.getGrammar() |
| 634 |
|
| 635 |
def assertAttrs(self, c, **assertions): |
| 636 |
for k,v in list(assertions.items()): |
| 637 |
self.assertEqual(getattr(c, k), v, |
| 638 |
"%s, %s!=%s"%(k, repr(getattr(c, k)), repr(v))) |
| 639 |
|
| 640 |
|
| 641 |
class TreeParseTest(_TreeParseTestBase): |
| 642 |
def testSelectList(self): |
| 643 |
for q, e in [ |
| 644 |
("select a from z", ["a"]), |
| 645 |
("select x.a from z", ["a"]), |
| 646 |
("select x.a, b from z", ["a", "b"]), |
| 647 |
('select "one weird name", b from z', |
| 648 |
[utils.QuotedName('one weird name'), "b"]), |
| 649 |
]: |
| 650 |
tree = self.grammar.parseString(q)[0] |
| 651 |
res = [c.name for c in tree.getSelectFields()] |
| 652 |
self.assertEqual(res, e, |
| 653 |
"Select list from %s: expected %s, got %s"%(q, e, res)) |
| 654 |
|
| 655 |
def testSourceTables(self): |
| 656 |
for q, e in [ |
| 657 |
("select * from z", ["z"]), |
| 658 |
("select * from z.x", ["z.x"]), |
| 659 |
("select * from z.x.y", ["z.x.y"]), |
| 660 |
("select * from z.x.y, a", ["z.x.y", "a"]), |
| 661 |
("select * from (select * from z) as q, a", ["q", "a"]), |
| 662 |
]: |
| 663 |
res = list(self.grammar.parseString(q)[0].getAllNames()) |
| 664 |
self.assertEqual(res, e, |
| 665 |
"Source tables from %s: expected %s, got %s"%(q, e, res)) |
| 666 |
|
| 667 |
def testSourceTablesJoin(self): |
| 668 |
for q, e in [ |
| 669 |
("select * from z join x", ["z", "x"]), |
| 670 |
("select * from (select * from a,b, (select * from c,d) as q) as r join" |
| 671 |
"(select * from x,y) as p", ["r", "p"]), |
| 672 |
]: |
| 673 |
res = list(self.grammar.parseString(q)[0].getAllNames()) |
| 674 |
self.assertEqual(res, e, |
| 675 |
"Source tables from %s: expected %s, got %s"%(q, e, res)) |
| 676 |
|
| 677 |
def testContributingTables(self): |
| 678 |
q = ("select * from (select * from urks.a,b," |
| 679 |
" (select * from c,monk.d) as q) as r join" |
| 680 |
" (select * from x,y) as p") |
| 681 |
self.grammar.parseString(q)[0].getContributingNames() |
| 682 |
self.assertEqual(self.grammar.parseString(q)[0].getContributingNames(), |
| 683 |
set(['c', 'b', 'urks.a', 'q', 'p', 'r', 'y', 'x', 'monk.d'])) |
| 684 |
|
| 685 |
def testAliasedColumn(self): |
| 686 |
q = "select foo+2 as fp2 from x" |
| 687 |
res = self.grammar.parseString(q)[0] |
| 688 |
field = list(res.getSelectFields())[0] |
| 689 |
self.assertEqual(field.name, "fp2") |
| 690 |
|
| 691 |
def testTainting(self): |
| 692 |
for q, (exName, exTaint) in [ |
| 693 |
("select x from z", ("x", False)), |
| 694 |
("select x as u from z", ("u", False)), |
| 695 |
("select x+2 from z", (None, True)), |
| 696 |
('select x+2 as "99 Monkeys" from z', (utils.QuotedName("99 Monkeys"), |
| 697 |
True)), |
| 698 |
('select x+2 as " ""cute"" Monkeys" from z', |
| 699 |
(utils.QuotedName(' "cute" Monkeys'), True)), |
| 700 |
]: |
| 701 |
res = list(self.grammar.parseString(q)[0].getSelectFields())[0] |
| 702 |
self.assertEqual(res.tainted, exTaint, "Field taintedness wrong in %s"% |
| 703 |
q) |
| 704 |
if exName: |
| 705 |
self.assertEqual(res.name, exName) |
| 706 |
|
| 707 |
def testValueExpressionColl(self): |
| 708 |
t = adql.parseToTree("select x from z where 5+9>'gaga'||'bla'") |
| 709 |
compPred = t.whereClause.children[1] |
| 710 |
self.assertEqual(compPred.op1.type, "numericValueExpression") |
| 711 |
self.assertEqual(compPred.opr, ">") |
| 712 |
self.assertEqual(compPred.op2.type, "stringValueExpression") |
| 713 |
|
| 714 |
def testQualifiedStar(self): |
| 715 |
t = adql.parseToTree("select t1.*, s1.t2.* from t1, s1.t2, s2.t3") |
| 716 |
self.assertEqual(t.selectList.selectFields[0].type, "qualifiedStar") |
| 717 |
self.assertEqual(t.selectList.selectFields[0].sourceTable.qName, |
| 718 |
"t1") |
| 719 |
self.assertEqual(t.selectList.selectFields[1].sourceTable.qName, |
| 720 |
"s1.t2") |
| 721 |
|
| 722 |
def testBadSystem(self): |
| 723 |
self.assertRaises(adql.ParseSyntaxException, |
| 724 |
self.grammar.parseString, "select point('QUARK', 1, 2) from spatial") |
| 725 |
|
| 726 |
def testQuotedTableName(self): |
| 727 |
t = adql.parseToTree('select "abc-g".* from "abc-g" JOIN "select"') |
| 728 |
self.assertEqual(t.selectList.selectFields[0].sourceTable.name, "abc-g") |
| 729 |
self.assertEqual(t.selectList.selectFields[0].sourceTable.qName, '"abc-g"') |
| 730 |
|
| 731 |
def testQuotedSchemaName(self): |
| 732 |
t = adql.parseToTree('select * from "Murks Schema"."Murks Tabelle"') |
| 733 |
table = t.fromClause.tableReference |
| 734 |
self.assertEqual(table.tableName.name, |
| 735 |
utils.QuotedName("Murks Tabelle")) |
| 736 |
self.assertEqual(table.tableName.schema, |
| 737 |
utils.QuotedName("Murks Schema")) |
| 738 |
|
| 739 |
def testSetLimitInherited(self): |
| 740 |
t = adql.parseToTree('select top 3 * from t1 union' |
| 741 |
' select top 4 * from t2 except select * from t3') |
| 742 |
self.assertEqual(t.setLimit, 4) |
| 743 |
|
| 744 |
def testSetLimitDeep(self): |
| 745 |
t = adql.parseToTree( |
| 746 |
'select top 7 * from t1 union' |
| 747 |
' (select top 4 * from t2 except select * from t3)' |
| 748 |
' except (select top 30 x from t4 except select top 3 y from t5)') |
| 749 |
self.assertEqual(t.setLimit, 30) |
| 750 |
|
| 751 |
def testHexadecimal(self): |
| 752 |
t = adql.parseToTree( |
| 753 |
"select x-0xaf, -0x1fffffff from t1") |
| 754 |
sels = list(t.getSelectClauses())[0].selectList.selectFields |
| 755 |
self.assertEqual(sels[0].flatten(), 'x - 175') |
| 756 |
self.assertEqual(sels[1].flatten(), '- 536870911') |
| 757 |
|
| 758 |
|
| 759 |
class CircleTreeParseTest(_TreeParseTestBase): |
| 760 |
def _getParsed(self, circleLiteral): |
| 761 |
t = adql.parseToTree('select %s from t1'%circleLiteral) |
| 762 |
return t.children[0].selectList.selectFields[0].expr |
| 763 |
|
| 764 |
def testColrefNosys(self): |
| 765 |
c = self._getParsed("CIRCLE(x, r)") |
| 766 |
self.assertAttrs(c, cooSys="") |
| 767 |
self.assertAttrs(c.radius, type="columnReference", name="r") |
| 768 |
self.assertAttrs(c.center, type="columnReference", name="x") |
| 769 |
|
| 770 |
def testColrefWithsys(self): |
| 771 |
c = self._getParsed("CIRCLE('ICRS', \"center\", \"radius\")") |
| 772 |
self.assertAttrs(c, cooSys="ICRS") |
| 773 |
self.assertAttrs(c.radius, type="columnReference", name="radius") |
| 774 |
self.assertAttrs(c.center, type="columnReference", name="center") |
| 775 |
|
| 776 |
def testSplitNosys(self): |
| 777 |
c = self._getParsed("CIRCLE(a, d, r)") |
| 778 |
self.assertAttrs(c, cooSys="") |
| 779 |
self.assertAttrs(c.radius, type="columnReference", name="r") |
| 780 |
self.assertAttrs(c.center.x, type="columnReference", name="a") |
| 781 |
self.assertAttrs(c.center.y, type="columnReference", name="d") |
| 782 |
|
| 783 |
def testLiteralPoint(self): |
| 784 |
c = self._getParsed("CIRCLE(NULL, POINT(a, d) ,r)") |
| 785 |
self.assertAttrs(c, cooSys="UNKNOWN") |
| 786 |
self.assertAttrs(c.radius, type="columnReference", name="r") |
| 787 |
self.assertAttrs(c.center.x, type="columnReference", name="a") |
| 788 |
self.assertAttrs(c.center.y, type="columnReference", name="d") |
| 789 |
|
| 790 |
def testLiteralPointNosys(self): |
| 791 |
c = self._getParsed("CIRCLE(POINT('ICRS', a, d) ,r)") |
| 792 |
self.assertAttrs(c, cooSys="") |
| 793 |
self.assertAttrs(c.radius, type="columnReference", name="r") |
| 794 |
self.assertAttrs(c.center.x, type="columnReference", name="a") |
| 795 |
self.assertAttrs(c.center.y, type="columnReference", name="d") |
| 796 |
|
| 797 |
def testSplitWithExpression(self): |
| 798 |
c = self._getParsed("CIRCLE(ra+2, dec ,r-1)") |
| 799 |
self.assertAttrs(c, cooSys="") |
| 800 |
self.assertAttrs(c.radius, type="numericValueExpression") |
| 801 |
self.assertAttrs(c.center.x, type="numericValueExpression") |
| 802 |
self.assertAttrs(c.center.y, type="columnReference", name="dec") |
| 803 |
self.assertEqual(c.radius.children[1], '-') |
| 804 |
|
| 805 |
@unittest.skipUnless(testhelpers.hasUDF("IVO_EPOCH_PROP"), "pgsphere too old") |
| 806 |
def testGeoUDF(self): |
| 807 |
c = self._getParsed("CIRCLE(ivo_apply_pm(12, 13, 1e-7, -1e-7, 19) ,r)") |
| 808 |
self.assertEqual(c.flatten(), |
| 809 |
"CIRCLE(IVO_APPLY_PM(12, 13, 1e-7, - 1e-7, 19),r)") |
| 810 |
|
| 811 |
|
| 812 |
class PolygonTreeParseTest(_TreeParseTestBase): |
| 813 |
def _getParsed(self, polygonLiteral): |
| 814 |
t = adql.parseToTree('select %s from t1'%polygonLiteral) |
| 815 |
return t.children[0].selectList.selectFields[0].expr |
| 816 |
|
| 817 |
def testColrefNosys(self): |
| 818 |
p = self._getParsed("POLYGON(a, b, c, d)") |
| 819 |
self.assertAttrs(p, type="polygon", cooSys="", coos=None) |
| 820 |
self.assertEqual(len(p.points), 4) |
| 821 |
self.assertAttrs(p.points[0], type="columnReference", name="a") |
| 822 |
self.assertAttrs(p.points[-1], type="columnReference", name="d") |
| 823 |
|
| 824 |
def testColrefWithsys(self): |
| 825 |
p = self._getParsed("polygon('ICRS', \"p 1\", \"p 2\", p3)") |
| 826 |
self.assertAttrs(p, cooSys="ICRS", coos=None) |
| 827 |
self.assertEqual(len(p.points), 3) |
| 828 |
self.assertAttrs(p.points[0], type="columnReference", name="p 1") |
| 829 |
self.assertAttrs(p.points[1], type="columnReference", name="p 2") |
| 830 |
self.assertAttrs(p.points[2], type="columnReference", name="p3") |
| 831 |
|
| 832 |
def testSplitNosys(self): |
| 833 |
p = self._getParsed("polygon(x1, y1, x2, y2, x3, y3)") |
| 834 |
self.assertAttrs(p, cooSys="", points=None) |
| 835 |
self.assertEqual(len(p.coos), 3) |
| 836 |
self.assertAttrs(p.coos[0][0], type="columnReference", name="x1") |
| 837 |
self.assertAttrs(p.coos[-1][1], type="columnReference", name="y3") |
| 838 |
|
| 839 |
def testLiteralPoints(self): |
| 840 |
p = self._getParsed("POLYGON(NULL, POINT(x1, y1)," |
| 841 |
" POINT('ICRS', x2, y2), POINT(x3,y3))") |
| 842 |
self.assertAttrs(p, cooSys="UNKNOWN", points=None) |
| 843 |
self.assertEqual(len(p.coos), 3) |
| 844 |
self.assertAttrs(p.coos[0][0], type="columnReference", name="x1") |
| 845 |
self.assertAttrs(p.coos[-1][1], type="columnReference", name="y3") |
| 846 |
|
| 847 |
def testLiteralPointNosys(self): |
| 848 |
p = self._getParsed("POLYGON(NULL, POINT(x1, y1)," |
| 849 |
" p, POINT(x3,y3))") |
| 850 |
self.assertAttrs(p, cooSys="UNKNOWN", coos=None) |
| 851 |
self.assertEqual(len(p.points), 3) |
| 852 |
self.assertAttrs(p.points[0].x, type="columnReference", name="x1") |
| 853 |
self.assertAttrs(p.points[-1].y, type="columnReference", name="y3") |
| 854 |
|
| 855 |
def testSplitWithExpression(self): |
| 856 |
p = self._getParsed( |
| 857 |
"polygon(ra+1, dec+1 ,ra+1, dec-1, ra-1, dec+1, ra-1, dec-1)") |
| 858 |
self.assertAttrs(p, cooSys="", points=None) |
| 859 |
self.assertAttrs(p.coos[0][0], type="numericValueExpression") |
| 860 |
self.assertEqual(p.coos[-1][1].children[1], "-") |
| 861 |
|
| 862 |
@unittest.skipUnless(testhelpers.hasUDF("IVO_EPOCH_PROP"), "pgsphere too old") |
| 863 |
def testGeoUDF(self): |
| 864 |
p = self._getParsed("polygon(ivo_apply_pm(12, 13, 1e-7, -1e-7, 19)," |
| 865 |
"ivo_apply_pm(12, 13, -1e-7, 1e-7, -19)," |
| 866 |
"ivo_apply_pm(12, 13, 1e-7, -1e-7, -19)," |
| 867 |
"ivo_apply_pm(12, 13, 1e-7, 1e-7, 19))") |
| 868 |
self.assertEqual(len(p.points), 4) |
| 869 |
self.assertEqual(p.flatten(), |
| 870 |
"POLYGON(IVO_APPLY_PM(12, 13, 1e-7, - 1e-7, 19)," |
| 871 |
" IVO_APPLY_PM(12, 13, - 1e-7, 1e-7, - 19)," |
| 872 |
" IVO_APPLY_PM(12, 13, 1e-7, - 1e-7, - 19)," |
| 873 |
" IVO_APPLY_PM(12, 13, 1e-7, 1e-7, 19))") |
| 874 |
|
| 875 |
|
| 876 |
class DistanceParseTest(_TreeParseTestBase): |
| 877 |
def _getParsed(self, distanceLiteral): |
| 878 |
t = adql.parseToTree('select %s from t1'%distanceLiteral) |
| 879 |
return t.children[0].selectList.selectFields[0].expr |
| 880 |
|
| 881 |
def testSplitArgs(self): |
| 882 |
df = self._getParsed("distance(1, dec1, ra2, dec2)") |
| 883 |
self.assertAttrs(df, funName="DISTANCE") |
| 884 |
self.assertEqual(len(df.args), 2) |
| 885 |
self.assertAttrs(df.args[0], type="point") |
| 886 |
self.assertAttrs(df.args[1].y, type="columnReference", name="dec2") |
| 887 |
|
| 888 |
def testPointArgs(self): |
| 889 |
df = self._getParsed("distance(p1, p2)") |
| 890 |
self.assertAttrs(df, funName="DISTANCE") |
| 891 |
self.assertEqual(len(df.args), 2) |
| 892 |
self.assertAttrs(df.args[0], type="columnReference", name="p1") |
| 893 |
self.assertAttrs(df.args[-1], type="columnReference", name="p2") |
| 894 |
|
| 895 |
def testPointArgsLiterals(self): |
| 896 |
df = self._getParsed("distance(point(ra1, dec1), point(ra2, dec2))") |
| 897 |
self.assertAttrs(df, funName="DISTANCE") |
| 898 |
self.assertEqual(len(df.args), 2) |
| 899 |
self.assertAttrs(df.args[0], type="point") |
| 900 |
self.assertAttrs(df.args[1].y, type="columnReference", name="dec2") |
| 901 |
|
| 902 |
def testPointArgsOneLiteral(self): |
| 903 |
df = self._getParsed("distance(point(ra1, dec1), p2)") |
| 904 |
self.assertAttrs(df, funName="DISTANCE") |
| 905 |
self.assertEqual(len(df.args), 2) |
| 906 |
self.assertAttrs(df.args[0], type="point") |
| 907 |
self.assertAttrs(df.args[0].x, type="columnReference", name="ra1") |
| 908 |
self.assertAttrs(df.args[1], type="columnReference", name="p2") |
| 909 |
|
| 910 |
|
| 911 |
class ParseErrorTest(testhelpers.VerboseTest, |
| 912 |
metaclass=testhelpers.SamplesBasedAutoTest): |
| 913 |
"""tests for sensible error messages. |
| 914 |
""" |
| 915 |
|
| 916 |
def _runTest(self, sample): |
| 917 |
query, msgFragment = sample |
| 918 |
# pyparsing has changed its quotes over the time; cope with both |
| 919 |
# versions: |
| 920 |
msgFragment = msgFragment.replace('"', """['"]""") |
| 921 |
try: |
| 922 |
_ = adql.getGrammar().parseString(query, parseAll=True) |
| 923 |
except (adql.ParseException, adql.ParseSyntaxException) as ex: |
| 924 |
msg = str(ex) |
| 925 |
self.assertTrue(re.search(msgFragment, msg), |
| 926 |
"'%s' does not contain '%s'"%(msg, msgFragment)) |
| 927 |
else: |
| 928 |
self.fail("'%s' parses but should not"%query) |
| 929 |
|
| 930 |
samples = [ |
| 931 |
("", r'Expected SELECT.* \(at char 0'), |
| 932 |
("select mag from %s", r'Expected table reference.* \(at char 16'), |
| 933 |
("SELECT TOP foo FROM x", r'Expected unsigned integer.* \(at char 11'), |
| 934 |
("SELECT FROM x", r'Expected select list.* \(at char 7'), |
| 935 |
("SELECT x, FROM y", r'Expected select list item.* \(at char 10'), |
| 936 |
#5 |
| 937 |
("SELECT * FROM distinct", r'Expected table reference.* \(at char 14'), |
| 938 |
("SELECT DISTINCT FROM y", r'Expected select list.* \(at char 16'), |
| 939 |
("SELECT *", r'Expected FROM.* \(at char 8'), |
| 940 |
("SELECT * FROM y WHERE", r'Expected boolean expression.* \(at char 21'), |
| 941 |
("SELECT * FROM y WHERE y u 2", |
| 942 |
r'Expected boolean expression.* \(at char 24'), |
| 943 |
# 10 |
| 944 |
("SELECT * FROM y WHERE y < 2 AND", |
| 945 |
r'Expected boolean expression.* \(at char 31'), |
| 946 |
("SELECT * FROM y WHERE y < 2 OR", |
| 947 |
r'Expected boolean expression.* \(at char 30'), |
| 948 |
("SELECT * FROM y WHERE y IS 3", r'Expected NULL.* \(at char 27'), |
| 949 |
("SELECT * FROM y WHERE CONTAINS(a,b)", |
| 950 |
r'Expected boolean expression.* \(at char 35'), |
| 951 |
("SELECT * FROM y WHERE 1=CONTAINS(POINT('ICRS',x,COUNT)" |
| 952 |
" ,CIRCLE('ICRS',x,y,z))", |
| 953 |
r"Expected boolean expression, found 'C' \(at char 24\)"), |
| 954 |
# 15 |
| 955 |
("SELECT * FROM (SELECT * FROM x)", |
| 956 |
r'Expected table reference.* \(at char 31'), |
| 957 |
("SELECT * FROM x WHERE EXISTS z", r'Expected subquery.* \(at char 29'), |
| 958 |
("SELECT POINT('junk', 3,4) FROM z", |
| 959 |
r'.*xpected "\)", found \',\' \(at char 22'), |
| 960 |
("SELECT * from a join b on foo", |
| 961 |
r"Expected boolean expression.* \(at char 29"), |
| 962 |
("SELECT * from a OFFSET 20 join b on foo", |
| 963 |
r"Expected end of text.* \(at char 26"), |
| 964 |
# 20 |
| 965 |
("SELECT * from a natural join b OFFSET banana", |
| 966 |
r"Expected unsigned integer.* \(at char 38"), |
| 967 |
# TODO: it would be cool if we found a way to reject the circle. |
| 968 |
("select * from ivoa.obscore where 1=contains(point(s_ra, s_dec)," |
| 969 |
" circle(120, 30))", |
| 970 |
r"Expected boolean expression, found 'c' \(at char 35\)"), |
| 971 |
("CREATE TABLE grube.quatsch AS SELECT * from foo.bar", |
| 972 |
r"""Expected "tap_user", found 'g' \(at char 13\)"""), |
| 973 |
] |
| 974 |
|
| 975 |
|
| 976 |
class JoinTypeTest(testhelpers.VerboseTest, metaclass=testhelpers.SamplesBasedAutoTest): |
| 977 |
sym = adql.getSymbols()["joinedTable"] |
| 978 |
|
| 979 |
def _collectJoinTypes(self, joinedNode): |
| 980 |
res = [] |
| 981 |
if hasattr(joinedNode.leftOperand, "leftOperand"): |
| 982 |
res.extend(self._collectJoinTypes(joinedNode.leftOperand)) |
| 983 |
res.append(joinedNode.getJoinType()) |
| 984 |
if hasattr(joinedNode.rightOperand, "leftOperand"): |
| 985 |
res.extend(self._collectJoinTypes(joinedNode.rightOperand)) |
| 986 |
return res |
| 987 |
|
| 988 |
def _runTest(self, sample): |
| 989 |
query, joinType = sample |
| 990 |
self.assertEqual( |
| 991 |
self._collectJoinTypes(self.sym.parseString(query)[0]), joinType) |
| 992 |
|
| 993 |
samples = [ |
| 994 |
("a CROSS JOIN b", ["CROSS"]), |
| 995 |
("a join b", ["NATURAL"]), |
| 996 |
("a join b using (x)", ["USING"]), |
| 997 |
("a CROSS JOIN b CROSS JOIN c", ["CROSS", "CROSS"]), |
| 998 |
("a CROSS JOIN b join c", ["CROSS", "NATURAL"]), |
| 999 |
#5 |
| 1000 |
("a join b cross join c", ["NATURAL", "CROSS"]), |
| 1001 |
("a join b on (x=y) cross join c", ["CROSS", "CROSS"]), |
| 1002 |
("a join b using (x,y) join c", ["USING", "NATURAL"]), |
| 1003 |
("a join b using (x,y) join c using (z,v)", ["USING", "USING"]), |
| 1004 |
("(a join b using (x,y)) join c using (z,v)", ["USING", "USING"]), |
| 1005 |
# 10 |
| 1006 |
("(a join b) cross join (c join d)", ["NATURAL", "CROSS", "NATURAL"]), |
| 1007 |
] |
| 1008 |
|
| 1009 |
|
| 1010 |
_largeTable = MS(rscdef.TableDef, nrows=1000000) |
| 1011 |
_smallTable = MS(rscdef.TableDef, nrows=1000) |
| 1012 |
|
| 1013 |
spatialFields = [ |
| 1014 |
MS(rscdef.Column, name="dist", ucd="phys.distance", unit="m"), |
| 1015 |
MS(rscdef.Column, name="width", ucd="phys.dim", unit="m"), |
| 1016 |
MS(rscdef.Column, name="height", ucd="phys.dim", unit="km"), |
| 1017 |
MS(rscdef.Column, name="ra1", ucd="pos.eq.ra", unit="deg", |
| 1018 |
parent_=_smallTable, tablehead="Raw RA"), |
| 1019 |
MS(rscdef.Column, name="ra2", ucd="pos.eq.ra", unit="rad"), |
| 1020 |
MS(rscdef.Column, name="gibtnet", ucd="invalid", unit="junk", hidden=True),] |
| 1021 |
spatial2Fields = [ |
| 1022 |
MS(rscdef.Column, name="ra1", ucd="pos.eq.ra;meta.main", unit="deg", |
| 1023 |
parent_=_largeTable), |
| 1024 |
MS(rscdef.Column, name="dec", ucd="pos.eq.dec;meta.main", unit="deg"), |
| 1025 |
MS(rscdef.Column, name="dist", ucd="phys.distance", unit="m"), |
| 1026 |
MS(rscdef.Column, name="t", ucd="time.epoch", unit="h")] |
| 1027 |
miscFields = [ |
| 1028 |
MS(rscdef.Column, name="mass", ucd="phys.mass", unit="kg"), |
| 1029 |
MS(rscdef.Column, name="mag", ucd="phot.mag", unit="mag"), |
| 1030 |
MS(rscdef.Column, name="speed", ucd="phys.veloc", unit="km/s")] |
| 1031 |
quotedFields = [ |
| 1032 |
MS(rscdef.Column, name=utils.QuotedName("left-right"), ucd="mess", |
| 1033 |
unit="bg"), |
| 1034 |
MS(rscdef.Column, name=utils.QuotedName('inch"ing'), ucd="imperial.mess", |
| 1035 |
unit="fin"), |
| 1036 |
MS(rscdef.Column, name=utils.QuotedName('plAin'), ucd="boring.stuff", |
| 1037 |
unit="pc"), |
| 1038 |
MS(rscdef.Column, name=utils.QuotedName('alllower'), ucd="simple.case", |
| 1039 |
unit="km"),] |
| 1040 |
crazyFields = [ |
| 1041 |
MS(rscdef.Column, name="ct", type="integer"), |
| 1042 |
MS(rscdef.Column, name="wot", type="bigint", |
| 1043 |
values=MS(rscdef.Values, nullLiteral="-1")), |
| 1044 |
MS(rscdef.Column, name="wotb", type="bytea", |
| 1045 |
values=MS(rscdef.Values, nullLiteral="254")), |
| 1046 |
MS(rscdef.Column, name="mass", ucd="event;using.incense"), |
| 1047 |
MS(rscdef.Column, name="name", type="unicode"), |
| 1048 |
MS(rscdef.Column, name="version", type="text"), |
| 1049 |
MS(rscdef.Column, name="flag", type="char"), |
| 1050 |
MS(rscdef.Column, name="vals", type="real[]", ucd="some.value", unit="yr")] |
| 1051 |
geoFields = [ |
| 1052 |
MS(rscdef.Column, name="pt", type="spoint"), |
| 1053 |
MS(rscdef.Column, name="coverage", type="spoly"), |
| 1054 |
MS(rscdef.Column , name="dt", type="timestamp", ucd="time;obs"), |
| 1055 |
] |
| 1056 |
|
| 1057 |
def _addSpatialSTC(sf, sf2, geo): |
| 1058 |
ast1 = stc.parseQSTCS('Position ICRS "ra1" "dec" Size "width" "height"') |
| 1059 |
ast2 = stc.parseQSTCS('Position FK4 SPHER3 "ra2" "dec" "dist"') |
| 1060 |
# XXX TODO: get utypes from ASTs |
| 1061 |
sf[0].stc, sf[0].stcUtype = ast2, None |
| 1062 |
sf[1].stc, sf[1].stcUtype = ast1, None |
| 1063 |
sf[2].stc, sf[2].stcUtype = ast1, None |
| 1064 |
sf[3].stc, sf[3].stcUtype = ast1, None |
| 1065 |
sf[4].stc, sf[4].stcUtype = ast2, None |
| 1066 |
sf2[0].stc, sf2[0].stcUtype = ast1, None |
| 1067 |
sf2[1].stc, sf2[0].stcUtype = ast1, None |
| 1068 |
sf2[2].stc, sf2[0].stcUtype = ast2, None |
| 1069 |
ast3 = stc.parseQSTCS('Time TT BARYCENTER "dt" Position GALACTIC [pt]') |
| 1070 |
geo[0].stc = ast3 |
| 1071 |
geo[1].stc = ast3 |
| 1072 |
_addSpatialSTC(spatialFields, spatial2Fields, geoFields) |
| 1073 |
|
| 1074 |
|
| 1075 |
def _addFakeIndices(sf): |
| 1076 |
assert sf[3].name=='ra1' |
| 1077 |
sf[3].isIndexed = lambda: ['q3c'] |
| 1078 |
_addFakeIndices(spatialFields) |
| 1079 |
|
| 1080 |
|
| 1081 |
class _MTH(object): |
| 1082 |
@classmethod |
| 1083 |
def getTableDefForTable(cls, tableName): |
| 1084 |
return { |
| 1085 |
'spatial': spatialFields, |
| 1086 |
'spatial2': spatial2Fields, |
| 1087 |
'misc': miscFields, |
| 1088 |
'quoted': quotedFields, |
| 1089 |
'crazy': crazyFields, |
| 1090 |
'geo': geoFields}.get(tableName) |
| 1091 |
|
| 1092 |
|
| 1093 |
class _SampleFieldInfoGetter(adqlglue.DaCHSFieldInfoGetter): |
| 1094 |
def __init__(self, *args): |
| 1095 |
adqlglue.DaCHSFieldInfoGetter.__init__(self) |
| 1096 |
self.mth = _MTH |
| 1097 |
|
| 1098 |
|
| 1099 |
@functools.lru_cache(None) |
| 1100 |
def _getFieldInfoGetter(): |
| 1101 |
return _SampleFieldInfoGetter() |
| 1102 |
|
| 1103 |
|
| 1104 |
class TestFieldInfoGetter(testhelpers.VerboseTest): |
| 1105 |
def testBasic(self): |
| 1106 |
s2 = _getFieldInfoGetter()("spatial2") |
| 1107 |
self.assertEqual(len(s2), 4) |
| 1108 |
self.assertEqual(s2[3][0], "t") |
| 1109 |
self.assertEqual(s2[3][1].unit, "h") |
| 1110 |
self.assertEqual(s2[3][1].userData[0].unit, "h") |
| 1111 |
|
| 1112 |
|
| 1113 |
def testNotFound(self): |
| 1114 |
self.assertRaisesWithMsg( |
| 1115 |
base.NotFoundError, |
| 1116 |
"table 'does.not.exist' could not be located in system" |
| 1117 |
" and uploaded tables", |
| 1118 |
_getFieldInfoGetter(), |
| 1119 |
("does.not.exist",)) |
| 1120 |
|
| 1121 |
|
| 1122 |
def parseWithArtificialTable(query): |
| 1123 |
parsedTree = adql.getGrammar().parseString(query)[0] |
| 1124 |
_ = adql.annotate(parsedTree, _getFieldInfoGetter()) |
| 1125 |
return parsedTree |
| 1126 |
|
| 1127 |
|
| 1128 |
class TypecalcTest(testhelpers.VerboseTest, metaclass=testhelpers.SamplesBasedAutoTest): |
| 1129 |
def _runTest(self, sample): |
| 1130 |
inTypes, result = sample |
| 1131 |
self.assertEqual(adql.getSubsumingType(inTypes), result) |
| 1132 |
|
| 1133 |
samples = [ |
| 1134 |
(["double precision", "integer", "bigint"], 'double precision'), |
| 1135 |
(["date", "timestamp", "timestamp"], 'timestamp'), |
| 1136 |
(["date", "boolean", "smallint"], 'text'), |
| 1137 |
(["box", "raw"], 'raw'), |
| 1138 |
(["date", "time"], 'timestamp'), |
| 1139 |
# 5 |
| 1140 |
(["char(3)", "integer"], "text"), |
| 1141 |
(["double precision", "char(3)"], "text"), |
| 1142 |
(["integer[3]", "bigint"], "bigint[]"), |
| 1143 |
(["integer", "smallint", "double precision[]"], "double precision[]"), |
| 1144 |
(["integer[][]", "smallint", "double precision[]"], "double precision[]"), |
| 1145 |
# 10 |
| 1146 |
# I would give you the next is plain wrong, but I'm relying on postgres |
| 1147 |
# to reject such nonsence in the first place. |
| 1148 |
(["double precision[340]", "char(3)"], "text"), |
| 1149 |
(["boolean", "boolean"], "boolean"), |
| 1150 |
(["boolean", "smallint"], "smallint"), |
| 1151 |
(["sbox", "spoint"], "text"), |
| 1152 |
(["sbox", "spoly"], "spoly"), |
| 1153 |
(["sbox", "whacko"], "raw"), |
| 1154 |
] |
| 1155 |
|
| 1156 |
|
| 1157 |
class ColumnTest(testhelpers.VerboseTest): |
| 1158 |
def setUp(self): |
| 1159 |
testhelpers.VerboseTest.setUp(self) |
| 1160 |
self.fieldInfoGetter = _getFieldInfoGetter() |
| 1161 |
self.grammar = adql.getGrammar() |
| 1162 |
|
| 1163 |
def _getColSeqAndCtx(self, query): |
| 1164 |
t = self.grammar.parseString(query)[0] |
| 1165 |
ctx = adql.annotate(t, self.fieldInfoGetter) |
| 1166 |
return t.fieldInfos.seq, ctx |
| 1167 |
|
| 1168 |
def _getColSeq(self, query): |
| 1169 |
return self._getColSeqAndCtx(query)[0] |
| 1170 |
|
| 1171 |
def _assertColumns(self, resultColumns, assertProperties): |
| 1172 |
self.assertEqual(len(resultColumns), len(assertProperties)) |
| 1173 |
for index, ((name, col), (type, unit, ucd, taint)) in enumerate(zip( |
| 1174 |
resultColumns, assertProperties)): |
| 1175 |
if type is not None: |
| 1176 |
self.assertEqual(col.type, type, "Type %d: %r != %r"% |
| 1177 |
(index, col.type, type)) |
| 1178 |
if unit is not None: |
| 1179 |
self.assertEqual(col.unit, unit, "Unit %d: %r != %r"% |
| 1180 |
(index, col.unit, unit)) |
| 1181 |
if ucd is not None: |
| 1182 |
self.assertEqual(col.ucd, ucd, "UCD %d: %r != %r"% |
| 1183 |
(index, col.ucd, ucd)) |
| 1184 |
if taint is not None: |
| 1185 |
self.assertEqual(col.tainted, taint, "Taint %d: should be %s"% |
| 1186 |
(index, taint)) |
| 1187 |
|
| 1188 |
|
| 1189 |
class SelectClauseTest(ColumnTest): |
| 1190 |
def testConstantSelect(self): |
| 1191 |
cols = self._getColSeq("select 1, 'const' from spatial") |
| 1192 |
self._assertColumns(cols, [ |
| 1193 |
("smallint", "", "", False), |
| 1194 |
("text", "", "", False),]) |
| 1195 |
|
| 1196 |
def testConstantExprSelect(self): |
| 1197 |
cols = self._getColSeq("select 1+0.1, 'const'||'ab' from spatial") |
| 1198 |
self._assertColumns(cols, [ |
| 1199 |
("double precision", "", "", True), |
| 1200 |
("text", "", "", True),]) |
| 1201 |
|
| 1202 |
def testConstantSelectWithAs(self): |
| 1203 |
cols = self._getColSeq("select 1+0.1 as x from spatial") |
| 1204 |
self._assertColumns(cols, [ |
| 1205 |
("double precision", "", "", True),]) |
| 1206 |
|
| 1207 |
def testSimpleColumn(self): |
| 1208 |
cols = self._getColSeq("select mass from misc") |
| 1209 |
self._assertColumns(cols, [ |
| 1210 |
("real", "kg", "phys.mass", False),]) |
| 1211 |
|
| 1212 |
def testBadRefRaises(self): |
| 1213 |
self.assertRaises(adql.ColumnNotFound, self._getColSeq, |
| 1214 |
"select x, foo.* from spatial, misc") |
| 1215 |
|
| 1216 |
def testQualifiedStarSingle(self): |
| 1217 |
cols = self._getColSeq("select misc.* from misc") |
| 1218 |
self._assertColumns(cols, [ |
| 1219 |
("real", "kg", "phys.mass", False), |
| 1220 |
("real", "mag", "phot.mag", False), |
| 1221 |
("real", "km/s", "phys.veloc", False),]) |
| 1222 |
|
| 1223 |
def testQualifiedStar(self): |
| 1224 |
cols = self._getColSeq("select misc.* from spatial, misc") |
| 1225 |
self._assertColumns(cols, [ |
| 1226 |
("real", "kg", "phys.mass", False), |
| 1227 |
("real", "mag", "phot.mag", False), |
| 1228 |
("real", "km/s", "phys.veloc", False),]) |
| 1229 |
|
| 1230 |
def testMixedQualifiedStar(self): |
| 1231 |
cols = self._getColSeq("select misc.*, dist, round(mass/10)" |
| 1232 |
" from spatial, misc") |
| 1233 |
self._assertColumns(cols, [ |
| 1234 |
("real", "kg", "phys.mass", False), |
| 1235 |
("real", "mag", "phot.mag", False), |
| 1236 |
("real", "km/s", "phys.veloc", False), |
| 1237 |
("real", "m", "phys.distance", False), |
| 1238 |
("double precision", "kg", "phys.mass", True),]) |
| 1239 |
|
| 1240 |
def testAliasedStar(self): |
| 1241 |
cols = self._getColSeq("select misc.* from spatial join misc as foo" |
| 1242 |
" on (spatial.dist=foo.mass)") |
| 1243 |
self.assertEqual(len(cols), 3) |
| 1244 |
|
| 1245 |
def testFancyRounding(self): |
| 1246 |
cols = self._getColSeq("select round(dist, 2) from spatial") |
| 1247 |
self._assertColumns(cols, [ |
| 1248 |
("double precision", "m", "phys.distance", True)]) |
| 1249 |
|
| 1250 |
|
| 1251 |
class ColResTest(ColumnTest): |
| 1252 |
"""tests for resolution of output columns from various expressions. |
| 1253 |
""" |
| 1254 |
def testSimpleSelect(self): |
| 1255 |
cols = self._getColSeq("select width, height from spatial") |
| 1256 |
self.assertEqual(cols[0][0], 'width') |
| 1257 |
self.assertEqual(cols[1][0], 'height') |
| 1258 |
wInfo = cols[0][1] |
| 1259 |
self.assertEqual(wInfo.unit, "m") |
| 1260 |
self.assertEqual(wInfo.ucd, "phys.dim") |
| 1261 |
self.assertTrue(wInfo.userData[0] is spatialFields[1]) |
| 1262 |
|
| 1263 |
def testNULL(self): |
| 1264 |
cols = self._getColSeq("select NULL from spatial") |
| 1265 |
self._assertColumns(cols, [ |
| 1266 |
(None, "", "", False)]) |
| 1267 |
|
| 1268 |
def testIgnoreCase(self): |
| 1269 |
cols = self._getColSeq("select Width, hEiGHT from spatial") |
| 1270 |
self._assertColumns(cols, [ |
| 1271 |
("real", "m", "phys.dim", False), |
| 1272 |
("real", "km", "phys.dim", False),]) |
| 1273 |
|
| 1274 |
def testStarSelect(self): |
| 1275 |
cols = self._getColSeq("select * from spatial") |
| 1276 |
self._assertColumns(cols, [ |
| 1277 |
("real", "m", "phys.distance", False), |
| 1278 |
("real", "m", "phys.dim", False), |
| 1279 |
("real", "km", "phys.dim", False), |
| 1280 |
("real", "deg", "pos.eq.ra", False), |
| 1281 |
("real", "rad", "pos.eq.ra", False), ]) |
| 1282 |
|
| 1283 |
def testStarSelectJoined(self): |
| 1284 |
cols = self._getColSeq("select * from spatial, misc") |
| 1285 |
self._assertColumns(cols, [ |
| 1286 |
("real", "m", "phys.distance", False), |
| 1287 |
("real", "m", "phys.dim", False), |
| 1288 |
("real", "km", "phys.dim", False), |
| 1289 |
("real", "deg", "pos.eq.ra", False), |
| 1290 |
("real", "rad", "pos.eq.ra", False), |
| 1291 |
("real", "kg", "phys.mass", False), |
| 1292 |
("real", "mag", "phot.mag", False), |
| 1293 |
("real", "km/s", "phys.veloc", False)]) |
| 1294 |
|
| 1295 |
def testDimlessSelect(self): |
| 1296 |
cols = self._getColSeq("select 3+4 from spatial") |
| 1297 |
self.assertEqual(cols[0][1].type, "smallint") |
| 1298 |
self.assertEqual(cols[0][1].unit, "") |
| 1299 |
self.assertEqual(cols[0][1].ucd, "") |
| 1300 |
|
| 1301 |
def testSimpleScalarExpression(self): |
| 1302 |
cols = self._getColSeq("select 2+width, 2*height, height*2" |
| 1303 |
" from spatial") |
| 1304 |
self._assertColumns(cols, [ |
| 1305 |
("real", "m", "", True), |
| 1306 |
("real", "km", "phys.dim", True), |
| 1307 |
("real", "km", "phys.dim", True),]) |
| 1308 |
self.assertTrue(cols[1][1].userData[0] is spatialFields[2]) |
| 1309 |
|
| 1310 |
def testFieldOperandExpression(self): |
| 1311 |
cols = self._getColSeq("select width*height, width/speed, " |
| 1312 |
"3*mag*height, mag+height, height+height from spatial, misc") |
| 1313 |
self._assertColumns(cols, [ |
| 1314 |
("real", "m.km", "", True), |
| 1315 |
("real", "m/(km/s)", "", True), |
| 1316 |
("real", "mag.km", "", True), |
| 1317 |
("real", "", "", True), |
| 1318 |
("real", "km", "phys.dim", True)]) |
| 1319 |
|
| 1320 |
def testMiscOperands(self): |
| 1321 |
cols = self._getColSeq("select -3*mag from misc") |
| 1322 |
self._assertColumns(cols, [ |
| 1323 |
("real", "mag", "phot.mag", True)]) |
| 1324 |
|
| 1325 |
def testSetFunctions(self): |
| 1326 |
cols = self._getColSeq("select AVG(mag), mAx(mag), max(2*mag)," |
| 1327 |
" Min(Mag), sum(mag), count(mag), avg(3), count(*) from misc") |
| 1328 |
self._assertColumns(cols, [ |
| 1329 |
("double precision", "mag", "phot.mag;stat.mean", False), |
| 1330 |
("real", "mag", "stat.max;phot.mag", False), |
| 1331 |
("real", "mag", "stat.max;phot.mag", True), |
| 1332 |
("real", "mag", "stat.min;phot.mag", False), |
| 1333 |
("real", "mag", "phot.mag", False), |
| 1334 |
("integer", "", "meta.number;phot.mag", False), |
| 1335 |
("double precision", "", None, False), |
| 1336 |
("integer", "", "meta.number", False)]) |
| 1337 |
|
| 1338 |
def testNumericFunctions(self): |
| 1339 |
cols = self._getColSeq("select acos(ra2), degrees(ra2), RadianS(ra1)," |
| 1340 |
" PI(), ABS(width), Ceiling(Width), Truncate(height*2)" |
| 1341 |
" from spatial") |
| 1342 |
self._assertColumns(cols, [ |
| 1343 |
("double precision", "rad", "", True), |
| 1344 |
("double precision", "deg", "pos.eq.ra", True), |
| 1345 |
("double precision", "rad", "pos.eq.ra", True), |
| 1346 |
("double precision", "", "", True), |
| 1347 |
("double precision", "m", "phys.dim", True), |
| 1348 |
("double precision", "m", "phys.dim", True), |
| 1349 |
("double precision", "km", "phys.dim", True)]) |
| 1350 |
|
| 1351 |
def testAggFunctions(self): |
| 1352 |
cols = self._getColSeq("select max(ra1), min(ra1) from spatial") |
| 1353 |
self._assertColumns(cols, [ |
| 1354 |
("real", "deg", "stat.max;pos.eq.ra", False), |
| 1355 |
("real", "deg", "stat.min;pos.eq.ra", False)]) |
| 1356 |
|
| 1357 |
def testPoint(self): |
| 1358 |
cols = self._getColSeq("select point('ICRS', ra1, ra2) from spatial") |
| 1359 |
self._assertColumns(cols, [ |
| 1360 |
("spoint", '', '', False)]) |
| 1361 |
self.assertTrue(cols[0][1].userData[0] is spatialFields[3]) |
| 1362 |
|
| 1363 |
def testDistance(self): |
| 1364 |
cols = self._getColSeq("select distance(point('galactic', 2, 3)," |
| 1365 |
" point('ICRS', ra1, ra2)) from spatial") |
| 1366 |
self._assertColumns(cols, [ |
| 1367 |
("double precision", 'deg', 'pos.angDistance', False)]) |
| 1368 |
|
| 1369 |
def testCentroid(self): |
| 1370 |
cols = self._getColSeq("select centroid(circle('galactic', ra1, ra2, 0.5))" |
| 1371 |
" from spatial") |
| 1372 |
self._assertColumns(cols, [ |
| 1373 |
("spoint", '', '', False)]) |
| 1374 |
|
| 1375 |
def testArea(self): |
| 1376 |
cols = self._getColSeq("select area(circle(ra1, ra2, 0.2))" |
| 1377 |
" from spatial") |
| 1378 |
self._assertColumns(cols, [ |
| 1379 |
("double precision", 'deg**2', 'phys.angSize', False)]) |
| 1380 |
|
| 1381 |
def testParenExprs(self): |
| 1382 |
cols = self._getColSeq("select (width+width)*height from spatial") |
| 1383 |
self._assertColumns(cols, [ |
| 1384 |
("real", "m.km", "", True)]) |
| 1385 |
|
| 1386 |
def testSubquery(self): |
| 1387 |
cols = self._getColSeq("select q.p from (select ra2 as p from" |
| 1388 |
" spatial) as q") |
| 1389 |
self._assertColumns(cols, [ |
| 1390 |
("real", 'rad', 'pos.eq.ra', False)]) |
| 1391 |
|
| 1392 |
def testSubqueryStar(self): |
| 1393 |
cols = self._getColSeq("select p, speed, q.*" |
| 1394 |
" from (select speed, mag as p from misc) as q") |
| 1395 |
self._assertColumns(cols, [ |
| 1396 |
("real", "mag", "phot.mag", False), |
| 1397 |
("real", "km/s", "phys.veloc", False), |
| 1398 |
("real", "km/s", "phys.veloc", False), |
| 1399 |
("real", "mag", "phot.mag", False)]) |
| 1400 |
|
| 1401 |
def testJoin(self): |
| 1402 |
cols = self._getColSeq("select dist, speed, 2*mass*height" |
| 1403 |
" from spatial join misc on (mass>height)") |
| 1404 |
self._assertColumns(cols, [ |
| 1405 |
("real", 'm', 'phys.distance', False), |
| 1406 |
("real", 'km/s', 'phys.veloc', False), |
| 1407 |
("real", 'kg.km', '', True),]) |
| 1408 |
|
| 1409 |
def testWhereResolutionPlain(self): |
| 1410 |
cols = self._getColSeq("select dist from spatial where exists" |
| 1411 |
" (select * from misc where dist=misc.mass)") |
| 1412 |
self._assertColumns(cols, [ |
| 1413 |
("real", 'm', 'phys.distance', False)]) |
| 1414 |
|
| 1415 |
def testWhereResolutionWithAlias(self): |
| 1416 |
cols = self._getColSeq("select dist from spatial as q where exists" |
| 1417 |
" (select * from misc where q.dist=misc.mass)") |
| 1418 |
self._assertColumns(cols, [ |
| 1419 |
("real", 'm', 'phys.distance', False)]) |
| 1420 |
|
| 1421 |
def testErrorReporting(self): |
| 1422 |
self.assertRaises(adql.ColumnNotFound, self._getColSeq, |
| 1423 |
"select gnurks from spatial") |
| 1424 |
|
| 1425 |
def testExpressionWithUnicode(self): |
| 1426 |
cols = self._getColSeq("select crazy.name||geo.pt from crazy, geo") |
| 1427 |
self._assertColumns(cols, [ |
| 1428 |
("unicode", '', '', True)]) |
| 1429 |
|
| 1430 |
def testIdenticalNames(self): |
| 1431 |
cols = self._getColSeq("SELECT u.ra1 FROM spatial AS mine" |
| 1432 |
" LEFT OUTER JOIN spatial2 as u" |
| 1433 |
" ON (1=CONTAINS(POINT('', mine.ra1, mine.ra2)," |
| 1434 |
" CIRCLE('', u.ra1, u.dec, 1)))") |
| 1435 |
self._assertColumns(cols, [ |
| 1436 |
("real", 'deg', 'pos.eq.ra;meta.main', False)]) |
| 1437 |
|
| 1438 |
def testAliasedColumn(self): |
| 1439 |
cols = self._getColSeq("SELECT foo, ra1 FROM (" |
| 1440 |
"SELECT ra1 as foO, ra1 FROM spatial) as q") |
| 1441 |
self._assertColumns(cols, [ |
| 1442 |
("real", 'deg', 'pos.eq.ra', False), |
| 1443 |
("real", 'deg', 'pos.eq.ra', False)]) |
| 1444 |
|
| 1445 |
def testCoalesce(self): |
| 1446 |
cols = self._getColSeq("SELECT COALESCE(ra1, pt, '') as foo FROM" |
| 1447 |
" spatial, geo") |
| 1448 |
self._assertColumns(cols, [ |
| 1449 |
("real", 'deg', 'pos.eq.ra', True)]) |
| 1450 |
|
| 1451 |
def testCaseWithCol(self): |
| 1452 |
cols = self._getColSeq("SELECT CASE ra1 WHEN 3 Then dist" |
| 1453 |
" when 3 then height END as q FROM" |
| 1454 |
" spatial") |
| 1455 |
self._assertColumns(cols, [ |
| 1456 |
("real", 'm', 'phys.distance', True)]) |
| 1457 |
|
| 1458 |
def testCaseWithColExpr(self): |
| 1459 |
cols = self._getColSeq("SELECT CASE ra1 WHEN 2 THEN ra1*14 WHEN 3" |
| 1460 |
" Then dist else height END as q FROM" |
| 1461 |
" spatial") |
| 1462 |
self._assertColumns(cols, [ |
| 1463 |
("real", 'deg', 'pos.eq.ra', True)]) |
| 1464 |
|
| 1465 |
def testCaseElse(self): |
| 1466 |
cols = self._getColSeq("SELECT CASE ra1 WHEN 2 THEN 14 WHEN 3" |
| 1467 |
" Then 18 else height END as q FROM" |
| 1468 |
" spatial") |
| 1469 |
self._assertColumns(cols, [ |
| 1470 |
("real", 'km', 'phys.dim', True)]) |
| 1471 |
|
| 1472 |
def testNestedCase(self): |
| 1473 |
cols = self._getColSeq("SELECT CASE ra1 WHEN 2 THEN" |
| 1474 |
" case when dist/width<1 THEN dist ELSE width END WHEN 3" |
| 1475 |
" Then 18 else height END as q FROM spatial") |
| 1476 |
self._assertColumns(cols, [ |
| 1477 |
("real", 'm', 'phys.distance', True)]) |
| 1478 |
|
| 1479 |
def testOnlyLiteralCases(self): |
| 1480 |
cols = self._getColSeq("SELECT CASE WHEN ra1<2 THEN" |
| 1481 |
" 'knall' ELSE 'fall' END as q FROM spatial") |
| 1482 |
self._assertColumns(cols, [ |
| 1483 |
("text", '', '', True)]) |
| 1484 |
|
| 1485 |
def testNULLLiteralInCase(self): |
| 1486 |
cols = self._getColSeq("SELECT CASE WHEN ra1<2 THEN" |
| 1487 |
" NULL ELSE 'fall' END as q FROM spatial") |
| 1488 |
self._assertColumns(cols, [ |
| 1489 |
(None, '', '', True)]) |
| 1490 |
|
| 1491 |
|
| 1492 |
class ExprColTest(ColumnTest): |
| 1493 |
def testCharConcat(self): |
| 1494 |
cols = self._getColSeq("select flag||'ab' as cat from crazy") |
| 1495 |
self._assertColumns(cols, [ |
| 1496 |
("text", '', "", True),]) |
| 1497 |
|
| 1498 |
def testTextConcat(self): |
| 1499 |
cols = self._getColSeq("select version||'ab' as cat from crazy") |
| 1500 |
self._assertColumns(cols, [ |
| 1501 |
("text", '', "", True),]) |
| 1502 |
|
| 1503 |
def testUnicodeConcat(self): |
| 1504 |
cols = self._getColSeq("select name||'ab' as cat from crazy") |
| 1505 |
self._assertColumns(cols, [ |
| 1506 |
("unicode", '', "", True),]) |
| 1507 |
|
| 1508 |
def testUCDColSimple(self): |
| 1509 |
cols = self._getColSeq("select UCDCOL('phys.mass') from misc") |
| 1510 |
self._assertColumns(cols, [ |
| 1511 |
("real", "kg", "phys.mass", False)]) |
| 1512 |
|
| 1513 |
def testUCDColPattern(self): |
| 1514 |
cols = self._getColSeq("select UCDCOL('phys.mass'), UCDCOL('phys.dist*')" |
| 1515 |
" from misc join spatial on (dist=mass)") |
| 1516 |
self._assertColumns(cols, [ |
| 1517 |
("real", "kg", "phys.mass", False), |
| 1518 |
("real", "m", "phys.distance", False) |
| 1519 |
]) |
| 1520 |
|
| 1521 |
def testUCDColFails(self): |
| 1522 |
self.assertRaisesWithMsg(base.NotFoundError, |
| 1523 |
"column matching ucd 'phys.mass' could not be located in from clause", |
| 1524 |
self._getColSeq, |
| 1525 |
("select UCDCOL('phys.mass') from spatial",)) |
| 1526 |
|
| 1527 |
def testInUnit(self): |
| 1528 |
cols = self._getColSeq("select IN_UNIT(height, 'm') from spatial") |
| 1529 |
self._assertColumns(cols, [ |
| 1530 |
("real", "m", "phys.dim", False),]) |
| 1531 |
|
| 1532 |
def testInUnitFailsIncompatibleUnit(self): |
| 1533 |
self.assertRaisesWithMsg(adql.Error, |
| 1534 |
"in_unit error: km and rad do not have the same SI base", |
| 1535 |
self._getColSeq, |
| 1536 |
("select IN_UNIT(height, 'rad') from spatial",)) |
| 1537 |
|
| 1538 |
def testInUnitFailsBogusUnit(self): |
| 1539 |
self.assertRaisesWithMsg(adql.Error, |
| 1540 |
"Bad unit passed to in_unit: 'krach schlagen' at col. 7", |
| 1541 |
self._getColSeq, |
| 1542 |
("select IN_UNIT(height, 'krach schlagen') from spatial",)) |
| 1543 |
|
| 1544 |
def testAggregateUDF(self): |
| 1545 |
cols = self._getColSeq("select gavo_histogram(mass, 0, 100, 10) as h" |
| 1546 |
" from misc") |
| 1547 |
self._assertColumns(cols, [ |
| 1548 |
("integer[]", "", "stat.histogram;phys.mass", False)]) |
| 1549 |
|
| 1550 |
def testArrayElement(self): |
| 1551 |
cols = self._getColSeq("select vals[5] as h" |
| 1552 |
" from crazy") |
| 1553 |
self._assertColumns(cols, [ |
| 1554 |
("real", "yr", "some.value", True)]) |
| 1555 |
|
| 1556 |
def testNonArraySubscript(self): |
| 1557 |
self.assertRaisesWithMsg(adql.Error, |
| 1558 |
"Cannot subscript a non-array in width [ 0 ]", |
| 1559 |
self._getColSeq, |
| 1560 |
("select width[0] from spatial",)) |
| 1561 |
|
| 1562 |
def testNoNumberSubscript(self): |
| 1563 |
self.assertRaisesWithMsg(base.ParseException, |
| 1564 |
'Expected FROM, found \'[\' (at char 8), (line:1, col:9)', |
| 1565 |
self._getColSeq, |
| 1566 |
("select 5[0] from spatial",)) |
| 1567 |
|
| 1568 |
def testCountFunction(self): |
| 1569 |
cols = self._getColSeq("select count(pt) from geo") |
| 1570 |
self._assertColumns(cols, [ |
| 1571 |
("integer", "", "meta.number", False)]) |
| 1572 |
|
| 1573 |
|
| 1574 |
class DelimitedColResTest(ColumnTest): |
| 1575 |
"""tests for column resolution with delimited identifiers. |
| 1576 |
""" |
| 1577 |
def testCaseSensitive(self): |
| 1578 |
self.assertRaises(adql.ColumnNotFound, self._getColSeq, |
| 1579 |
'select "Inch""ing" from quoted') |
| 1580 |
|
| 1581 |
def testMixedCase(self): |
| 1582 |
cols = self._getColSeq('select "plAin" from quoted') |
| 1583 |
self.assertEqual(cols[0][0], utils.QuotedName("plAin")) |
| 1584 |
|
| 1585 |
def testNoFoldToRegular(self): |
| 1586 |
self.assertRaises(adql.ColumnNotFound, self._getColSeq, |
| 1587 |
'select plain from quoted') |
| 1588 |
|
| 1589 |
def testDelimitedMatchesRegular(self): |
| 1590 |
cols = self._getColSeq('select "mass" from misc') |
| 1591 |
self.assertEqual(cols[0][0], "mass") |
| 1592 |
|
| 1593 |
def testConstantSelectWithAs(self): |
| 1594 |
cols = self._getColSeq('select 1+0.1 as "x" from spatial') |
| 1595 |
self.assertEqual(cols[0][0], "x") |
| 1596 |
|
| 1597 |
def testRegularMatchesDelmitied(self): |
| 1598 |
cols = self._getColSeq('select alllower from quoted') |
| 1599 |
self.assertEqual(cols[0][0], "alllower") |
| 1600 |
|
| 1601 |
def testSimpleStar(self): |
| 1602 |
cols = self._getColSeq("select * from quoted") |
| 1603 |
self._assertColumns(cols, [ |
| 1604 |
("real", 'bg', "mess", False), |
| 1605 |
("real", 'fin', "imperial.mess", False), |
| 1606 |
("real", 'pc', "boring.stuff", False), |
| 1607 |
("real", 'km', "simple.case", False),]) |
| 1608 |
|
| 1609 |
def testSimpleJoin(self): |
| 1610 |
cols = self._getColSeq('select "inch""ing", "mass" from misc join' |
| 1611 |
' quoted on ("left-right"=speed)') |
| 1612 |
self._assertColumns(cols, [ |
| 1613 |
("real", 'fin', "imperial.mess", False), |
| 1614 |
("real", 'kg', 'phys.mass', False)]) |
| 1615 |
|
| 1616 |
def testPlainAndSubselect(self): |
| 1617 |
cols = self._getColSeq('select "inch""ing", alllower from (' |
| 1618 |
'select TOP 5 * from quoted where alllower<"inch""ing") as q') |
| 1619 |
self._assertColumns(cols, [ |
| 1620 |
("real", 'fin', "imperial.mess", False), |
| 1621 |
("real", 'km', "simple.case", False),]) |
| 1622 |
|
| 1623 |
def testQuotedExpressions(self): |
| 1624 |
cols = self._getColSeq('select 4*alllower*"inch""ing" from quoted') |
| 1625 |
self._assertColumns(cols, [ |
| 1626 |
("real", 'km.fin', None, True)]) |
| 1627 |
|
| 1628 |
def testReferencingRegulars(self): |
| 1629 |
cols = self._getColSeq('select "ra1" from spatial') |
| 1630 |
self._assertColumns(cols, [ |
| 1631 |
("real", 'deg', "pos.eq.ra", False)]) |
| 1632 |
|
| 1633 |
|
| 1634 |
class JoinColResTest(ColumnTest): |
| 1635 |
def testJoin(self): |
| 1636 |
cols = self._getColSeq("select dist, speed, 2*mass*height" |
| 1637 |
" from spatial join misc on (mass>height)") |
| 1638 |
self._assertColumns(cols, [ |
| 1639 |
("real", 'm', 'phys.distance', False), |
| 1640 |
("real", 'km/s', 'phys.veloc', False), |
| 1641 |
("real", 'kg.km', '', True),]) |
| 1642 |
|
| 1643 |
def testJoinStar(self): |
| 1644 |
cols = self._getColSeq("select * from spatial as q join misc as p on" |
| 1645 |
" (1=contains(point('ICRS', q.dist, q.width), circle('ICRS'," |
| 1646 |
" p.mass, p.mag, 0.02)))") |
| 1647 |
self._assertColumns(cols, [ |
| 1648 |
("real", 'm', 'phys.distance', False), |
| 1649 |
("real", 'm', 'phys.dim', False), |
| 1650 |
("real", 'km', 'phys.dim', False), |
| 1651 |
("real", 'deg', 'pos.eq.ra', False), |
| 1652 |
("real", 'rad', 'pos.eq.ra', False), |
| 1653 |
("real", 'kg', 'phys.mass', False), |
| 1654 |
("real", 'mag', 'phot.mag', False), |
| 1655 |
("real", 'km/s', 'phys.veloc', False), |
| 1656 |
]) |
| 1657 |
|
| 1658 |
def testSubqueryJoin(self): |
| 1659 |
cols = self._getColSeq("SELECT * FROM (" |
| 1660 |
"SELECT ALL q.mass, spatial.ra1 FROM (" |
| 1661 |
" SELECT TOP 100 mass, mag FROM misc" |
| 1662 |
" WHERE speed BETWEEN 0 AND 1) AS q JOIN" |
| 1663 |
" spatial ON (mass=width)) AS f") |
| 1664 |
self._assertColumns(cols, [ |
| 1665 |
("real", 'kg', 'phys.mass', False), |
| 1666 |
("real", 'deg', 'pos.eq.ra', False)]) |
| 1667 |
|
| 1668 |
def testAutoJoin(self): |
| 1669 |
cols = self._getColSeq("SELECT * FROM misc JOIN" |
| 1670 |
" (SELECT TOP 3 * FROM crazy) AS q ON (mag=q.ct)") |
| 1671 |
physMass = cols[0] |
| 1672 |
self.assertEqual(physMass[0], "mass") |
| 1673 |
self.assertEqual(physMass[1].ucd, "phys.mass") |
| 1674 |
crazyMass = cols[6] |
| 1675 |
self.assertEqual(crazyMass[0], "mass") |
| 1676 |
self.assertEqual(crazyMass[1].ucd, "event;using.incense") |
| 1677 |
|
| 1678 |
def testSelfUsingJoin(self): |
| 1679 |
cols = self._getColSeq("SELECT * FROM " |
| 1680 |
" misc JOIN misc AS u USING (mass)") |
| 1681 |
self._assertColumns(cols, [ |
| 1682 |
("real", 'kg', 'phys.mass', False), |
| 1683 |
("real", 'mag', 'phot.mag', False), |
| 1684 |
("real", 'km/s', 'phys.veloc', False), |
| 1685 |
("real", 'mag', 'phot.mag', False), |
| 1686 |
("real", 'km/s', 'phys.veloc', False) ]) |
| 1687 |
|
| 1688 |
def testExReferenceBad(self): |
| 1689 |
self.assertRaises(adql.TableNotFound, self._getColSeq, |
| 1690 |
"select foo.dist from spatial join misc on (mass>height)") |
| 1691 |
|
| 1692 |
def testExReference(self): |
| 1693 |
cols = self._getColSeq("select a.dist, b.dist" |
| 1694 |
" from spatial as a join spatial as b on (a.dist>b.dist)") |
| 1695 |
self._assertColumns(cols, [ |
| 1696 |
("real", 'm', 'phys.distance', False), |
| 1697 |
("real", 'm', 'phys.distance', False)]) |
| 1698 |
|
| 1699 |
def testExReferenceMixed(self): |
| 1700 |
cols = self._getColSeq("select spatial.dist, b.speed" |
| 1701 |
" from spatial as a join misc as b on (a.dist>b.speed)") |
| 1702 |
self._assertColumns(cols, [ |
| 1703 |
("real", 'm', 'phys.distance', False), |
| 1704 |
("real", 'km/s', 'phys.veloc', False)]) |
| 1705 |
|
| 1706 |
def testNaturalJoin(self): |
| 1707 |
cols = self._getColSeq("SELECT * FROM" |
| 1708 |
" spatial JOIN spatial2 WHERE dist<2") |
| 1709 |
self._assertColumns(cols, [ |
| 1710 |
("real", "m", "phys.distance", False), |
| 1711 |
("real", "m", "phys.dim", False), |
| 1712 |
("real", "km", "phys.dim", False), |
| 1713 |
("real", "deg", "pos.eq.ra", False), |
| 1714 |
("real", "rad", "pos.eq.ra", False), |
| 1715 |
("real", "deg", "pos.eq.dec;meta.main", False), |
| 1716 |
("real", "h", "time.epoch", False)]) |
| 1717 |
|
| 1718 |
def testNaturalJoinSubquery(self): |
| 1719 |
cols = self._getColSeq("SELECT dist, width FROM" |
| 1720 |
" spatial JOIN spatial2 WHERE dist IN (SELECT spatial2.dist FROM spatial2)") |
| 1721 |
self._assertColumns(cols, [ |
| 1722 |
("real", "m", "phys.distance", False), |
| 1723 |
("real", "m", "phys.dim", False)]) |
| 1724 |
|
| 1725 |
def testUsingJoin1(self): |
| 1726 |
cols = self._getColSeq("SELECT * FROM" |
| 1727 |
" spatial JOIN spatial2 USING (ra1)") |
| 1728 |
self._assertColumns(cols, [ |
| 1729 |
("real", "m", "phys.distance", False), |
| 1730 |
("real", "m", "phys.dim", False), |
| 1731 |
("real", "km", "phys.dim", False), |
| 1732 |
("real", "deg", "pos.eq.ra", False), |
| 1733 |
("real", "rad", "pos.eq.ra", False), |
| 1734 |
("real", "deg", "pos.eq.dec;meta.main", False), |
| 1735 |
("real", "m", "phys.distance", False), |
| 1736 |
("real", "h", "time.epoch", False)]) |
| 1737 |
|
| 1738 |
def testUsingJoin2(self): |
| 1739 |
cols = self._getColSeq("SELECT * FROM" |
| 1740 |
" spatial JOIN spatial2 USING (ra1, dist)") |
| 1741 |
self._assertColumns(cols, [ |
| 1742 |
("real", "m", "phys.distance", False), |
| 1743 |
("real", "m", "phys.dim", False), |
| 1744 |
("real", "km", "phys.dim", False), |
| 1745 |
("real", "deg", "pos.eq.ra", False), |
| 1746 |
("real", "rad", "pos.eq.ra", False), |
| 1747 |
("real", "deg", "pos.eq.dec;meta.main", False), |
| 1748 |
("real", "h", "time.epoch", False)]) |
| 1749 |
|
| 1750 |
def testUsingJoin3(self): |
| 1751 |
cols = self._getColSeq("SELECT ra1, dec, mass FROM" |
| 1752 |
" spatial JOIN spatial2 USING (ra1, dist) JOIN misc ON (dist=mass)") |
| 1753 |
self._assertColumns(cols, [ |
| 1754 |
("real", "deg", "pos.eq.ra", False), |
| 1755 |
("real", "deg", "pos.eq.dec;meta.main", False), |
| 1756 |
("real", "kg", "phys.mass", False),]) |
| 1757 |
|
| 1758 |
def testUsingJoin4(self): |
| 1759 |
cols = self._getColSeq("SELECT ra1, dec, mass FROM" |
| 1760 |
" (SELECT * FROM spatial) as q JOIN spatial2" |
| 1761 |
" USING (ra1, dist) JOIN misc ON (dist=mass)") |
| 1762 |
self._assertColumns(cols, [ |
| 1763 |
("real", "deg", "pos.eq.ra", False), |
| 1764 |
("real", "deg", "pos.eq.dec;meta.main", False), |
| 1765 |
("real", "kg", "phys.mass", False),]) |
| 1766 |
|
| 1767 |
def testCommaAll(self): |
| 1768 |
cols = self._getColSeq("SELECT * from spatial, spatial, misc") |
| 1769 |
self.assertEqual([c[1].userData[0].name for c in cols], [ |
| 1770 |
'dist', 'width', 'height', 'ra1', 'ra2', 'dist', 'width', |
| 1771 |
'height', 'ra1', 'ra2', 'mass', 'mag', 'speed']) |
| 1772 |
|
| 1773 |
def testHaving1(self): |
| 1774 |
cols = self._getColSeq( |
| 1775 |
"SELECT ct FROM crazy " |
| 1776 |
"JOIN (" |
| 1777 |
" SELECT height FROM spatial" |
| 1778 |
" JOIN spatial2 ON (ra2=dist)" |
| 1779 |
" GROUP BY height" |
| 1780 |
" HAVING (height>avg(dist))) AS q " |
| 1781 |
"ON (wot=height)") |
| 1782 |
self._assertColumns(cols, [ |
| 1783 |
('integer', '', '', False)]) |
| 1784 |
|
| 1785 |
|
| 1786 |
class SetColResTest(ColumnTest): |
| 1787 |
def testSimple(self): |
| 1788 |
cols = self._getColSeq("select dist, height from spatial" |
| 1789 |
" union select dist, height from spatial") |
| 1790 |
self._assertColumns(cols, [ |
| 1791 |
("real", 'm', 'phys.distance', False), |
| 1792 |
("real", 'km', 'phys.dim', False)]) |
| 1793 |
|
| 1794 |
def testStars(self): |
| 1795 |
cols = self._getColSeq("select 0 as i, misc.* from misc" |
| 1796 |
" union select 1 as i, misc.* from misc") |
| 1797 |
self._assertColumns(cols, [ |
| 1798 |
("smallint", '', '', False), |
| 1799 |
("real", 'kg', 'phys.mass', False), |
| 1800 |
("real", 'mag', 'phot.mag', False), |
| 1801 |
("real", 'km/s', 'phys.veloc', False)]) |
| 1802 |
|
| 1803 |
def testLengthFailure(self): |
| 1804 |
self.assertRaisesWithMsg(adql.IncompatibleTables, |
| 1805 |
"Operands in set operation have differing result tuple lengths.", |
| 1806 |
self._getColSeq, |
| 1807 |
("select dist, width, height from spatial" |
| 1808 |
" union select dist, height from spatial",)) |
| 1809 |
|
| 1810 |
def testName(self): |
| 1811 |
self.assertRaisesWithMsg(adql.IncompatibleTables, |
| 1812 |
"Operands if set operation have differing names. First differing name: width vs. dist", |
| 1813 |
self._getColSeq, |
| 1814 |
("select width, height from spatial" |
| 1815 |
" union select dist, height from spatial",)) |
| 1816 |
|
| 1817 |
def testAliasing(self): |
| 1818 |
cols = self._getColSeq("select dist, height from spatial" |
| 1819 |
" union select dist, ra1 as height from spatial2" |
| 1820 |
" intersect select mass as dist, mag as height from misc" |
| 1821 |
' except select "left-right" as dist, "plAin" as height from quoted') |
| 1822 |
self._assertColumns(cols, [ |
| 1823 |
("real", '', '', False), |
| 1824 |
("real", '', '', False)]) |
| 1825 |
|
| 1826 |
def testNested(self): |
| 1827 |
cols = self._getColSeq("select dist, height from spatial" |
| 1828 |
" union select ra1 as dist, dec as height from (" |
| 1829 |
" select ra1, dec, dist from spatial2" |
| 1830 |
" except select mag as ra1, mass as dec, speed as dist from misc) as q" |
| 1831 |
" where dist>2") |
| 1832 |
self._assertColumns(cols, [ |
| 1833 |
("real", '', '', False), |
| 1834 |
("real", '', '', False)]) |
| 1835 |
|
| 1836 |
def testSetGeneratingFunction(self): |
| 1837 |
cols = self._getColSeq("select * from generate_series(1, 4)") |
| 1838 |
self._assertColumns(cols, [ |
| 1839 |
('integer', None, None, False)]) |
| 1840 |
self.assertEqual(cols[0][0], "generate_series") |
| 1841 |
|
| 1842 |
def testSetGeneratingFunctionAlias(self): |
| 1843 |
cols = self._getColSeq("select * from generate_series(1, 4) as q") |
| 1844 |
self._assertColumns(cols, [ |
| 1845 |
('integer', None, None, False)]) |
| 1846 |
self.assertEqual(cols[0][0], "q") |
| 1847 |
|
| 1848 |
def testSetGeneratingFunctionJoin(self): |
| 1849 |
cols = self._getColSeq("select mass, q from generate_series(1, 4) as q" |
| 1850 |
" join misc on (q=speed)") |
| 1851 |
self._assertColumns(cols, [ |
| 1852 |
('real', 'kg', 'phys.mass', False), |
| 1853 |
('integer', None, None, False)]) |
| 1854 |
self.assertEqual(cols[1][0], "q") |
| 1855 |
|
| 1856 |
|
| 1857 |
class CastColResTest(ColumnTest): |
| 1858 |
def testSimple(self): |
| 1859 |
cols = self._getColSeq("select dist," |
| 1860 |
" cast(dist as char(10)) as d_str," |
| 1861 |
" cast(dist as CHAR) as d_chr," |
| 1862 |
" cast(dist as natIonal char(13)) as d_uni," |
| 1863 |
" cast(dist as national char) as d_uni," |
| 1864 |
" cast(dist as integer) as d_int," |
| 1865 |
" cast(dist as bigint) as d_long," |
| 1866 |
" cast(ra1 as smallint) as ra_short," |
| 1867 |
" cast(dist as real) as d_float," |
| 1868 |
" cast(dist as double precision) as d_double," |
| 1869 |
" cast(dist as timestamp) as d_ts," |
| 1870 |
" cast(NULL as bigint) as n_long," |
| 1871 |
" cast(2 as smallint) as lit_int," |
| 1872 |
" cast(2 as varchar(*)) as varchar_lit" |
| 1873 |
" from spatial") |
| 1874 |
self._assertColumns(cols, [ |
| 1875 |
("real", 'm', 'phys.distance', False), |
| 1876 |
("text", 'm', 'phys.distance', True), |
| 1877 |
("char", 'm', 'phys.distance', True), |
| 1878 |
("unicode", 'm', 'phys.distance', True), |
| 1879 |
("unicode", 'm', 'phys.distance', True), |
| 1880 |
("integer", 'm', 'phys.distance', True), |
| 1881 |
("bigint", 'm', 'phys.distance', True), |
| 1882 |
("smallint", 'deg', 'pos.eq.ra', True), |
| 1883 |
("real", 'm', 'phys.distance', True), |
| 1884 |
("double precision", 'm', 'phys.distance', True), |
| 1885 |
("timestamp", 'm', 'phys.distance', True), |
| 1886 |
("bigint", '', '', True), |
| 1887 |
("smallint", '', '', True), |
| 1888 |
("text", '', '', True), |
| 1889 |
]) |
| 1890 |
|
| 1891 |
def testPoint(self): |
| 1892 |
cols = self._getColSeq("SELECT CAST('23 24' AS POINT)," |
| 1893 |
"CAST(coverage AS CIRCLE)," |
| 1894 |
"CAST('12 23' || '23 24' || '24 25' as polygon)" |
| 1895 |
" from geo") |
| 1896 |
self._assertColumns(cols, [ |
| 1897 |
("spoint", '', '', False), |
| 1898 |
("scircle", '', '', False), |
| 1899 |
("spoly", '', '', False),]) |
| 1900 |
|
| 1901 |
|
| 1902 |
class WithColResTest(ColumnTest): |
| 1903 |
def testSimple(self): |
| 1904 |
cols = self._getColSeq("with hollow as (select * from spatial)" |
| 1905 |
" select dist, ra2 from hollow") |
| 1906 |
self._assertColumns(cols, [ |
| 1907 |
("real", "m", "phys.distance", False), |
| 1908 |
("real", "rad", "pos.eq.ra", False),]) |
| 1909 |
|
| 1910 |
def testWithSetOperations(self): |
| 1911 |
cols = self._getColSeq("with hollow as" |
| 1912 |
" (select * from spatial where dist>5" |
| 1913 |
" union select * from spatial where ra1<3)" |
| 1914 |
" select dist, ra2 from hollow") |
| 1915 |
self._assertColumns(cols, [ |
| 1916 |
("real", "m", "phys.distance", False), |
| 1917 |
("real", "rad", "pos.eq.ra", False),]) |
| 1918 |
|
| 1919 |
def testMultipleWith(self): |
| 1920 |
cols = self._getColSeq("with hollow as (select dist, ra2 from spatial)," |
| 1921 |
" filled as (select mass as dist, mag from misc)" |
| 1922 |
" select ra2, mag from hollow natural join filled") |
| 1923 |
self._assertColumns(cols, [ |
| 1924 |
("real", "rad", "pos.eq.ra", False), |
| 1925 |
("real", "mag", "phot.mag", False)]) |
| 1926 |
|
| 1927 |
|
| 1928 |
class UnitColResTest(ColumnTest): |
| 1929 |
def testPlainLiteral(self): |
| 1930 |
cols = self._getColSeq("select 4.5e-9{kpc/cyr} from misc") |
| 1931 |
self._assertColumns(cols, [ |
| 1932 |
("double precision", "kpc/cyr", None, False),]) |
| 1933 |
|
| 1934 |
def testLiteralInExpression(self): |
| 1935 |
cols = self._getColSeq("select ra1*3600{arcsec/deg} from spatial") |
| 1936 |
self._assertColumns(cols, [ |
| 1937 |
# TODO: should we normalise this? |
| 1938 |
# TODO: this probably should not be tainted (but what's the |
| 1939 |
# limit? How would we recognise true non-dimensional |
| 1940 |
# factors if we say it's ok to multiply with quantities? |
| 1941 |
("real", "deg.arcsec/deg", None, True),]) |
| 1942 |
|
| 1943 |
def testComprehensibleBadUnitMessage(self): |
| 1944 |
self.assertRaisesWithMsg(adql.ParseSyntaxException, |
| 1945 |
"Cannot parse unit: 'kpc/cyr.t' at col. 8, found" |
| 1946 |
" '{' (at char 13), (line:1, col:14)", |
| 1947 |
self._getColSeq, |
| 1948 |
("select 4.5e-9{kpc/cyr.t} from misc",)) |
| 1949 |
|
| 1950 |
def testComprehensibleBadTypeMessage(self): |
| 1951 |
self.assertRaisesWithMsg(adql.ParseException, |
| 1952 |
# If we could come up with a hack that made this "strings can't have |
| 1953 |
# units" or somesuch that'd be great. |
| 1954 |
"Expected FROM, found '{' (at char 15), (line:1, col:16)", |
| 1955 |
self._getColSeq, |
| 1956 |
("select '4.5e-9'{kpc/cyr.t} from misc",)) |
| 1957 |
|
| 1958 |
def testComprehensibleLiteralUnitMessage(self): |
| 1959 |
self.assertRaisesWithMsg(adql.Error, |
| 1960 |
"You cannot unit-coerce literals", |
| 1961 |
self._getColSeq, |
| 1962 |
("select 4.5@{km} from misc",)) |
| 1963 |
|
| 1964 |
def testCoercions(self): |
| 1965 |
cols = self._getColSeq("select dist@{pc}, (width*height)@{AU**2}" |
| 1966 |
" FROM spatial") |
| 1967 |
self._assertColumns(cols, [ |
| 1968 |
("real", "pc", "phys.distance", False), |
| 1969 |
("real", "AU**2", "", True),]) |
| 1970 |
|
| 1971 |
|
| 1972 |
class _UploadTDWithOID(testhelpers.TestResource): |
| 1973 |
def make(self, ignored): |
| 1974 |
from gavo import votable |
| 1975 |
from gavo.formats import votableread |
| 1976 |
from io import StringIO |
| 1977 |
|
| 1978 |
rows =next(votable.parse(StringIO( |
| 1979 |
"""<VOTABLE><RESOURCE><TABLE> |
| 1980 |
<FIELD name="oid" datatype="float"/> |
| 1981 |
<DATA><TABLEDATA><TR><TD>1</TD></TR></TABLEDATA></DATA> |
| 1982 |
</TABLE></RESOURCE></VOTABLE>"""))) |
| 1983 |
return votableread.makeTableDefForVOTable( |
| 1984 |
"foo", rows.tableDefinition, votableread.AutoQuotedNameMaker()) |
| 1985 |
|
| 1986 |
_uploadTDWithOID = _UploadTDWithOID() |
| 1987 |
|
| 1988 |
|
| 1989 |
class UploadColResTest(ColumnTest): |
| 1990 |
resources = [("nastyTD", _uploadTDWithOID)] |
| 1991 |
|
| 1992 |
def setUp(self): |
| 1993 |
ColumnTest.setUp(self) |
| 1994 |
self.fieldInfoGetter = adqlglue.DaCHSFieldInfoGetter(tdsForUploads=[ |
| 1995 |
testhelpers.getTestTable("adql")]) |
| 1996 |
|
| 1997 |
def testNormalResolution(self): |
| 1998 |
cols = self._getColSeq("select alpha, rv from TAP_UPLOAD.adql") |
| 1999 |
self._assertColumns(cols, [ |
| 2000 |
("real", 'deg', 'pos.eq.ra;meta.main', False), |
| 2001 |
("double precision", 'km/s', 'phys.veloc;pos.heliocentric', False),]) |
| 2002 |
|
| 2003 |
def testFailedResolutionCol(self): |
| 2004 |
self.assertRaises(base.NotFoundError, self._getColSeq, |
| 2005 |
'select alp, rv from TAP_UPLOAD.adql') |
| 2006 |
|
| 2007 |
def testFailedResolutionTable(self): |
| 2008 |
self.assertRaises(base.NotFoundError, self._getColSeq, |
| 2009 |
'select alpha, rv from TAP_UPLOAD.junk') |
| 2010 |
|
| 2011 |
def testPGForbiddenNames(self): |
| 2012 |
self.fieldInfoGetter = adqlglue.DaCHSFieldInfoGetter( |
| 2013 |
tdsForUploads=[self.nastyTD]) |
| 2014 |
cols = self._getColSeq( |
| 2015 |
"select q.*, q.oid from (select oid from tap_upload.foo) as q") |
| 2016 |
self.assertEqual(cols[0][0], "oid_") |
| 2017 |
self.assertEqual(cols[1][0], "oid_") |
| 2018 |
|
| 2019 |
|
| 2020 |
class STCTest(ColumnTest): |
| 2021 |
"""tests for working STC inference in ADQL expressions. |
| 2022 |
""" |
| 2023 |
def testSimple(self): |
| 2024 |
cs = self._getColSeq("select ra1, ra2 from spatial") |
| 2025 |
self.assertEqual(cs[0][1].stc.astroSystem.spaceFrame.refFrame, 'ICRS') |
| 2026 |
self.assertEqual(cs[1][1].stc.astroSystem.spaceFrame.refFrame, 'FK4') |
| 2027 |
|
| 2028 |
def testBroken(self): |
| 2029 |
cs = self._getColSeq("select ra1+ra2 from spatial") |
| 2030 |
self.assertTrue(hasattr(cs[0][1].stc, "broken")) |
| 2031 |
|
| 2032 |
def testOKPoint(self): |
| 2033 |
cs, ctx = self._getColSeqAndCtx( |
| 2034 |
"select point('ICRS', ra1, 2) from spatial") |
| 2035 |
self.assertEqual(cs[0][1].stc.astroSystem.spaceFrame.refFrame, 'ICRS') |
| 2036 |
self.assertEqual(ctx.errors, []) |
| 2037 |
|
| 2038 |
def testEmptyCoosysInherits(self): |
| 2039 |
cs, ctx = self._getColSeqAndCtx( |
| 2040 |
"select point('', ra2, 2) from spatial") |
| 2041 |
self.assertEqual(cs[0][1].stc.astroSystem.spaceFrame.refFrame, 'FK4') |
| 2042 |
self.assertEqual(ctx.errors, []) |
| 2043 |
|
| 2044 |
def testEmptyCoosysBecomesNone(self): |
| 2045 |
cs, ctx = self._getColSeqAndCtx( |
| 2046 |
"select point('', mag, 2) from misc") |
| 2047 |
self.assertEqual(cs[0][1].stc.astroSystem.spaceFrame.refFrame, None) |
| 2048 |
self.assertEqual(ctx.errors, []) |
| 2049 |
|
| 2050 |
def testMissingCoosysBecomesNone(self): |
| 2051 |
cs, ctx = self._getColSeqAndCtx( |
| 2052 |
"select point('', mag, 2) from misc") |
| 2053 |
self.assertEqual(cs[0][1].stc.astroSystem.spaceFrame.refFrame, None) |
| 2054 |
self.assertEqual(ctx.errors, []) |
| 2055 |
|
| 2056 |
def testNULLCoosysInherits(self): |
| 2057 |
cs, ctx = self._getColSeqAndCtx( |
| 2058 |
"select point(NULL, ra1, 2) from spatial") |
| 2059 |
self.assertEqual(cs[0][1].stc.astroSystem.spaceFrame.refFrame, 'ICRS') |
| 2060 |
self.assertEqual(ctx.errors, []) |
| 2061 |
|
| 2062 |
def testMissingCoosysInherits(self): |
| 2063 |
cs, ctx = self._getColSeqAndCtx( |
| 2064 |
"select point(ra2, 2) from spatial") |
| 2065 |
self.assertEqual(cs[0][1].stc.astroSystem.spaceFrame.refFrame, 'FK4') |
| 2066 |
self.assertEqual(ctx.errors, []) |
| 2067 |
|
| 2068 |
def testMissingCoosysInheritsCircle(self): |
| 2069 |
cs, ctx = self._getColSeqAndCtx( |
| 2070 |
"select circle(ra2, dist, 2) from spatial") |
| 2071 |
self.assertEqual(cs[0][1].stc.astroSystem.spaceFrame.refFrame, 'FK4') |
| 2072 |
self.assertEqual(ctx.errors, []) |
| 2073 |
|
| 2074 |
def testPointBadCoo(self): |
| 2075 |
cs, ctx = self._getColSeqAndCtx( |
| 2076 |
"select point('ICRS', ra2, 2) from spatial") |
| 2077 |
self.assertEqual(cs[0][1].stc.astroSystem.spaceFrame.refFrame, 'ICRS') |
| 2078 |
self.assertEqual(ctx.errors, ['When constructing point:' |
| 2079 |
' Argument 1 has incompatible STC']) |
| 2080 |
|
| 2081 |
def testPointFunctionsSelect(self): |
| 2082 |
cs, ctx = self._getColSeqAndCtx( |
| 2083 |
"select coordsys(p), coord1(p), coord2(p) from" |
| 2084 |
" (select point('FK5', ra1, width) as p from spatial) as q") |
| 2085 |
self._assertColumns(cs, [ |
| 2086 |
("text", '', 'meta.ref;pos.frame', False), |
| 2087 |
("double precision", 'deg', None, False), |
| 2088 |
("double precision", 'deg', None, False)]) |
| 2089 |
|
| 2090 |
def testBadSTCSRegion(self): |
| 2091 |
self.assertRaisesWithMsg(adql.RegionError, |
| 2092 |
"Invalid argument to REGION: 'Time TT'.", |
| 2093 |
self._getColSeqAndCtx, ( |
| 2094 |
"select * from spatial where 1=intersects(" |
| 2095 |
"region('Time TT'), circle('icrs', 1, 1, 0.1))",)) |
| 2096 |
|
| 2097 |
def testRegionExpressionRaises(self): |
| 2098 |
self.assertRaisesWithMsg(adql.RegionError, |
| 2099 |
"Invalid argument to REGION: ''Position' || alphaName || deltaName'.", |
| 2100 |
self._getColSeqAndCtx, ( |
| 2101 |
"select * from spatial where 1=intersects(" |
| 2102 |
"region('Position' || alphaName || deltaName)," |
| 2103 |
" circle('icrs', 1, 1, 0.1))",)) |
| 2104 |
|
| 2105 |
def testSTCSRegion(self): |
| 2106 |
cs, ctx = self._getColSeqAndCtx( |
| 2107 |
"select region('Circle FK4 10 10 1')" |
| 2108 |
" from spatial") |
| 2109 |
self.assertEqual(cs[0][1].unit, "deg") |
| 2110 |
|
| 2111 |
def testPolygonInheritsGeo(self): |
| 2112 |
cs, ctx = self._getColSeqAndCtx( |
| 2113 |
"select polygon(pt, point(1, 2), point(3,4))" |
| 2114 |
" from geo") |
| 2115 |
self.assertEqual(cs[0][1].stc.astroSystem.spaceFrame.refFrame, |
| 2116 |
'GALACTIC_II') |
| 2117 |
|
| 2118 |
def testPolygonInheritsSplit(self): |
| 2119 |
cs, ctx = self._getColSeqAndCtx( |
| 2120 |
"select polygon(ra2, dist, ra1, height, 2, 3)" |
| 2121 |
" from spatial") |
| 2122 |
self.assertEqual(cs[0][1].stc.astroSystem.spaceFrame.refFrame, |
| 2123 |
'FK4') |
| 2124 |
|
| 2125 |
def timestampMetaInference(self): |
| 2126 |
cs, ctx = self._getColSeqAndCtx( |
| 2127 |
"select timestamp('2017-12-01'), TIMESTAMP(dt)" |
| 2128 |
" from geo") |
| 2129 |
self.assertEqual(cs[0][1].ucd, '') |
| 2130 |
self.assertEqual(cs[0][1].unit, '') |
| 2131 |
self.assertEqual(cs[0][1].type, 'timestamp') |
| 2132 |
self.assertEqual(cs[0][1].stc, None) |
| 2133 |
self.assertEqual(cs[1][1].ucd, 'time;obs') |
| 2134 |
self.assertEqual(cs[1][1].type, 'timestamp') |
| 2135 |
self.assertEqual(cs[1][1].stc.astroSystem.timeFrame.timeScale, "TT") |
| 2136 |
|
| 2137 |
|
| 2138 |
class FunctionNodeTest(unittest.TestCase): |
| 2139 |
"""tests for nodes.FunctionMixin and friends. |
| 2140 |
""" |
| 2141 |
def setUp(self): |
| 2142 |
self.grammar = adql.getGrammar() |
| 2143 |
|
| 2144 |
def testPlainArgparse(self): |
| 2145 |
t = self.grammar.parseString("select POINT('ICRS', width,height)" |
| 2146 |
" from spatial")[0] |
| 2147 |
p = t.selectList.selectFields[0].expr |
| 2148 |
self.assertEqual(p.cooSys, "ICRS") |
| 2149 |
self.assertEqual(nodes.flatten(p.x), "width") |
| 2150 |
self.assertEqual(nodes.flatten(p.y), "height") |
| 2151 |
|
| 2152 |
def testExprArgparse(self): |
| 2153 |
t = self.grammar.parseString("select POINT('ICRS', " |
| 2154 |
"5*width+height*LOG(width),height)" |
| 2155 |
" from spatial")[0] |
| 2156 |
p = t.selectList.selectFields[0].expr |
| 2157 |
self.assertEqual(p.cooSys, "ICRS") |
| 2158 |
self.assertEqual(nodes.flatten(p.x), "5 * width + height * LOG(width)") |
| 2159 |
self.assertEqual(nodes.flatten(p.y), "height") |
| 2160 |
|
| 2161 |
|
| 2162 |
class ComplexExpressionTest(unittest.TestCase): |
| 2163 |
"""quite random tests for correct processing of complex-ish search expressions. |
| 2164 |
""" |
| 2165 |
def testOne(self): |
| 2166 |
t = adql.getGrammar().parseString("select top 5 * from" |
| 2167 |
" lsw.plates where dateobs between 'J2416642 ' and 'J2416643'")[0] |
| 2168 |
self.assertEqual(t.whereClause.children[1].name, "dateobs") |
| 2169 |
self.assertEqual(adql.flatten(t.whereClause.children[-1]), "'J2416643'") |
| 2170 |
|
| 2171 |
|
| 2172 |
class NameSuggestingTest(testhelpers.VerboseTest, |
| 2173 |
metaclass=testhelpers.SamplesBasedAutoTest): |
| 2174 |
def _runTest(self, sample): |
| 2175 |
query, name = sample |
| 2176 |
t = adql.getGrammar().parseString(query)[0] |
| 2177 |
self.assertEqual(t.suggestAName(), name) |
| 2178 |
|
| 2179 |
samples = [ |
| 2180 |
("select * from plaintable", "plaintable"), |
| 2181 |
('select * from "plaintable"', "_plaintable"), |
| 2182 |
('select * from "useless & table"" name"', "_uselesstablename"), |
| 2183 |
('select * from "3columns"', "_3columns"), |
| 2184 |
('select * from t1 join t2', "t1_t2"), |
| 2185 |
# 5 |
| 2186 |
('select * from (select * from gnug) as booger', "booger"), |
| 2187 |
('select * from (select * from gnug) as booger join boog', |
| 2188 |
"booger_boog"),] |
| 2189 |
|
| 2190 |
|
| 2191 |
class _FlatteningTest(testhelpers.VerboseTest): |
| 2192 |
def _assertFlattensTo(self, rawADQL, flattenedADQL): |
| 2193 |
tree = adql.parseToTree(rawADQL) |
| 2194 |
self.assertEqual(adql.flatten(tree), |
| 2195 |
flattenedADQL) |
| 2196 |
|
| 2197 |
|
| 2198 |
class MiscFlatteningTest(_FlatteningTest): |
| 2199 |
"""tests for flattening of plain ADQL trees. |
| 2200 |
""" |
| 2201 |
def testCircle(self): |
| 2202 |
self._assertFlattensTo("select alphaFloat, deltaFloat from ppmx.data" |
| 2203 |
" where contains(point('ICRS', alphaFloat, deltaFloat), " |
| 2204 |
" circle('ICRS', 23, 24, 0.2))=1", |
| 2205 |
"SELECT alphaFloat, deltaFloat FROM ppmx.data WHERE" |
| 2206 |
" CONTAINS(POINT(alphaFloat, deltaFloat)," |
| 2207 |
" CIRCLE(ICRS,23,24,0.2)) = 1") |
| 2208 |
|
| 2209 |
def testFunctions(self): |
| 2210 |
self._assertFlattensTo( |
| 2211 |
"select round(x,2)as a, truncate(x,-2) as b from foo", |
| 2212 |
"SELECT ROUND(x, 2) AS a, TRUNCATE(x, - 2) AS b FROM foo") |
| 2213 |
|
| 2214 |
def testJoin(self): |
| 2215 |
self._assertFlattensTo( |
| 2216 |
"SELECT ra1, dec, mass FROM\n" |
| 2217 |
" (SELECT * FROM spatial) as q LEFT OUTER JOIN spatial2\n" |
| 2218 |
" USING (ra1, dist) JOIN misc ON (dist=mass)", |
| 2219 |
"SELECT ra1, dec, mass FROM (SELECT * FROM spatial) AS q" |
| 2220 |
" LEFT OUTER JOIN spatial2 USING ( ra1 , dist ) JOIN misc" |
| 2221 |
" ON ( dist = mass )") |
| 2222 |
|
| 2223 |
def testCommaJoin(self): |
| 2224 |
self._assertFlattensTo( |
| 2225 |
"SELECT ra1, dec, mass FROM\n spatial, spatial2, misc", |
| 2226 |
"SELECT ra1, dec, mass FROM spatial , spatial2 , misc") |
| 2227 |
|
| 2228 |
def testSubJoin(self): |
| 2229 |
self._assertFlattensTo( |
| 2230 |
"SELECT ra1, dec, mass FROM\n" |
| 2231 |
" (spatial join spatial2 using (ra1)), misc", |
| 2232 |
"SELECT ra1, dec, mass FROM" |
| 2233 |
" (spatial JOIN spatial2 USING ( ra1 )) , misc") |
| 2234 |
|
| 2235 |
def testConcat(self): |
| 2236 |
self._assertFlattensTo( |
| 2237 |
"select 'ivo://' || name || '%' as pat from crazy", |
| 2238 |
"SELECT 'ivo://' || name || '%' AS pat FROM crazy") |
| 2239 |
|
| 2240 |
def testAliasExpr(self): |
| 2241 |
self._assertFlattensTo( |
| 2242 |
"select a+b/(8+x) as num from crazy", |
| 2243 |
"SELECT a + b / ( 8 + x ) AS num FROM crazy") |
| 2244 |
|
| 2245 |
|
| 2246 |
class CommentTest(_FlatteningTest): |
| 2247 |
def testTopComment(self): |
| 2248 |
self._assertFlattensTo("-- opening remarks;\n" |
| 2249 |
"-- quite a few of them, actually.\nselect * from foo", |
| 2250 |
"SELECT * FROM foo") |
| 2251 |
|
| 2252 |
def testEmbeddedComments(self): |
| 2253 |
self._assertFlattensTo("select -- comment\n" |
| 2254 |
"bar, --comment\n" |
| 2255 |
"quux --comment\n" |
| 2256 |
"from -- comment\n" |
| 2257 |
"foo --comment", |
| 2258 |
"SELECT bar, quux FROM foo") |
| 2259 |
|
| 2260 |
def testStringJoining(self): |
| 2261 |
self._assertFlattensTo("select * from bar where a='qua' -- cmt\n'tsch'", |
| 2262 |
"SELECT * FROM bar WHERE a = 'quatsch'") |
| 2263 |
|
| 2264 |
def testLeadingWhitespaceCleanup(self): |
| 2265 |
self._assertFlattensTo("select * from--comment\n bar", |
| 2266 |
"SELECT * FROM bar") |
| 2267 |
|
| 2268 |
def testEquivalentToWhitespace(self): |
| 2269 |
self._assertFlattensTo("select * from--comment\nbar", |
| 2270 |
"SELECT * FROM bar") |
| 2271 |
|
| 2272 |
|
| 2273 |
class _MorphTestWithTestTables(testhelpers.VerboseTest): |
| 2274 |
def _parseAnnotating(self, query): |
| 2275 |
return adql.parseAnnotating(query, _getFieldInfoGetter())[1] |
| 2276 |
|
| 2277 |
|
| 2278 |
class SpatialMorphTest(_MorphTestWithTestTables): |
| 2279 |
# These are tests exercising mainly the ugly optimisation hacks in nodes.py |
| 2280 |
# (_sortLargeFirst and friends). They are mainly built on the _largeTable |
| 2281 |
# (spatial2) and _smallTable (spatial) annotations introduced in the field |
| 2282 |
# definitions above. |
| 2283 |
def setUp(self): |
| 2284 |
self.grammar = adql.getGrammar() |
| 2285 |
|
| 2286 |
def testCircleIn(self): |
| 2287 |
s, t = morphpg.morphPG( |
| 2288 |
self._parseAnnotating("select ra1, ra2 from spatial" |
| 2289 |
" where contains(point('ICRS', ra1, ra2), " |
| 2290 |
" circle('ICRS', 23, 24, 0.2))=1")) |
| 2291 |
self.assertEqual(adql.flatten(t), |
| 2292 |
"SELECT ra1, ra2 FROM spatial WHERE" |
| 2293 |
" q3c_join(23, 24, ra1, ra2, 0.2)") |
| 2294 |
|
| 2295 |
def testCircleOut(self): |
| 2296 |
s, t = morphpg.morphPG( |
| 2297 |
self._parseAnnotating("select ra1, ra2 from spatial" |
| 2298 |
" where 0=contains(point('ICRS', ra1, ra2)," |
| 2299 |
" circle('ICRS', 23, 24, 0.2))")) |
| 2300 |
self.assertEqual(adql.flatten(t), |
| 2301 |
"SELECT ra1, ra2 FROM spatial WHERE" |
| 2302 |
" NOT ( q3c_join(23, 24, ra1, ra2, 0.2) )") |
| 2303 |
|
| 2304 |
def testConstantsFirstPoint(self): |
| 2305 |
s, t = morphpg.morphPG( |
| 2306 |
self._parseAnnotating("select ra1 from spatial" |
| 2307 |
" where 0=contains(point('ICRS', 23, 24)," |
| 2308 |
" circle('ICRS', ra1, ra2, 0.2))")) |
| 2309 |
self.assertEqual(adql.flatten(t), |
| 2310 |
"SELECT ra1 FROM spatial WHERE" |
| 2311 |
" NOT ( q3c_join(23, 24, ra1, ra2, 0.2) )") |
| 2312 |
|
| 2313 |
def testConstantsFirstCircle(self): |
| 2314 |
s, t = morphpg.morphPG( |
| 2315 |
self._parseAnnotating("select ra1 from spatial" |
| 2316 |
" where 0=contains(point('ICRS', ra1, ra2)," |
| 2317 |
" circle('ICRS', 23, 24, 0.2))")) |
| 2318 |
self.assertEqual(adql.flatten(t), |
| 2319 |
"SELECT ra1 FROM spatial WHERE" |
| 2320 |
" NOT ( q3c_join(23, 24, ra1, ra2, 0.2) )") |
| 2321 |
|
| 2322 |
def testConstantsFirstDistanceDirect(self): |
| 2323 |
s, t = morphpg.morphPG( |
| 2324 |
self._parseAnnotating("select ra1 from spatial" |
| 2325 |
" where distance(23, 24, ra1, ra2)<0.2")) |
| 2326 |
self.assertEqual(adql.flatten(t), |
| 2327 |
"SELECT ra1 FROM spatial WHERE" |
| 2328 |
" q3c_join(23, 24, ra1, ra2, 0.2)") |
| 2329 |
|
| 2330 |
def testConstantsFirstDistanceSwap(self): |
| 2331 |
s, t = morphpg.morphPG( |
| 2332 |
self._parseAnnotating("select ra1 from spatial" |
| 2333 |
" where distance(ra1, ra2, 23, 24)<0.2")) |
| 2334 |
self.assertEqual(adql.flatten(t), |
| 2335 |
"SELECT ra1 FROM spatial WHERE" |
| 2336 |
" q3c_join(23, 24, ra1, ra2, 0.2)") |
| 2337 |
|
| 2338 |
def testCircleAnnotated(self): |
| 2339 |
s, t = morphpg.morphPG( |
| 2340 |
self._parseAnnotating("SELECT TOP 10 * FROM spatial" |
| 2341 |
" WHERE 1=CONTAINS(POINT('ICRS', ra1, ra2)," |
| 2342 |
" CIRCLE('ICRS', 10, 10, 0.5))")) |
| 2343 |
self.assertEqual(adql.flatten(t), |
| 2344 |
"SELECT spatial.dist, spatial.width, spatial.height, spatial.ra1, spatial.ra2 FROM spatial WHERE q3c_join(10, 10, ra1, ra2, 0.5) LIMIT 10") |
| 2345 |
|
| 2346 |
def testMogrifiedIntersect(self): |
| 2347 |
s, t = morphpg.morphPG( |
| 2348 |
self._parseAnnotating("SELECT TOP 10 * FROM spatial" |
| 2349 |
" WHERE 1=INTERSECTS(CIRCLE('ICRS', 10, 10, 0.5)," |
| 2350 |
"POINT('ICRS', ra1, ra2))")) |
| 2351 |
self.assertEqual(adql.flatten(t), |
| 2352 |
"SELECT spatial.dist, spatial.width, spatial.height, spatial.ra1, spatial.ra2 FROM spatial WHERE q3c_join(10, 10, ra1, ra2, 0.5) LIMIT 10") |
| 2353 |
|
| 2354 |
def testDistanceTranslatedCrossmatch(self): |
| 2355 |
s, t = morphpg.morphPG( |
| 2356 |
self._parseAnnotating("select ra1 from spatial as a join spatial as b" |
| 2357 |
" where distance(a.ra1, a.ra2, b.ra1, b.ra2)<0.001")) |
| 2358 |
morphed = adql.flatten(t) |
| 2359 |
self.assertEqual(morphed, |
| 2360 |
"SELECT ra1 FROM spatial AS a JOIN spatial AS b" |
| 2361 |
" WHERE q3c_join(a.ra1, a.ra2, b.ra1, b.ra2, 0.001)") |
| 2362 |
|
| 2363 |
def testOp2DistanceTranslatedCrossmatch(self): |
| 2364 |
s, t = morphpg.morphPG( |
| 2365 |
self._parseAnnotating("select ra1 from spatial as a join spatial as b" |
| 2366 |
" where 0.001 > distance(a.ra1, a.ra2, b.ra1, b.ra2)")) |
| 2367 |
morphed = adql.flatten(t) |
| 2368 |
self.assertEqual(morphed, |
| 2369 |
"SELECT ra1 FROM spatial AS a JOIN spatial AS b" |
| 2370 |
" WHERE q3c_join(a.ra1, a.ra2, b.ra1, b.ra2, 0.001)") |
| 2371 |
|
| 2372 |
def testDistanceTranslatedInvertedCrossmatch(self): |
| 2373 |
s, t = morphpg.morphPG( |
| 2374 |
self._parseAnnotating("select * from spatial as a join spatial as b" |
| 2375 |
" where distance(a.ra1, a.ra2, b.ra1, b.ra2)>=0.001")) |
| 2376 |
morphed = adql.flatten(t) |
| 2377 |
self.assertEqual(morphed, "SELECT dist, width, height, ra1, ra2" |
| 2378 |
" FROM spatial AS a JOIN spatial AS b WHERE" |
| 2379 |
" NOT q3c_join(a.ra1, a.ra2, b.ra1, b.ra2, 0.001)") |
| 2380 |
|
| 2381 |
def testDistanceTranslatedSelect(self): |
| 2382 |
s, t = morphpg.morphPG( |
| 2383 |
self._parseAnnotating( |
| 2384 |
"select distance(ra1, ra2*2, ra2, dist) AS d from spatial")) |
| 2385 |
self.assertEqual(adql.flatten(t), |
| 2386 |
"SELECT DEGREES((spoint(RADIANS(ra1), RADIANS(ra2 * 2))) <-> (spoint(RADIANS(ra2), RADIANS(dist)))) AS d FROM spatial") |
| 2387 |
|
| 2388 |
def testDistanceTranslatedPGS(self): |
| 2389 |
s, t = morphpg.morphPG( |
| 2390 |
self._parseAnnotating( |
| 2391 |
"select distance(ra1, dec*2, ra1, dist) AS d from spatial2")) |
| 2392 |
self.assertEqual(adql.flatten(t), |
| 2393 |
"SELECT DEGREES((spoint(RADIANS(ra1), RADIANS(dist))) <->" |
| 2394 |
" (spoint(RADIANS(ra1), RADIANS(dec * 2)))) AS d FROM spatial2") |
| 2395 |
|
| 2396 |
def testDistanceOptimisedOnTablesize(self): |
| 2397 |
# spatial2 is the larger table here and hence needs to be in the |
| 2398 |
# second argument. |
| 2399 |
s, t = morphpg.morphPG( |
| 2400 |
self._parseAnnotating("select ra1 from spatial as a join spatial2" |
| 2401 |
" as b where distance(a.ra1, a.ra2, b.ra1, b.dec)<0.001")) |
| 2402 |
morphed = adql.flatten(t) |
| 2403 |
self.assertEqual(morphed, "SELECT ra1" |
| 2404 |
" FROM spatial AS a JOIN spatial2 AS b WHERE" |
| 2405 |
" q3c_join(a.ra1, a.ra2, b.ra1, b.dec, 0.001)") |
| 2406 |
|
| 2407 |
def testDistanceOptimisedOnTablesizeSwap(self): |
| 2408 |
# spatial2 is the larger table here and hence needs to be in the |
| 2409 |
# second argument. |
| 2410 |
s, t = morphpg.morphPG( |
| 2411 |
self._parseAnnotating("select ra1 from spatial as a join spatial2" |
| 2412 |
" as b where distance(b.ra1, b.dec, a.ra1, a.ra2)<0.001")) |
| 2413 |
morphed = adql.flatten(t) |
| 2414 |
self.assertEqual(morphed, "SELECT ra1" |
| 2415 |
" FROM spatial AS a JOIN spatial2 AS b WHERE" |
| 2416 |
" q3c_join(a.ra1, a.ra2, b.ra1, b.dec, 0.001)") |
| 2417 |
|
| 2418 |
def testDistanceOptimisedWithCTE(self): |
| 2419 |
# I sort CTEs into the first position no matter what, since they never |
| 2420 |
# have q3c indexes. |
| 2421 |
s, t = morphpg.morphPG( |
| 2422 |
self._parseAnnotating("with sample as (select ra1, dec from spatial2)" |
| 2423 |
" select ra1 from spatial as a join sample" |
| 2424 |
" as b where distance(b.ra1, b.dec, a.ra1, a.ra2)<0.001")) |
| 2425 |
morphed = adql.flatten(t) |
| 2426 |
self.assertEqual(morphed, "WITH sample AS MATERIALIZED" |
| 2427 |
" ( SELECT ra1, dec FROM spatial2 )" |
| 2428 |
" SELECT ra1 FROM spatial AS a JOIN sample AS b WHERE" |
| 2429 |
" q3c_join(b.ra1, b.dec, a.ra1, a.ra2, 0.001)") |
| 2430 |
|
| 2431 |
|
| 2432 |
class PQMorphTest(testhelpers.VerboseTest): |
| 2433 |
"""tests for morphing to non-geometry ADQL syntax to postgres. |
| 2434 |
""" |
| 2435 |
resources = [("nastyTD", _uploadTDWithOID)] |
| 2436 |
|
| 2437 |
def _testMorph(self, stIn, stOut, fieldInfoGetter=None): |
| 2438 |
tree = adql.parseToTree(stIn) |
| 2439 |
if fieldInfoGetter: |
| 2440 |
_ = adql.annotate(tree, fieldInfoGetter) |
| 2441 |
status, t = adql.morphPG(tree) |
| 2442 |
flattened = nodes.flatten(t) |
| 2443 |
self.assertEqualIgnoringAliases(flattened, stOut) |
| 2444 |
|
| 2445 |
def testSyntax(self): |
| 2446 |
self._testMorph("select distinct top 10 x, y from foo offset 3", |
| 2447 |
'SELECT DISTINCT x, y FROM foo LIMIT 10 OFFSET 3') |
| 2448 |
|
| 2449 |
def testTOP0(self): |
| 2450 |
self._testMorph("select top 0 * from foo", |
| 2451 |
'SELECT * FROM foo LIMIT 0') |
| 2452 |
|
| 2453 |
def testWhitespace(self): |
| 2454 |
self._testMorph("select\t distinct top\n\r\n 10 x, y from foo", |
| 2455 |
'SELECT DISTINCT x, y FROM foo LIMIT 10') |
| 2456 |
|
| 2457 |
def testGroupby(self): |
| 2458 |
self._testMorph("select count(*), inc from (" |
| 2459 |
" select round(x) as inc from foo) as q group by inc", |
| 2460 |
"SELECT COUNT ( * ) ASWHATEVER, inc FROM" |
| 2461 |
" (SELECT ROUND(x) AS inc FROM foo) AS q" |
| 2462 |
" GROUP BY inc") |
| 2463 |
|
| 2464 |
def testTwoArgRound(self): |
| 2465 |
self._testMorph( |
| 2466 |
"select round(x, 2) as a, truncate(x, -2) as b from foo", |
| 2467 |
'SELECT ROUND((x)*10^(2)) / 10^(2) AS a, TRUNC((x)*' |
| 2468 |
'10^(- 2)) / 10^(- 2) AS b FROM foo') |
| 2469 |
|
| 2470 |
def testExprArgs(self): |
| 2471 |
self._testMorph( |
| 2472 |
"select truncate(round((x*2)+y, 4)) from foo", |
| 2473 |
'SELECT TRUNC(ROUND((( x * 2 ) + y)*10^(4)) / 10^(4)) ASWHATEVER FROM foo') |
| 2474 |
|
| 2475 |
def testPointFunctionWithFieldInfo(self): |
| 2476 |
t = adql.parseToTree("select coordsys(q.p) from " |
| 2477 |
"(select point('ICRS', ra1, ra2) as p from spatial) as q") |
| 2478 |
ctx = adql.annotate(t, _getFieldInfoGetter()) |
| 2479 |
self.assertEqual(ctx.errors[0], |
| 2480 |
'When constructing point: Argument 2 has incompatible STC') |
| 2481 |
status, t = adql.morphPG(t) |
| 2482 |
self.assertEqualIgnoringAliases(nodes.flatten(t), |
| 2483 |
"SELECT 'ICRS' ASWHATEVER FROM (SELECT spoint" |
| 2484 |
"(RADIANS(ra1), RADIANS(ra2)) AS p FROM spatial) AS q") |
| 2485 |
|
| 2486 |
def testStringReplacedNumerics(self): |
| 2487 |
self._testMorph("select square(x+x) from foo", |
| 2488 |
"SELECT (x + x)^2 ASWHATEVER FROM foo") |
| 2489 |
|
| 2490 |
def testNumerics(self): |
| 2491 |
self._testMorph("select log10(x), log(x), rand(), rand(5), " |
| 2492 |
" TRUNCATE(x), TRUNCATE(x,3) from foo", |
| 2493 |
'SELECT LOG(x) ASWHATEVER, LN(x) ASWHATEVER, random() ASWHATEVER,' |
| 2494 |
' random() ASWHATEVER, TRUNC(' |
| 2495 |
'x) ASWHATEVER, TRUNC((x)*10^(3)) / 10^(3) ASWHATEVER FROM foo') |
| 2496 |
|
| 2497 |
def testHarmless(self): |
| 2498 |
self._testMorph("select delta*2, alpha*mag, alpha+delta" |
| 2499 |
" from something where mag<-10", |
| 2500 |
'SELECT delta * 2 ASWHATEVER, alpha * mag ASWHATEVER, alpha + delta ASWHATEVER FROM something' |
| 2501 |
' WHERE mag < - 10') |
| 2502 |
|
| 2503 |
def testUnaryLogic(self): |
| 2504 |
self._testMorph("select x from something where y not in (1,2)", |
| 2505 |
'SELECT x FROM something WHERE y NOT IN ( 1 , 2 )') |
| 2506 |
|
| 2507 |
def testOrder(self): |
| 2508 |
self._testMorph("select top 100 * from spatial where dist>10" |
| 2509 |
" order by dist, height", |
| 2510 |
'SELECT spatial.dist, spatial.width, spatial.height, spatial.ra1, spatial.ra2 FROM spatial WHERE dist > 10 ORDER BY dist , height LIMIT 100', |
| 2511 |
_getFieldInfoGetter()) |
| 2512 |
|
| 2513 |
def testUploadKilled(self): |
| 2514 |
self._testMorph("select * from TAP_UPLOAD.abc", |
| 2515 |
"SELECT * FROM abc") |
| 2516 |
|
| 2517 |
def testAliasedUploadKilled(self): |
| 2518 |
self._testMorph("select * from TAP_UPLOAD.abc as o", |
| 2519 |
"SELECT * FROM abc AS o") |
| 2520 |
|
| 2521 |
def testUploadColRef(self): |
| 2522 |
self._testMorph("select TAP_UPLOAD.abc.c from TAP_UPLOAD.abc", |
| 2523 |
"SELECT abc.c FROM abc") |
| 2524 |
|
| 2525 |
def testUploadColRefInGeom(self): |
| 2526 |
self._testMorph("select POINT('', TAP_UPLOAD.abc.b, TAP_UPLOAD.abc.c)" |
| 2527 |
" from TAP_UPLOAD.abc", |
| 2528 |
"SELECT spoint(RADIANS(abc.b), RADIANS(abc.c)) ASWHATEVER FROM abc") |
| 2529 |
|
| 2530 |
def testUploadColRefInGeomContains(self): |
| 2531 |
self._testMorph("SELECT TAP_UPLOAD.user_table.ra FROM" |
| 2532 |
" TAP_UPLOAD.user_table WHERE (1=CONTAINS(POINT('ICRS'," |
| 2533 |
" usnob.data.raj2000, usnob.data.dej2000), CIRCLE('ICRS'," |
| 2534 |
" TAP_UPLOAD.user_table.ra2000, a.dec2000, 0.016666666666666666)))", |
| 2535 |
"SELECT user_table.ra FROM user_table WHERE (" |
| 2536 |
" ((spoint(RADIANS(usnob.data.raj2000), RADIANS(usnob.data.dej2000)))" |
| 2537 |
" <@ (scircle(spoint(RADIANS(user_table.ra2000), RADIANS(a.dec2000))," |
| 2538 |
" RADIANS(0.016666666666666666)))) )") |
| 2539 |
|
| 2540 |
def testSTCSSingle(self): |
| 2541 |
self._testMorph( |
| 2542 |
"select * from foo where 1=CONTAINS(REGION('Position ICRS 1 2'), x)", |
| 2543 |
"SELECT * FROM foo WHERE" |
| 2544 |
" ((spoint '(0.0174532925,0.0349065850)') <@ (x))") |
| 2545 |
|
| 2546 |
def testSTCSExpr(self): |
| 2547 |
self._testMorph( |
| 2548 |
"select * from foo where 1=CONTAINS(" |
| 2549 |
"REGION('Union ICRS (Position 1 2 Intersection" |
| 2550 |
" (circle 1 2 3 box 1 2 3 4 circle 30 40 2))')," |
| 2551 |
" REGION('circle GALACTIC 1 2 3'))", |
| 2552 |
"SELECT * FROM foo WHERE ((spoint '(0.0174532925,0.0349065850)' <@ ((scircle '< (0.0174532925, 0.0349065850), 0.0523598776 >')+strans(1.346356097441,-1.097319001837,0.574770524729)))) OR (((scircle '< (0.0174532925, 0.0349065850), 0.0523598776 >' <@ ((scircle '< (0.0174532925, 0.0349065850), 0.0523598776 >')+strans(1.346356097441,-1.097319001837,0.574770524729)))) AND ((spoly '{(-0.0087266463,0.0000000000),(-0.0087266463,0.0698131701),(0.0436332313,0.0698131701),(0.0436332313,0.0000000000)}' <@ ((scircle '< (0.0174532925, 0.0349065850), 0.0523598776 >')+strans(1.346356097441,-1.097319001837,0.574770524729)))) AND ((scircle '< (0.5235987756, 0.6981317008), 0.0349065850 >' <@ ((scircle '< (0.0174532925, 0.0349065850), 0.0523598776 >')+strans(1.346356097441,-1.097319001837,0.574770524729)))))") |
| 2553 |
# TODO: Have a long, close look at this |
| 2554 |
|
| 2555 |
def testSTCSNotRegion(self): |
| 2556 |
self._testMorph( |
| 2557 |
"select * from foo where 1=INTERSECTS(REGION('NOT (circle 1 2 3)'), x)", |
| 2558 |
"SELECT * FROM foo WHERE NOT ((scircle '< (0.0174532925, 0.0349065850), 0.0523598776 >' && (x)))") |
| 2559 |
|
| 2560 |
def testIsNotNull(self): |
| 2561 |
self._testMorph( |
| 2562 |
"select * from foo where x is not null", |
| 2563 |
"SELECT * FROM foo WHERE x IS NOT NULL") |
| 2564 |
|
| 2565 |
def testIsNull(self): |
| 2566 |
self._testMorph( |
| 2567 |
"select * from foo where x is null", |
| 2568 |
"SELECT * FROM foo WHERE x IS NULL") |
| 2569 |
|
| 2570 |
def testMultiJoin(self): |
| 2571 |
self._testMorph( |
| 2572 |
"select * from spatial natural join spatial2 join misc on (dist=speed)", |
| 2573 |
"SELECT spatial.dist, spatial.width, spatial.height, spatial.ra1, spatial.ra2, spatial2.ra1, spatial2.dec, spatial2.dist, spatial2.t, misc.mass, misc.mag, misc.speed FROM spatial NATURAL JOIN spatial2 JOIN misc ON ( dist = speed )", |
| 2574 |
_getFieldInfoGetter()) |
| 2575 |
|
| 2576 |
@unittest.skipUnless(testhelpers.hasUDF("IVO_EPOCH_PROP"), "pgsphere too old") |
| 2577 |
def testMoveAndUnit(self): |
| 2578 |
self._testMorph("select ivo_apply_pm(" |
| 2579 |
"in_unit(ra1, 'arcmin'), in_unit(dec, 'deg')," |
| 2580 |
"in_unit(ra1/t, 'mas/s'), in_unit(dec/(t+1), 'uarcsec/min'), 80) as gnack" |
| 2581 |
" from spatial natural join spatial2 where" |
| 2582 |
" 5<distance(point(ra1, dec)," |
| 2583 |
" ivo_apply_pm(ra1, ra2, in_unit(dec/t, 'deg/yr')," |
| 2584 |
" in_unit(ra1/t, 'mas/h'), 30))", |
| 2585 |
"SELECT IVO_APPLY_PM((ra1 * 60), (dec * 1), ((ra1 / t) " |
| 2586 |
"* 999.9999999999999), ((dec / ( t + 1 )) * 60000000), 80) AS gnack" |
| 2587 |
" FROM spatial NATURAL JOIN spatial2 WHERE NOT " |
| 2588 |
" (spoint(RADIANS(ra1), RADIANS(dec))) <@ scircle(" |
| 2589 |
"IVO_APPLY_PM(ra1, ra2, ((dec / t) * 8766), ((ra1 / t) " |
| 2590 |
"* 3600000), 30), RADIANS(5))", |
| 2591 |
_getFieldInfoGetter()) |
| 2592 |
|
| 2593 |
def testQualifiedStar(self): |
| 2594 |
self._testMorph( |
| 2595 |
"select spatial.*, misc.* from spatial natural join spatial2" |
| 2596 |
" join misc on (dist=speed)", |
| 2597 |
"SELECT spatial.dist, spatial.width, spatial.height, spatial.ra1, spatial.ra2, misc.mass, misc.mag, misc.speed FROM spatial NATURAL JOIN spatial2 JOIN misc ON ( dist = speed )", |
| 2598 |
_getFieldInfoGetter()) |
| 2599 |
|
| 2600 |
def testStarWithAlias(self): |
| 2601 |
self._testMorph("select * from spatial as b", |
| 2602 |
"SELECT b.dist, b.width, b.height, b.ra1, b.ra2 FROM spatial AS b", |
| 2603 |
_getFieldInfoGetter()) |
| 2604 |
|
| 2605 |
def testStarWithJoin(self): |
| 2606 |
self._testMorph("select * from spatial join spatial2 on (width=dec)", |
| 2607 |
"SELECT spatial.dist, spatial.width, spatial.height," |
| 2608 |
" spatial.ra1, spatial.ra2, spatial2.ra1, spatial2.dec," |
| 2609 |
" spatial2.dist, spatial2.t FROM spatial JOIN spatial2 ON ( width = dec )", |
| 2610 |
_getFieldInfoGetter()) |
| 2611 |
|
| 2612 |
def testStarWithSubquery(self): |
| 2613 |
tree = adql.parseToTree("select * from spatial join " |
| 2614 |
" (select ra1+dec, dist-2 as foo, dec from spatial2 offset 0) as q" |
| 2615 |
" ON ( width = dec )") |
| 2616 |
adql.annotate(tree, _getFieldInfoGetter()) |
| 2617 |
status, t = adql.morphPG(tree) |
| 2618 |
flattened = nodes.flatten(t) |
| 2619 |
self.assertTrue(re.match(r'SELECT spatial.dist, spatial.width, spatial.height, spatial.ra1, spatial.ra2, q.([a-z]*), q.foo, q.dec FROM spatial JOIN \(SELECT ra1 \+ dec AS \1, dist - 2 AS foo, dec FROM spatial2 OFFSET 0\) AS q ON \( width = dec \)$', flattened)) |
| 2620 |
|
| 2621 |
def testSetLimitIntegrated(self): |
| 2622 |
self._testMorph("select top 3 * from x union (select top 40 a from y" |
| 2623 |
" except select * from z)", |
| 2624 |
"SELECT * FROM x UNION ( SELECT a FROM y EXCEPT SELECT * FROM z ) LIMIT 40") |
| 2625 |
|
| 2626 |
def testDeepSetLimitProtected(self): |
| 2627 |
self._testMorph("select * from (select TOP 30 * from x) as q union" |
| 2628 |
" select TOP 4 * from u", |
| 2629 |
"SELECT * FROM (SELECT * FROM x LIMIT 30) AS q UNION SELECT * FROM u LIMIT 4") |
| 2630 |
|
| 2631 |
def testUCDCOL(self): |
| 2632 |
# non postgres-specific, but we need the annotation |
| 2633 |
self._testMorph("select UCDCOL('pos.eq.dec*'), UCDCOL('phys.dim')" |
| 2634 |
" from spatial natural join spatial2", |
| 2635 |
"SELECT dec, width FROM spatial NATURAL JOIN spatial2 ", |
| 2636 |
_getFieldInfoGetter()) |
| 2637 |
|
| 2638 |
def testInUnit(self): |
| 2639 |
# non postgres-specific, but we need the annotation |
| 2640 |
self._testMorph("select in_unit(" |
| 2641 |
"in_unit(ra1, 'deg')/in_unit(height, 'pc')+" |
| 2642 |
"in_unit(ra2, 'deg')/in_unit(width, 'pc'), 'rad/pc') as fantasy" |
| 2643 |
" from spatial", |
| 2644 |
"SELECT (((ra1 * 1) / (height * 3.240755744239556e-14) + (ra2 * 57.29577951308232) / (width * 3.240755744239557e-17)) * 0.0174532925199433) AS fantasy FROM spatial", |
| 2645 |
_getFieldInfoGetter()) |
| 2646 |
|
| 2647 |
def testUnitCoercion(self): |
| 2648 |
# non postgres-specific, but we need the annotation |
| 2649 |
self._testMorph("select (" |
| 2650 |
"ra1@{deg}/height@{pc}+ra2@{deg}/width@{pc}" |
| 2651 |
")@{rad/pc} as fantasy" |
| 2652 |
" from spatial", |
| 2653 |
"SELECT ((( (ra1 * 1) / (height * 3.240755744239556e-14) + (ra2 * 57.29577951308232) / (width * 3.240755744239557e-17) )) * 0.0174532925199433) AS fantasy FROM spatial", |
| 2654 |
_getFieldInfoGetter()) |
| 2655 |
|
| 2656 |
def testTimestamp(self): |
| 2657 |
self._testMorph("select TIMESTAMP('2007-02-03' || 'T12:33:44') from geo" |
| 2658 |
" where dt>TIMESTAMP('1997-03-02')", |
| 2659 |
"SELECT ('2007-02-03' || 'T12:33:44')::TIMESTAMP ASWHATEVER FROM geo WHERE dt > ('1997-03-02')::TIMESTAMP") |
| 2660 |
|
| 2661 |
def testBitwise(self): |
| 2662 |
self._testMorph("select BITWISE_AND(mass, mag) as one," |
| 2663 |
" BITWISE_OR(ROUND(mass), power(mag, 2)) as two," |
| 2664 |
" BITWISE_XOR(BITWISE_NOT(mass)+3, power(mag, 2)/2) as three" |
| 2665 |
" from misc", |
| 2666 |
"SELECT (mass)&(mag) AS one, (ROUND(mass))|(POWER(mag, 2)) AS two, (~(mass) + 3)#(POWER(mag, 2) / 2) AS three FROM misc") |
| 2667 |
|
| 2668 |
def testOidInUpload(self): |
| 2669 |
self._testMorph( |
| 2670 |
"select q.*, q.oid from (select oid from tap_upload.foo) as q", |
| 2671 |
"SELECT q.oid_, q.oid_ FROM (SELECT oid_ FROM foo) AS q", |
| 2672 |
fieldInfoGetter=adqlglue.DaCHSFieldInfoGetter( |
| 2673 |
tdsForUploads=[self.nastyTD])) |
| 2674 |
|
| 2675 |
def testArray(self): |
| 2676 |
self._testMorph("select vals[3] as x from crazy where vals[round(mass)]=3", |
| 2677 |
"SELECT vals [ 3 ] AS x FROM crazy WHERE vals [ ROUND(mass) ] = 3", |
| 2678 |
_getFieldInfoGetter()) |
| 2679 |
|
| 2680 |
def testEmbeddedQuotes(self): |
| 2681 |
self._testMorph("select count(*) as x from crazy where name='O''Toole'", |
| 2682 |
"SELECT COUNT ( * ) AS x FROM crazy WHERE name = 'O''Toole'", |
| 2683 |
_getFieldInfoGetter()) |
| 2684 |
|
| 2685 |
def testSampling(self): |
| 2686 |
self._testMorph("select * from foo as a tablesample( 0.01 )", |
| 2687 |
"SELECT * FROM foo AS a TABLESAMPLE SYSTEM (0.01)") |
| 2688 |
|
| 2689 |
def testSetGenerating(self): |
| 2690 |
self._testMorph("select * from generate_series(low, high) as foo", |
| 2691 |
"SELECT * FROM generate_series ( low , high ) AS foo") |
| 2692 |
|
| 2693 |
def testCharStarInCast(self): |
| 2694 |
self._testMorph("select cast(x as char(*)) as h from foo", |
| 2695 |
"SELECT CAST ( x AS TEXT ) AS h FROM foo") |
| 2696 |
|
| 2697 |
def testCoalesce(self): |
| 2698 |
self._testMorph("select coalesce(x, y+3, 'nothing') from foo", |
| 2699 |
"SELECT COALESCE ( x , y + 3 , 'nothing' ) ASWHATEVER FROM foo") |
| 2700 |
|
| 2701 |
def testArrayAgg(self): |
| 2702 |
self._testMorph("select arr_map(sin(x)+1, arr) as z from foo", |
| 2703 |
"SELECT (SELECT array_agg( SIN(x) + 1 ) from unnest( arr ) x) AS z FROM foo") |
| 2704 |
|
| 2705 |
def testCastToPoint(self): |
| 2706 |
self._testMorph("select cast('22' || ' -31' as pOint) from foo", |
| 2707 |
"SELECT cast_to_point('22' || ' -31') ASWHATEVER FROM foo") |
| 2708 |
|
| 2709 |
def testCastToCircle(self): |
| 2710 |
self._testMorph("select cast(MOC('4/22') as CIRCLE) as bcirc from foo", |
| 2711 |
"SELECT cast_to_circle(smoc('4/22')) AS bcirc FROM foo") |
| 2712 |
|
| 2713 |
def testCastToPolygon(self): |
| 2714 |
self._testMorph("select cast(CIRCLE(2, 3, 4) as polygon) from foo", |
| 2715 |
"SELECT cast_to_polygon(scircle(spoint(RADIANS(2), RADIANS(3))" |
| 2716 |
", RADIANS(4))) ASWHATEVER FROM foo") |
| 2717 |
|
| 2718 |
def testCreateTable(self): |
| 2719 |
from gavo.web import tap_uploads |
| 2720 |
try: |
| 2721 |
self._testMorph( |
| 2722 |
"Create TABLE tap_user.knall AS SELECT * FROM spatial", |
| 2723 |
"CREATE TABLE tap_user._anonymous_knall AS SELECT spatial.dist, spatial.width, spatial.height, spatial.ra1, spatial.ra2 FROM spatial", |
| 2724 |
_getFieldInfoGetter()) |
| 2725 |
finally: |
| 2726 |
with base.getWritableTableConn() as conn: |
| 2727 |
tap_uploads.dropUserUploadedTable(conn, "anonymous", "knall") |
| 2728 |
|
| 2729 |
def testUnitsPrecedence(self): |
| 2730 |
self._testMorph("select dist+height@{m}, ra1*ra2@{deg}" |
| 2731 |
"from spatial where dist>10", |
| 2732 |
"SELECT dist + (height * 1000) ASWHATEVER, ra1 * (ra2 * 57.29577951308232) ASWHATEVER FROM spatial WHERE dist > 10", |
| 2733 |
_getFieldInfoGetter()) |
| 2734 |
|
| 2735 |
|
| 2736 |
class PGSMorphTest(testhelpers.VerboseTest, |
| 2737 |
metaclass=testhelpers.SamplesBasedAutoTest): |
| 2738 |
def _runTest(self, sample): |
| 2739 |
query, morphed = sample |
| 2740 |
_, tree = adql.parseAnnotating(query, _getFieldInfoGetter()) |
| 2741 |
#pprint(tree.asTree()) |
| 2742 |
status, t = adql.morphPG(tree) |
| 2743 |
self.assertEqualIgnoringAliases(nodes.flatten(t), morphed) |
| 2744 |
|
| 2745 |
samples = [ |
| 2746 |
("select AREA(circle('ICRS', COORD1(p1), coord2(p1), 2))," |
| 2747 |
" DISTANCE(p1,p2), centroid(circle('ICRS', coord1(p1), coord2(p1)," |
| 2748 |
" 3)) from (select point('ICRS', ra1, ra2) as p1," |
| 2749 |
" point('ICRS', ra2, dist) as p2 from spatial) as q", |
| 2750 |
"SELECT 3282.806350011744*AREA(scircle(spoint(RADIANS(DEGREES(long(p1))), RADIANS(DEGREES(lat(p1)))), RADIANS(2))) ASWHATEVER, DEGREES((p1) <-> (p2)) ASWHATEVER, @@(scircle(spoint(RADIANS(DEGREES(long(p1))), RADIANS(DEGREES(lat(p1)))), RADIANS(3))) ASWHATEVER FROM (SELECT spoint(RADIANS(ra1), RADIANS(ra2)) AS p1, spoint(RADIANS(ra2), RADIANS(dist)) AS p2 FROM spatial) AS q"), |
| 2751 |
("select coord1(pt) from geo", 'SELECT DEGREES(long(pt)) ASWHATEVER FROM geo'), |
| 2752 |
("select coord2(pt) from geo", 'SELECT DEGREES(lat(pt)) ASWHATEVER FROM geo'), |
| 2753 |
("select coordsys(q.p) as c from (select point('ICRS', dist, width)" |
| 2754 |
" as p from spatial) as q", |
| 2755 |
"SELECT 'ICRS' AS c FROM (SELECT spoint(RADIANS(dist), RADIANS(width)) AS p FROM spatial) AS q"), |
| 2756 |
("select ra1 from spatial where" |
| 2757 |
" Intersects(circle('ICRS', ra1, ra2," |
| 2758 |
" height*height), polygon('ICRS', 1, 12, 3, 4, 5, 6, 7, 8))=0", |
| 2759 |
"SELECT ra1 FROM spatial WHERE NOT ( ((scircle(spoint(RADIANS(ra1), RADIANS(ra2)), RADIANS(height * height))) && ((SELECT spoly(q.p) FROM (VALUES (0, spoint(RADIANS(1), RADIANS(12))), (1, spoint(RADIANS(3), RADIANS(4))), (2, spoint(RADIANS(5), RADIANS(6))), (3, spoint(RADIANS(7), RADIANS(8))) ORDER BY column1) as q(ind,p)))) )"), |
| 2760 |
|
| 2761 |
# 5 |
| 2762 |
("select ra1 from spatial where" |
| 2763 |
" contains(circle('ICRS', ra1, ra2," |
| 2764 |
" height*height), box('ICRS', dist, width, height, ra2))=0", |
| 2765 |
"SELECT ra1 FROM spatial WHERE NOT ( ((scircle(spoint(RADIANS(ra1), RADIANS(ra2)), RADIANS(height * height))) <@ ((SELECT spoly(q.p) FROM (VALUES (0, spoint(RADIANS(dist)-RADIANS(height)/2, RADIANS(width)-RADIANS(ra2)/2)), (1, spoint(RADIANS(dist)-RADIANS(height)/2, RADIANS(width)+RADIANS(ra2)/2)), (2, spoint(RADIANS(dist)+RADIANS(height)/2, RADIANS(width)+RADIANS(ra2)/2)), (3, spoint(RADIANS(dist)+RADIANS(height)/2, RADIANS(width)-RADIANS(ra2)/2)) ORDER BY column1) as q(ind,p)))) )"), |
| 2766 |
("select point('ICRS', cos(ra1)*sin(ra2), cos(ra2)*sin(ra1))," |
| 2767 |
" circle('ICRS', width, height, 25-dist*dist) from spatial", |
| 2768 |
'SELECT spoint(RADIANS(COS(ra1) * SIN(ra2)), RADIANS(COS(ra2) * SIN(ra1))) ASWHATEVER, scircle(spoint(RADIANS(width), RADIANS(height)), RADIANS(25 - dist * dist)) ASWHATEVER FROM spatial'), |
| 2769 |
("select POiNT('ICRS', 1, 2), CIRCLE('ICRS', 2, 3, 4)," |
| 2770 |
" bOx('ICRS', 2 ,3, 4, 5), polygon('ICRS', 2, 3, 4, 5, 6, 7)" |
| 2771 |
" from spatial", |
| 2772 |
'SELECT spoint(RADIANS(1), RADIANS(2)) ASWHATEVER,' |
| 2773 |
' scircle(spoint(RADIANS(2), RADIANS(3)), RADIANS(4)) ASWHATEVER,' |
| 2774 |
' (SELECT spoly(q.p) FROM (VALUES (0, spoint(RADIANS(2)-RADIANS(4)/2, RADIANS(3)-RADIANS(5)/2)), (1, spoint(RADIANS(2)-RADIANS(4)/2, RADIANS(3)+RADIANS(5)/2)), (2, spoint(RADIANS(2)+RADIANS(4)/2, RADIANS(3)+RADIANS(5)/2)), (3, spoint(RADIANS(2)+RADIANS(4)/2, RADIANS(3)-RADIANS(5)/2)) ORDER BY column1) as q(ind,p)) ASWHATEVER,' |
| 2775 |
' (SELECT spoly(q.p) FROM (VALUES (0, spoint(RADIANS(2), RADIANS(3))), (1, spoint(RADIANS(4), RADIANS(5))), (2, spoint(RADIANS(6), RADIANS(7))) ORDER BY column1) as q(ind,p)) ASWHATEVER FROM spatial'), |
| 2776 |
("select Box('ICRS',ra1,ra2,dist*100,width*100)" |
| 2777 |
" from spatial where dist!=0 and width!=0", |
| 2778 |
"SELECT (SELECT spoly(q.p) FROM (VALUES (0, spoint(RADIANS(ra1)-RADIANS(dist * 100)/2, RADIANS(ra2)-RADIANS(width * 100)/2)), (1, spoint(RADIANS(ra1)-RADIANS(dist * 100)/2, RADIANS(ra2)+RADIANS(width * 100)/2)), (2, spoint(RADIANS(ra1)+RADIANS(dist * 100)/2, RADIANS(ra2)+RADIANS(width * 100)/2)), (3, spoint(RADIANS(ra1)+RADIANS(dist * 100)/2, RADIANS(ra2)-RADIANS(width * 100)/2)) ORDER BY column1) as q(ind,p)) ASWHATEVER FROM spatial WHERE dist != 0 AND width != 0"), |
| 2779 |
("select * from spatial where 1=contains(point('fk4', 1,2)," |
| 2780 |
" circle('Galactic',2,3,4))", |
| 2781 |
"SELECT spatial.dist, spatial.width, spatial.height, spatial.ra1, spatial.ra2 FROM spatial WHERE (((spoint(RADIANS(2), RADIANS(3)))-strans(1.346356097441,-1.097319001837,0.574770524729)+strans(1.565186433367,-0.004859055280,-1.576368104353)) <@ (scircle(spoint(RADIANS(1), RADIANS(2)), RADIANS(4))))"), |
| 2782 |
# 10 |
| 2783 |
("select ra2 from spatial where contains(point('UNKNOWN', height,width)," |
| 2784 |
" circle('Galactic',2,3,4))=1", |
| 2785 |
"SELECT ra2 FROM spatial WHERE ((spoint(RADIANS(height), RADIANS(width))) <@ (scircle(spoint(RADIANS(2), RADIANS(3)), RADIANS(4))))"), |
| 2786 |
("select dt from geo where 1=intersects(coverage," |
| 2787 |
"circle('icrs', 10, 10, 1))", |
| 2788 |
"SELECT dt FROM geo WHERE ((coverage) && (scircle(spoint(RADIANS(10), RADIANS(10)), RADIANS(1))))"), |
| 2789 |
("select \"plAin\" from quoted where 1=intersects(\"left-right\"," |
| 2790 |
"circle('icrs', 10, 10, 1))", |
| 2791 |
"SELECT \"plAin\" FROM quoted WHERE ((\"left-right\") && (scircle(spoint(RADIANS(10), RADIANS(10)), RADIANS(1))))"), |
| 2792 |
("select contains(coverage, circle('', 10, 10, 1)) from geo", |
| 2793 |
"SELECT CONTAINS(coverage, scircle(spoint(RADIANS(10), RADIANS(10)), RADIANS(1))) ASWHATEVER FROM geo"), |
| 2794 |
("select * from (select point(ra1, ra2) as p from spatial) as q" |
| 2795 |
" where 1=intersects(circle(p, 0.1), circle(1,2,3))", |
| 2796 |
"SELECT q.p FROM (SELECT spoint(RADIANS(ra1), RADIANS(ra2)) AS p FROM spatial) AS q WHERE ((scircle(p, RADIANS(0.1))) && (scircle(spoint(RADIANS(1), RADIANS(2)), RADIANS(3))))"), |
| 2797 |
# 15 |
| 2798 |
("select distance(ra1, dec, 12, 13) as d1," |
| 2799 |
" distance(point(ra1, dec), point(12, 13)) as d2" |
| 2800 |
" from spatial2" |
| 2801 |
" where distance(10, 13, ra1, dec) < 2", |
| 2802 |
"SELECT DEGREES((spoint(RADIANS(ra1), RADIANS(dec))) <-> (spoint(RADIANS(12), RADIANS(13)))) AS d1, DEGREES((spoint(RADIANS(ra1), RADIANS(dec))) <-> (spoint(RADIANS(12), RADIANS(13)))) AS d2 FROM spatial2 WHERE (spoint(RADIANS(ra1), RADIANS(dec))) <@ scircle(spoint(RADIANS(10), RADIANS(13)), RADIANS(2))"), |
| 2803 |
("select 1 as c" |
| 2804 |
" from spatial2" |
| 2805 |
" where 2>=distance(10, 13, ra1, dec)", |
| 2806 |
'SELECT 1 AS c FROM spatial2 WHERE (spoint(RADIANS(ra1), RADIANS(dec))) <@ scircle(spoint(RADIANS(10), RADIANS(13)), RADIANS(2))'), |
| 2807 |
("select 1 as c" |
| 2808 |
" from spatial2" |
| 2809 |
" where 2<distance(ra1, dec, 10, 13)", |
| 2810 |
"SELECT 1 AS c FROM spatial2 WHERE NOT (spoint(RADIANS(ra1), RADIANS(dec))) <@ scircle(spoint(RADIANS(10), RADIANS(13)), RADIANS(2))"), |
| 2811 |
("select 1 as c" |
| 2812 |
" from spatial2" |
| 2813 |
" where distance(10, 13, ra1, dec)>cos(dec)", |
| 2814 |
"SELECT 1 AS c FROM spatial2 WHERE NOT (spoint(RADIANS(ra1), RADIANS(dec))) <@ scircle(spoint(RADIANS(10), RADIANS(13)), RADIANS(COS(dec)))"), |
| 2815 |
("select 1 as c" |
| 2816 |
" from spatial2" |
| 2817 |
" where distance(10, 13, ra1, dec)>distance(3, 10, dist, dec)", |
| 2818 |
'SELECT 1 AS c FROM spatial2 WHERE (spoint(RADIANS(dist), RADIANS(dec))) <@ scircle(spoint(RADIANS(3), RADIANS(10)), RADIANS(DEGREES((spoint(RADIANS(dist), RADIANS(dec))) <-> (spoint(RADIANS(3), RADIANS(10))))))'), |
| 2819 |
# 20 |
| 2820 |
("select 1 as c" |
| 2821 |
" from spatial2" |
| 2822 |
" where distance(ra1, dec, 10, 13)>2", |
| 2823 |
"SELECT 1 AS c FROM spatial2 WHERE NOT (spoint(RADIANS(ra1), RADIANS(dec))) <@ scircle(spoint(RADIANS(10), RADIANS(13)), RADIANS(2))"), |
| 2824 |
("select MOC(6, p), moc('4/3,'|| dist) from" |
| 2825 |
" (select point(ra1, ra2) as p, dist from spatial) as q", |
| 2826 |
"SELECT smoc(6, p) ASWHATEVER, smoc('4/3,' || dist) ASWHATEVER FROM (SELECT spoint(RADIANS(ra1), RADIANS(ra2)) AS p, dist FROM spatial) AS q"), |
| 2827 |
] |
| 2828 |
|
| 2829 |
|
| 2830 |
class PGSNoMorphTest(testhelpers.VerboseTest): |
| 2831 |
def testPolygonNoCentroid(self): |
| 2832 |
tree = adql.parseToTree( |
| 2833 |
"select centroid(polygon('ICRS', 12, 13, 14, 15, 15, 17)) from foo") |
| 2834 |
self.assertRaisesWithMsg(adql.MorphError, |
| 2835 |
"Can only compute centroids of circles and points yet." |
| 2836 |
" Complain to make us implement other geometries faster.", |
| 2837 |
adql.morphPG, |
| 2838 |
(tree,)) |
| 2839 |
|
| 2840 |
def testReferencedBoxNoCentroid(self): |
| 2841 |
tree = parseWithArtificialTable( |
| 2842 |
"select centroid(b) from (select" |
| 2843 |
" box('', 1, 1, 2, 2) as b from spatial) as q") |
| 2844 |
self.assertRaisesWithMsg(adql.MorphError, |
| 2845 |
"Can only compute centroids of circles and points yet." |
| 2846 |
" Complain to make us implement other geometries faster.", |
| 2847 |
adql.morphPG, |
| 2848 |
(tree,)) |
| 2849 |
|
| 2850 |
|
| 2851 |
class UDFMorphTest(_MorphTestWithTestTables): |
| 2852 |
def testDistanceWithCoord(self): |
| 2853 |
s, t = morphpg.morphPG( |
| 2854 |
self._parseAnnotating( |
| 2855 |
"select dist from spatial where" |
| 2856 |
" 2>distance(coord1(ivo_healpix_center(5, 100))," |
| 2857 |
" coord2(ivo_healpix_center(5, 100)), ra1, ra2)")) |
| 2858 |
self.assertEqual(adql.flatten(t), |
| 2859 |
"SELECT dist FROM spatial WHERE q3c_join(COORD1(center_of_healpix_nest(5, 100)), COORD2(center_of_healpix_nest(5, 100)), ra1, ra2, 2)") |
| 2860 |
|
| 2861 |
def testCircleWithCoord(self): |
| 2862 |
s, t = morphpg.morphPG( |
| 2863 |
self._parseAnnotating( |
| 2864 |
"select dist from spatial where" |
| 2865 |
" 1=contains(point(ra1, ra2), " |
| 2866 |
" CIRCLE(coord1(ivo_healpix_center(5, 100))," |
| 2867 |
" coord2(ivo_healpix_center(5, 100)), 2))")) |
| 2868 |
self.assertEqual(adql.flatten(t), |
| 2869 |
"SELECT dist FROM spatial WHERE q3c_join(DEGREES(long(center_of_healpix_nest(5, 100))), DEGREES(lat(center_of_healpix_nest(5, 100))), ra1, ra2, 2)") |
| 2870 |
|
| 2871 |
@unittest.skipUnless(testhelpers.hasUDF("IVO_EPOCH_PROP"), "pgsphere too old") |
| 2872 |
def testPolygonConst(self): |
| 2873 |
s, t = morphpg.morphPG( |
| 2874 |
self._parseAnnotating( |
| 2875 |
"select polygon(coord1(p1), coord2(p1), coord1(p2), coord2(p2)," |
| 2876 |
"2,3) from (SELECT POINT(ra1, ra2) as p1, ivo_apply_pm(ra1, ra2," |
| 2877 |
" 1e-7, 2e-7, 10) as p2 from spatial) as q")) |
| 2878 |
self.assertEqualIgnoringAliases(adql.flatten(t), |
| 2879 |
"SELECT (SELECT spoly(q.p) FROM (VALUES (0, spoint(RADIANS(" |
| 2880 |
"DEGREES(long(p1))), RADIANS(DEGREES(lat(p1))))), " |
| 2881 |
"(1, spoint(RADIANS(DEGREES(long(p2))), RADIANS(DEGREES(lat(p2)))))," |
| 2882 |
" (2, spoint(RADIANS(2), RADIANS(3))) ORDER BY column1) as q(ind,p))" |
| 2883 |
" ASWHATEVER FROM (SELECT spoint(RADIANS(ra1), RADIANS(ra2)) AS p1," |
| 2884 |
" IVO_APPLY_PM(ra1, ra2, 1e-7, 2e-7, 10) AS p2 FROM spatial) AS q") |
| 2885 |
|
| 2886 |
def testNestedUDFs(self): |
| 2887 |
s, t = morphpg.morphPG( |
| 2888 |
self._parseAnnotating( |
| 2889 |
"select dist from spatial where" |
| 2890 |
" 1=ivo_interval_overlaps(dist-1, dist+1," |
| 2891 |
" gavo_specconv(500, 'pm', 'm'), gavo_specconv(600, 'pm', 'm'))")) |
| 2892 |
self.assertEqual(adql.flatten(t), |
| 2893 |
"SELECT dist FROM spatial WHERE dist + 1 >= 1e-12 * ( 500 ) / 1 AND 1e-12 * ( 600 ) / 1 >= dist - 1 AND dist - 1 <= dist + 1 AND 1e-12 * ( 500 ) / 1 <= 1e-12 * ( 600 ) / 1") |
| 2894 |
|
| 2895 |
|
| 2896 |
class GlueTest(testhelpers.VerboseTest): |
| 2897 |
# Tests for some aspects of adqlglue |
| 2898 |
def testAutoNull(self): |
| 2899 |
td = adqlglue._getTableDescForOutput( |
| 2900 |
parseWithArtificialTable("select * from crazy")) |
| 2901 |
self.assertEqual(td.getColumnByName("ct").values.nullLiteral, "-2147483648") |
| 2902 |
|
| 2903 |
def testSpecifiedNull(self): |
| 2904 |
td = adqlglue._getTableDescForOutput( |
| 2905 |
parseWithArtificialTable("select * from crazy")) |
| 2906 |
self.assertEqual(td.getColumnByName("wot").values.nullLiteral, "-1") |
| 2907 |
|
| 2908 |
def testSpecifiedNullOverridden(self): |
| 2909 |
td = adqlglue._getTableDescForOutput( |
| 2910 |
parseWithArtificialTable("select 2+wot from crazy")) |
| 2911 |
self.assertEqual(td.columns[0].values.nullLiteral, '-9223372036854775808') |
| 2912 |
|
| 2913 |
def testPureByteaNotPromoted(self): |
| 2914 |
td = adqlglue._getTableDescForOutput( |
| 2915 |
parseWithArtificialTable("select wotb from crazy")) |
| 2916 |
self.assertEqual(td.columns[0].values.nullLiteral, '254') |
| 2917 |
self.assertEqual(td.columns[0].type, 'bytea') |
| 2918 |
|
| 2919 |
def testByteaInMultiplication(self): |
| 2920 |
# This probably behaviour that doesn't work with postgres anyway. |
| 2921 |
# Fix the whole unsignedByte mess by not linking it to bytea. |
| 2922 |
td = adqlglue._getTableDescForOutput( |
| 2923 |
parseWithArtificialTable("select 2*wotb from crazy")) |
| 2924 |
self.assertEqual(td.columns[0].type, 'smallint') |
| 2925 |
self.assertEqual(td.columns[0].values.nullLiteral, "-32768") |
| 2926 |
|
| 2927 |
|
| 2928 |
class TableheadTest(testhelpers.VerboseTest): |
| 2929 |
def _assertTablehead(self, expr, tablehead): |
| 2930 |
tree, selClause = adql.parseAnnotating(f"select {expr} from spatial", |
| 2931 |
_getFieldInfoGetter()) |
| 2932 |
tableTrunk = adqlglue._getTableDescForOutput(selClause) |
| 2933 |
self.assertEqual(tableTrunk.columns[0].tablehead, tablehead) |
| 2934 |
|
| 2935 |
def testDirectColumnReference(self): |
| 2936 |
self._assertTablehead("ra1", "Raw RA") |
| 2937 |
|
| 2938 |
def testNoInventedTablehead(self): |
| 2939 |
self._assertTablehead("dist", None) |
| 2940 |
|
| 2941 |
def testAsHonoured(self): |
| 2942 |
self._assertTablehead("dist as foo", "foo") |
| 2943 |
|
| 2944 |
def testDelimitedAs(self): |
| 2945 |
self._assertTablehead('dist as "some ""mad"" terms"', 'some "mad" terms') |
| 2946 |
|
| 2947 |
def testExpression(self): |
| 2948 |
self._assertTablehead('power(dist, 3)', 'POWER(dist, 3)') |
| 2949 |
|
| 2950 |
def testLongExpression(self): |
| 2951 |
self._assertTablehead('sqrt(power(dist, 3)+log10(width))', |
| 2952 |
'SQRT(POWER(dist, 3) + LOG10(w…') |
| 2953 |
|
| 2954 |
|
| 2955 |
class QueryTest(testhelpers.VerboseTest): |
| 2956 |
"""performs some actual queries to test the whole thing. |
| 2957 |
""" |
| 2958 |
resources = [("ds", adqlTestTable), ("querier", adqlQuerier), |
| 2959 |
("geomds", tresc.adqlGeoTable)] |
| 2960 |
|
| 2961 |
def setUp(self): |
| 2962 |
testhelpers.VerboseTest.setUp(self) |
| 2963 |
self.tableName = self.ds.tables["adql"].tableDef.getQName() |
| 2964 |
|
| 2965 |
def _assertFieldProperties(self, dataField, expected): |
| 2966 |
for label, value in expected: |
| 2967 |
self.assertEqual(getattr(dataField, label, None), value, |
| 2968 |
"Data field %s:" |
| 2969 |
" Expected %s for %s, found %s"%(dataField.name, repr(value), |
| 2970 |
label, repr(getattr(dataField, label, None)))) |
| 2971 |
|
| 2972 |
def runQuery(self, query, **kwargs): |
| 2973 |
return self.querier.queryADQL(query, **kwargs) |
| 2974 |
|
| 2975 |
def testPlainSelect(self): |
| 2976 |
res = self.runQuery( |
| 2977 |
"select alpha, delta, NULL from %s where mag<0"% |
| 2978 |
self.tableName) |
| 2979 |
self.assertEqual(res.tableDef.id, self.tableName.split(".")[-1]) |
| 2980 |
|
| 2981 |
row = testhelpers.pickSingle(res.rows) |
| 2982 |
self.assertEqual(len(row), 3) |
| 2983 |
self.assertEqual(row["alpha"], 290.125) |
| 2984 |
raField, deField, nullField = res.tableDef.columns |
| 2985 |
self._assertFieldProperties(raField, [("ucd", 'pos.eq.ra;meta.main'), |
| 2986 |
("description", 'A sample RA'), ("unit", 'deg'), |
| 2987 |
("tablehead", "Raw RA")]) |
| 2988 |
self._assertFieldProperties(deField, [("ucd", 'pos.eq.dec;meta.main'), |
| 2989 |
("description", 'A sample Dec'), ("unit", 'deg'), |
| 2990 |
("tablehead", None)]) |
| 2991 |
self._assertFieldProperties(nullField, [("type", "real"), |
| 2992 |
("description", ' [ADQL: NULL]'), ("unit", '')]) |
| 2993 |
|
| 2994 |
def testStarSelect(self): |
| 2995 |
res = self.runQuery("select * from %s where mag<0"% |
| 2996 |
self.tableName) |
| 2997 |
self.assertEqual(len(testhelpers.pickSingle(res.rows)), 5) |
| 2998 |
fields = res.tableDef.columns |
| 2999 |
self._assertFieldProperties(fields[0], [("ucd", 'pos.eq.ra;meta.main'), |
| 3000 |
("description", 'A sample RA'), ("unit", 'deg'), |
| 3001 |
("tablehead", "Raw RA")]) |
| 3002 |
self._assertFieldProperties(fields[1], [("ucd", 'pos.eq.dec;meta.main'), |
| 3003 |
("description", 'A sample Dec'), ("unit", 'deg'), |
| 3004 |
("tablehead", None)]) |
| 3005 |
self._assertFieldProperties(fields[3], [ |
| 3006 |
("ucd", 'phys.veloc;pos.heliocentric'), |
| 3007 |
("description", 'A sample radial velocity'), ("unit", 'km/s')]) |
| 3008 |
self._assertFieldProperties(fields[4], [ |
| 3009 |
("ucd", ''), ("description", ''), ("unit", '')]) |
| 3010 |
|
| 3011 |
def testQualifiedStarSelect(self): |
| 3012 |
res = self.runQuery("select %s.* from %s join %s as q1" |
| 3013 |
" using (mag) where q1.mag<0"%( |
| 3014 |
self.tableName, self.tableName, self.tableName)) |
| 3015 |
self.assertEqual(res.tableDef.id, "adql_q1") |
| 3016 |
self.assertEqual(len(testhelpers.pickSingle(res.rows)), 5) |
| 3017 |
fields = res.tableDef.columns |
| 3018 |
self._assertFieldProperties(fields[0], [("ucd", 'pos.eq.ra;meta.main'), |
| 3019 |
("description", 'A sample RA'), ("unit", 'deg'), |
| 3020 |
("tablehead", "Raw RA")]) |
| 3021 |
|
| 3022 |
def testNoCase(self): |
| 3023 |
# will just raise an Exception if things are broken. |
| 3024 |
self.runQuery("select ALPHA, DeLtA, MaG from %s"%self.tableName) |
| 3025 |
|
| 3026 |
def testDelimitedMapping(self): |
| 3027 |
res = self.runQuery('select alpha from "test"."adql"') |
| 3028 |
self.assertEqual( |
| 3029 |
str(res.tableDef.columns[0].name), |
| 3030 |
'alpha') |
| 3031 |
self.assertEqual( |
| 3032 |
res.tableDef.id, |
| 3033 |
"_adql") |
| 3034 |
|
| 3035 |
def testDelimitedBadTableFails(self): |
| 3036 |
# hack: the group by in the query below currently suppresses the use |
| 3037 |
# of cursors which would make our error messages a good deal uglier. |
| 3038 |
self.assertRaisesWithMsg(base.DBError, |
| 3039 |
'relation "test.Adql" does not exist\nLINE 1: SELECT "alpha" FROM test."Adql" GROUP BY "alpha" LIMIT 20000\n ^\n', |
| 3040 |
self.runQuery, |
| 3041 |
('select "alpha" from test."Adql" group by "alpha"',)) |
| 3042 |
|
| 3043 |
def testDelimitedNameForDerived(self): |
| 3044 |
res = self.runQuery('select "SEL-ECT".alpha from' |
| 3045 |
'(SELECT alpha FROM test.adql) "SEL-ECT"') |
| 3046 |
self.assertEqual( |
| 3047 |
res.tableDef.columns[0].name, |
| 3048 |
'alpha') |
| 3049 |
self.assertEqual(res.tableDef.id, '"SEL-ECT"') |
| 3050 |
|
| 3051 |
def testTainting(self): |
| 3052 |
res = self.runQuery("select delta*2, alpha*mag, alpha+delta" |
| 3053 |
" from %s where mag<-10"% self.tableName) |
| 3054 |
f1, f2, f3 = res.tableDef.columns |
| 3055 |
self._assertFieldProperties(f1, [("ucd", 'pos.eq.dec;meta.main'), |
| 3056 |
("description", 'A sample Dec -- *TAINTED*: the value was operated' |
| 3057 |
' on in a way that unit and ucd may be severely wrong' |
| 3058 |
' [ADQL: delta * 2]'), |
| 3059 |
("unit", 'deg')]) |
| 3060 |
self._assertFieldProperties(f2, [("ucd", ''), |
| 3061 |
("description", 'This field has traces of: A sample RA;' |
| 3062 |
' A sample magnitude -- *TAINTED*: the value was operated' |
| 3063 |
' on in a way that unit and ucd may be severely wrong' |
| 3064 |
' [ADQL: alpha * mag]'), |
| 3065 |
("unit", 'deg.mag')]) |
| 3066 |
self._assertFieldProperties(f3, [("ucd", ''), |
| 3067 |
("description", 'This field has traces of: A sample RA; A sample Dec' |
| 3068 |
' -- *TAINTED*: the value was operated on in a way that unit and' |
| 3069 |
' ucd may be severely wrong [ADQL: alpha + delta]'), |
| 3070 |
("unit", 'deg')]) |
| 3071 |
|
| 3072 |
def testTransformation(self): |
| 3073 |
res = self.runQuery("select mag from %s where" |
| 3074 |
" 1=contains(point('icrs', alpha, delta)," |
| 3075 |
" circle('galactic', 107,-47, 1))"%self.tableName) |
| 3076 |
self.assertEqual(list(res)[0]["mag"], 10.25) |
| 3077 |
|
| 3078 |
def testGeometryInSelect(self): |
| 3079 |
res = self.runQuery( |
| 3080 |
"select rv, point('icrs', alpha, delta) as p, mag, alpha, delta," |
| 3081 |
" contains(point(alpha, delta), circle('', 3, 15, 1)) as c," |
| 3082 |
" contains(point('', alpha, delta), circle(3, 15, 2)) as c1," |
| 3083 |
" intersects(point(alpha, delta), circle(3, 15, 2)) as i1," |
| 3084 |
" intersects(circle(alpha, delta, 1.5), circle(3, 15, 1.5)) as i2," |
| 3085 |
" intersects(circle(alpha, delta, 0.5), circle(3, 15, 0.5)) as i3," |
| 3086 |
" circle('icrs', alpha, delta, 10) as ci," |
| 3087 |
" circle(delta, alpha, 5) as cn" |
| 3088 |
" from %s where mag>5"%self.tableName) |
| 3089 |
rows = list(res) |
| 3090 |
|
| 3091 |
expected = pgsphere.SPoint.fromDegrees(2, 14) |
| 3092 |
self.assertAlmostEqual(rows[0]["p"].x, expected.x) |
| 3093 |
self.assertAlmostEqual(rows[0]["p"].y, expected.y) |
| 3094 |
self.assertEqual(rows[0]["rV"], -23.75) |
| 3095 |
self.assertEqual(rows[0]["c"], 0) |
| 3096 |
self.assertEqual(rows[0]["c1"], 1) |
| 3097 |
self.assertEqual(rows[0]["i1"], 1) |
| 3098 |
self.assertEqual(rows[0]["i2"], 1) |
| 3099 |
self.assertEqual(rows[0]["i3"], 0) |
| 3100 |
expected = pgsphere.SCircle.fromDALI([2, 14, 10]) |
| 3101 |
expected2 = pgsphere.SCircle.fromDALI([14, 2, 5]) |
| 3102 |
self.assertAlmostEqual(rows[0]["ci"].center.x, expected.center.x) |
| 3103 |
self.assertAlmostEqual(rows[0]["ci"].radius, expected.radius) |
| 3104 |
self.assertAlmostEqual(rows[0]["cn"].center.y, expected2.center.y) |
| 3105 |
self.assertAlmostEqual(rows[0]["cn"].radius, expected2.radius) |
| 3106 |
self.assertEqual(res.tableDef.getColumnByName("p").type, |
| 3107 |
"spoint") |
| 3108 |
self.assertEqual(res.tableDef.getColumnByName("ci").type, |
| 3109 |
"scircle") |
| 3110 |
self.assertEqual(res.tableDef.getColumnByName("cn").type, |
| 3111 |
"scircle") |
| 3112 |
|
| 3113 |
def testQuotedIdentifier(self): |
| 3114 |
res = self.runQuery( |
| 3115 |
'select "rv", rV from %s where delta=89'%self.tableName) |
| 3116 |
self.assertEqual(res.rows, [{"rV": 28., "rV_": 28.}]) |
| 3117 |
|
| 3118 |
def testNoCasefixingOnExpressions(self): |
| 3119 |
res = self.runQuery( |
| 3120 |
'select rv, rv+1 from %s where delta=89'%self.tableName) |
| 3121 |
self.assertEqual(res.rows[0]["rV"], 28.0) |
| 3122 |
# the other name must be a result of intToFunnyWord, i.e., all-lowercase. |
| 3123 |
otherId = (set(res.rows[0].keys())-{"rV"}).pop() |
| 3124 |
self.assertTrue(re.match("[a-z]+$", otherId)) |
| 3125 |
|
| 3126 |
def testDistanceDegrees(self): |
| 3127 |
res = self.runQuery( |
| 3128 |
"select DISTANCE(POINT('ICRS', 22, -3), POINT('ICRS', 183, 50)) as d" |
| 3129 |
" from %s"%self.tableName) |
| 3130 |
self.assertAlmostEqual(res.rows[0]["d"], 130.31777623681) |
| 3131 |
|
| 3132 |
def testInUnitGeometry(self): |
| 3133 |
res = self.runQuery( |
| 3134 |
"select in_unit(DISTANCE(POINT('ICRS', 22, -3)," |
| 3135 |
" POINT('ICRS', 183, 50)), 'rad') as d" |
| 3136 |
" from %s"%self.tableName) |
| 3137 |
self.assertAlmostEqual(res.rows[0]["d"], 2.27447426920956) |
| 3138 |
|
| 3139 |
def testGeometryCoercion(self): |
| 3140 |
res = self.runQuery( |
| 3141 |
"select DISTANCE(POINT('ICRS', 22, -3)," |
| 3142 |
" POINT('ICRS', 183, 50))@{rad} as d" |
| 3143 |
" from %s"%self.tableName) |
| 3144 |
self.assertAlmostEqual(res.rows[0]["d"], 2.27447426920956) |
| 3145 |
|
| 3146 |
@unittest.skipUnless(testhelpers.hasUDF("IVO_EPOCH_PROP"), "pgsphere too old") |
| 3147 |
def testApplyPM(self): |
| 3148 |
res = self.runQuery( |
| 3149 |
"SELECT moved, coord1(moved) as ra, coord2(moved) as dec FROM (SELECT" |
| 3150 |
" ivo_epoch_prop_pos(alpha, delta, NULL, 7200, -3600, NULL, 2020, 1965) as moved" |
| 3151 |
" FROM %s where alpha between 20 and 26) AS q"%self.tableName) |
| 3152 |
mapped = list(base.SerManager(res).getMappedValues())[0] |
| 3153 |
self.assertAlmostEqual(mapped["moved"][0], 24.88665977523) |
| 3154 |
self.assertAlmostEqual(mapped["moved"][1], -13.9449737974) |
| 3155 |
self.assertAlmostEqual(mapped["ra"], 24.88665977523) |
| 3156 |
self.assertAlmostEqual(mapped["dec"], -13.9449737974) |
| 3157 |
|
| 3158 |
def testStringFunctions(self): |
| 3159 |
res = self.runQuery( |
| 3160 |
"SELECT UPPer(table_name) as tn, lower(table_name) as td" |
| 3161 |
" from tap_schema.columns where column_name ='table_name'") |
| 3162 |
self.assertTrue({'tn': 'TAP_SCHEMA.TABLES', 'td': 'tap_schema.tables' |
| 3163 |
} in res.rows) |
| 3164 |
|
| 3165 |
def testDMAnnotation(self): |
| 3166 |
res = self.runQuery("SELECT TOP 1 * FROM %s"%self.tableName) |
| 3167 |
ann = next(res.tableDef.iterAnnotationsOfType("geojson:FeatureCollection" |
| 3168 |
)) |
| 3169 |
self.assertEqual(ann["feature"]["geometry"]["type"], "sepcoo") |
| 3170 |
self.assertEqual(ann["feature"]["geometry"]["latitude"].value, |
| 3171 |
res.tableDef.getByName("delta")) |
| 3172 |
|
| 3173 |
def testMOCVsPoint(self): |
| 3174 |
res = self.runQuery("SELECT row_id FROM test.adqlgeo" |
| 3175 |
" WHERE 1=CONTAINS(POINT('ICRS', 55.5, 20.7), a_moc)") |
| 3176 |
self.assertEqual([r["row_id"] for r in res.rows], |
| 3177 |
['moc-6-1', 'moc-4-1']) |
| 3178 |
res = self.runQuery("SELECT row_id FROM test.adqlgeo" |
| 3179 |
" WHERE 1=CONTAINS(POINT('ICRS', 56, 21), a_moc)") |
| 3180 |
self.assertEqual([r["row_id"] for r in res.rows], |
| 3181 |
['moc-4-1']) |
| 3182 |
|
| 3183 |
def testSpointedCircle(self): |
| 3184 |
res = self.runQuery("SELECT row_id FROM test.adqlgeo" |
| 3185 |
" WHERE 1=INTERSECTS(CIRCLE(a_point, 1), CIRCLE(23, 42, 1))") |
| 3186 |
self.assertEqual([r["row_id"] for r in res.rows], |
| 3187 |
['moc-6-1']) |
| 3188 |
|
| 3189 |
def testSpointedPolygon(self): |
| 3190 |
res = self.runQuery("SELECT row_id," |
| 3191 |
" polygon(a_point,POINT(23,42), POINT(23, 41)) as p FROM test.adqlgeo" |
| 3192 |
" WHERE 1=CONTAINS(POINT(24, 43), POLYGON(a_point," |
| 3193 |
" POINT(23,42), POINT(23, 41), POINT(24, 41)))") |
| 3194 |
self.assertEqual([r["row_id"] for r in res.rows], |
| 3195 |
['moc-4-1']) |
| 3196 |
self.assertAlmostEqual(res.rows[-1]["p"].points[0].x, 0.436332313) |
| 3197 |
|
| 3198 |
def testCTE(self): |
| 3199 |
res = self.runQuery("WITH knall as (SELECT POINT(alpha, delta) as pt" |
| 3200 |
" from test.adql)" |
| 3201 |
" SELECT * FROM kNall") |
| 3202 |
self.assertEqual(len(res.rows), 3) |
| 3203 |
self.assertEqual(type(res.rows[0]["pt"]), pgsphere.SPoint) |
| 3204 |
self.assertEqual(res.tableDef.columns[0].name, "pt") |
| 3205 |
for infoMeta in res.iterMeta("info"): |
| 3206 |
if infoMeta.infoName=="sql_query": |
| 3207 |
self.assertEqual(infoMeta.infoValue, |
| 3208 |
'WITH knall AS MATERIALIZED ( SELECT spoint(RADIANS(alpha), RADIANS(delta)) AS pt FROM test.adql ) SELECT kNall.pt FROM kNall LIMIT 20000') |
| 3209 |
break |
| 3210 |
else: |
| 3211 |
self.fail("No sql_query info meta?") |
| 3212 |
|
| 3213 |
def testSetGeneratingFunction(self): |
| 3214 |
res = self.runQuery("SELECT * FROM GENERATE_SERIES(1,2)") |
| 3215 |
self.assertEqual(len(res.rows), 2) |
| 3216 |
self.assertEqual(res.tableDef.columns[0].name, "generate_series") |
| 3217 |
self.assertEqual(res.tableDef.id, "generate_series") |
| 3218 |
|
| 3219 |
def testMOCMaking(self): |
| 3220 |
res = self.runQuery("SELECT moc('4/' || z) as g" |
| 3221 |
" FROM GENERATE_SERIES(9,12) as z") |
| 3222 |
self.assertEqual(res.rows[-1]["g"].asDALI(), "4/12") |
| 3223 |
|
| 3224 |
def testTimestampOutput(self): |
| 3225 |
res = self.runQuery("select top 1 timestamp('2020-01-12')" |
| 3226 |
" as t from tap_schema.tables") |
| 3227 |
self.assertEqual(res.rows[0]["t"], datetime.datetime(2020, 1, 12)) |
| 3228 |
|
| 3229 |
def testGeoCasts(self): |
| 3230 |
res = self.runQuery("select" |
| 3231 |
" cast(cast(alpha as char(*)) || ' ' || cast(delta as char(*))" |
| 3232 |
" as point) as pt," |
| 3233 |
" cast('20 -10 ' || rv as circle) as ci," |
| 3234 |
" cast(cast('20 -10 14' as circle) as point) as cpt," |
| 3235 |
" cast('10 80 120 40 35 -10' as polygon) as poly" |
| 3236 |
" from test.adql where mag<0") |
| 3237 |
# alpha': 290.125, 'delta': 89.0, 'mag': -1.0, 'rV': 28.0 |
| 3238 |
row = res.rows[0] |
| 3239 |
self.assertEqual(res.tableDef.getColumnByName("pt").ucd, "") |
| 3240 |
self.assertAlmostEqual(row["pt"].asDALI()[0], 290.125) |
| 3241 |
self.assertAlmostEqual(row["ci"].asDALI()[-1], 28) |
| 3242 |
self.assertAlmostEqual(row["cpt"].asDALI()[1], -10) |
| 3243 |
self.assertAlmostEqual(row["poly"].asDALI()[4], 35) |
| 3244 |
|
| 3245 |
def testToplevelSetOperation(self): |
| 3246 |
res = self.runQuery("select alpha from test.adql where delta<80" |
| 3247 |
" except select alpha from test.adql where delta<0") |
| 3248 |
self.assertEqual(res.tableDef.columns[0].name, "alpha") |
| 3249 |
self.assertEqual(res.rows, [{'alpha': 2.0}]) |
| 3250 |
|
| 3251 |
|
| 3252 |
class SimpleSTCSTest(testhelpers.VerboseTest): |
| 3253 |
def setUp(self): |
| 3254 |
self.parse = tapstc.getSimpleSTCSParser() |
| 3255 |
|
| 3256 |
def testPosParses(self): |
| 3257 |
res = self.parse("Position 10 20 ") |
| 3258 |
self.assertEqual(res.pgType, "spoint") |
| 3259 |
self.assertAlmostEqual(res.x, 0.174532925199432) |
| 3260 |
self.assertEqual(res.cooSys, "UNKNOWN") |
| 3261 |
|
| 3262 |
def testCircleParses(self): |
| 3263 |
res = self.parse(" Circle ICRS 10 20 1e0") |
| 3264 |
self.assertEqual(res.pgType, "scircle") |
| 3265 |
self.assertEqual(res.cooSys, "ICRS") |
| 3266 |
|
| 3267 |
def testBadCircleRaises(self): |
| 3268 |
self.assertRaisesWithMsg(stc.STCSParseError, |
| 3269 |
'STC-S circles want three numbers.', |
| 3270 |
self.parse, |
| 3271 |
("Circle 2 1",)) |
| 3272 |
|
| 3273 |
def testBoxParses(self): |
| 3274 |
res = self.parse("box TOPOCENTER SPHERICAL2 -10 20 2.1 5.4") |
| 3275 |
self.assertEqual(res.pgType, "spoly") |
| 3276 |
|
| 3277 |
def testPolyParses(self): |
| 3278 |
res = self.parse("PolyGon FK4 TOPOCENTER SPHERICAL2 -10 20 2.1 5.4 1 3") |
| 3279 |
self.assertEqual(res.pgType, "spoly") |
| 3280 |
|
| 3281 |
def testNotParses(self): |
| 3282 |
res = self.parse("NOT (Box ICRS 1 2 3 4)") |
| 3283 |
self.assertTrue(isinstance(res, tapstc.GeomExpr)) |
| 3284 |
self.assertAlmostEqual( |
| 3285 |
testhelpers.pickSingle(res.operands).points[0].x, |
| 3286 |
-0.00872664626) |
| 3287 |
self.assertEqual(res.cooSys, "UNKNOWN") |
| 3288 |
|
| 3289 |
def testSimpleOpParses(self): |
| 3290 |
res = self.parse("UNiON (Box ICRS 1 2 3 4 Circle 1 2 3)") |
| 3291 |
self.assertTrue(isinstance(res, tapstc.GeomExpr)) |
| 3292 |
self.assertEqual(res.operator, "UNION") |
| 3293 |
self.assertEqual(len(res.operands), 2) |
| 3294 |
self.assertEqual(res.operands[0].pgType, "spoly") |
| 3295 |
self.assertEqual(res.operands[1].pgType, "scircle") |
| 3296 |
self.assertEqual(res.cooSys, "UNKNOWN") |
| 3297 |
|
| 3298 |
def testComplexOpParses(self): |
| 3299 |
res = self.parse("INtersection FK4 (" |
| 3300 |
"UNiON BARYCENTER (Box ICRS 1 2 3 4 Circle 1 2 3)" |
| 3301 |
" Polygon ICRS GEOCENTER 2 3 4 5 6 7" |
| 3302 |
" Circle Fk4 spherical2 3 4 5)") |
| 3303 |
self.assertEqual(res.operands[0].operator, "UNION") |
| 3304 |
self.assertEqual(res.operands[1].cooSys, "ICRS") |
| 3305 |
self.assertEqual(res.cooSys, "FK4") |
| 3306 |
|
| 3307 |
def testCartesianRaises(self): |
| 3308 |
self.assertRaisesWithMsg(stc.STCSParseError, |
| 3309 |
'Only SPHERICAL2 STC-S supported here', |
| 3310 |
self.parse, |
| 3311 |
("Position CARTESIAN3 1 2 3",)) |
| 3312 |
|
| 3313 |
|
| 3314 |
class IntersectsFallbackTest(testhelpers.VerboseTest): |
| 3315 |
# Does INTERSECT fall back to CONTAINS? |
| 3316 |
def testArg1(self): |
| 3317 |
ctx, tree = adql.parseAnnotating( |
| 3318 |
"SELECT pt from geo where intersects(pt, circle('ICRS', 2, 2, 1))=1", |
| 3319 |
_getFieldInfoGetter()) |
| 3320 |
funNode = tree.whereClause.children[1].op1 |
| 3321 |
self.assertEqual(funNode.funName, "CONTAINS") |
| 3322 |
self.assertEqual(funNode.args[0].type, "columnReference") |
| 3323 |
self.assertEqual(funNode.args[1].type, "circle") |
| 3324 |
|
| 3325 |
def testArg2(self): |
| 3326 |
ctx, tree = adql.parseAnnotating( |
| 3327 |
"SELECT pt from geo where intersects(circle('ICRS', 2, 2, 1), pt)=1", |
| 3328 |
_getFieldInfoGetter()) |
| 3329 |
funNode = tree.whereClause.children[1].op1 |
| 3330 |
self.assertEqual(funNode.funName, "CONTAINS") |
| 3331 |
self.assertEqual(funNode.args[0].type, "columnReference") |
| 3332 |
self.assertEqual(funNode.args[1].type, "circle") |
| 3333 |
|
| 3334 |
def testExpr(self): |
| 3335 |
ctx, tree = adql.parseAnnotating( |
| 3336 |
"SELECT pt from geo where intersects(" |
| 3337 |
"point('ICRS', 2, 2), circle('ICRS', 2, 2, 1))=1", |
| 3338 |
_getFieldInfoGetter()) |
| 3339 |
funNode = tree.whereClause.children[1].op1 |
| 3340 |
self.assertEqual(funNode.funName, "CONTAINS") |
| 3341 |
self.assertEqual(funNode.args[0].type, "point") |
| 3342 |
|
| 3343 |
def testNotouch(self): |
| 3344 |
ctx, tree = adql.parseAnnotating( |
| 3345 |
"SELECT pt from geo where intersects(" |
| 3346 |
"box('ICRS', 2, 2, 3, 3), circle('ICRS', 2, 2, 1))=1", |
| 3347 |
_getFieldInfoGetter()) |
| 3348 |
funNode = tree.whereClause.children[1].op1 |
| 3349 |
self.assertEqual(funNode.funName, "INTERSECTS") |
| 3350 |
|
| 3351 |
def testJoinCond(self): |
| 3352 |
ctx, tree = adql.parseAnnotating( |
| 3353 |
"SELECT * from geo as a join geo as b on (intersects(" |
| 3354 |
"circle('ICRS', coord1(b.pt), coord2(b.pt), 1), a.pt)=1)", |
| 3355 |
_getFieldInfoGetter()) |
| 3356 |
funNode = tree.fromClause.tableReference.joinSpecification.children[2].op1 |
| 3357 |
self.assertEqual(funNode.funName, "CONTAINS") |
| 3358 |
self.assertEqual(funNode.args[0].fieldInfo.type, "spoint") |
| 3359 |
|
| 3360 |
def testJoinCondGeoCol(self): |
| 3361 |
ctx, tree = adql.parseAnnotating( |
| 3362 |
"SELECT * from geo as a join geo as b on (intersects(" |
| 3363 |
"circle('ICRS', b.pt, 1), a.pt)=1)", |
| 3364 |
_getFieldInfoGetter()) |
| 3365 |
funNode = tree.fromClause.tableReference.joinSpecification.children[2].op1 |
| 3366 |
self.assertEqual(funNode.funName, "CONTAINS") |
| 3367 |
self.assertEqual(funNode.args[0].fieldInfo.type, "spoint") |
| 3368 |
|
| 3369 |
|
| 3370 |
class AnnotationTest(testhelpers.VerboseTest): |
| 3371 |
def testFailing(self): |
| 3372 |
self.assertRaisesWithMsg(adql.AmbiguousColumn, |
| 3373 |
"ra1", |
| 3374 |
adql.parseAnnotating, |
| 3375 |
("SELECT ra1 from spatial WHERE EXISTS (SELECT 1 FROM spatial2 where" |
| 3376 |
" ra1=t)", |
| 3377 |
_getFieldInfoGetter())) |
| 3378 |
|
| 3379 |
def testSucceedingUniqueMatch(self): |
| 3380 |
ctx, tree = adql.parseAnnotating( |
| 3381 |
"SELECT ra1 from spatial as a WHERE EXISTS (SELECT 1 FROM spatial where" |
| 3382 |
" ra1=a.height)", |
| 3383 |
_getFieldInfoGetter()) |
| 3384 |
|
| 3385 |
def testFailingMultiInference(self): |
| 3386 |
class MultiField(nodes.TransparentNode, nodes.FieldInfoedNode): |
| 3387 |
type = "multifield" |
| 3388 |
mf = MultiField(children=[ |
| 3389 |
nodes.GenericValueExpression(children=[4]), |
| 3390 |
nodes.GenericValueExpression(children=[5])]) |
| 3391 |
|
| 3392 |
self.assertRaisesWithMsg(adql.Error, |
| 3393 |
"More than one child with fieldInfo with no behaviour defined in" |
| 3394 |
" MultiField, children [('children', <ADQL Node genericValueExpression>)," |
| 3395 |
" ('children', <ADQL Node genericValueExpression>)]", |
| 3396 |
fieldinfos._annotateNodeRecurse, |
| 3397 |
(mf, annotations.AnnotationContext(_getFieldInfoGetter()))) |
| 3398 |
|
| 3399 |
def testFailingNullInference(self): |
| 3400 |
class MultiField(nodes.TransparentNode, nodes.FieldInfoedNode): |
| 3401 |
type = "multifield" |
| 3402 |
mf = MultiField(children=[]) |
| 3403 |
|
| 3404 |
self.assertRaisesWithMsg(adql.Error, |
| 3405 |
"No child with fieldInfo with no behaviour defined in" |
| 3406 |
" MultiField, children []", |
| 3407 |
fieldinfos._annotateNodeRecurse, |
| 3408 |
(mf, annotations.AnnotationContext(_getFieldInfoGetter()))) |
| 3409 |
|
| 3410 |
|
| 3411 |
if __name__=="__main__": |
| 3412 |
testhelpers.main(STCTest) |