Source

htsql-charset-option / src / htsql / tr / code.py

  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
#
# Copyright (c) 2006-2010, Prometheus Research, LLC
# Authors: Clark C. Evans <cce@clarkevans.com>,
#          Kirill Simonov <xi@resolvent.net>
#


"""
:mod:`htsql.tr.code`
====================

This module declares space and code nodes.
"""


from ..util import maybe, listof, tupleof, Node
from ..mark import Mark
from ..entity import TableEntity, ColumnEntity, Join
from ..domain import Domain, BooleanDomain, VoidDomain
from .binding import Binding, QueryBinding


class Code(Node):

    def __init__(self, mark, hash=None):
        assert isinstance(mark, Mark)
        if hash is None:
            hash = id(self)
        self.mark = mark
        self.hash = hash

    def __hash__(self):
        return hash(self.hash)

    def __eq__(self, other):
        return (isinstance(other, Code) and self.hash == other.hash)


class Space(Code):

    is_axis = False

    def __init__(self, parent, table,
                 is_contracting, is_expanding, mark,
                 hash=None):
        assert isinstance(parent, maybe(Space))
        assert isinstance(table, maybe(TableEntity))
        super(Space, self).__init__(mark, hash=hash)
        self.parent = parent
        self.table = table
        self.is_contracting = is_contracting
        self.is_expanding = is_expanding
        if self.parent is not None:
            self.scalar = self.parent.scalar
        else:
            self.scalar = self

    def unfold(self):
        components = []
        component = self
        while component is not None:
            components.append(component)
            component = component.parent
        return components

    def axes(self):
        space = None
        for component in reversed(self.unfold()):
            if component.is_axis:
                space = component.clone(parent=space)
        return space

    def inflate(self, other):
        self_components = self.unfold()
        other_components = other.unfold()
        space = None
        while self_components and other_components:
            self_component = self_components[-1]
            other_component = other_components[-1]
            if self_component.resembles(other_component):
                if self_component.is_axis:
                    space = self_component.clone(parent=space)
                self_components.pop()
                other_components.pop()
            elif not other_component.is_axis:
                other_components.pop()
            elif not self_component.is_axis:
                space = self_component.clone(parent=space)
                self_components.pop()
            else:
                break
        while self_components:
            component = self_components.pop()
            space = component.clone(parent=space)
        return space

    def spans(self, other):
        if self is other or self == other:
            return True
        self_axes = self.axes().unfold()
        other_axes = other.axes().unfold()
        while self_axes and other_axes:
            if self_axes[-1].resembles(other_axes[-1]):
                self_axes.pop()
                other_axes.pop()
            else:
                break
        for other_axis in other_axes:
            if not other_axis.is_contracting:
                return False
        return True

    def conforms(self, other):
        if self is other or self == other:
            return True
        self_components = self.unfold()
        other_components = other.unfold()
        while self_components and other_components:
            self_component = self_components[-1]
            other_component = other_components[-1]
            if self_component.resembles(other_component):
                self_components.pop()
                other_components.pop()
            elif (self_component.is_contracting and
                  self_component.is_expanding and
                  not self_component.is_axis):
                self_components.pop()
            elif (other_component.is_contrating and
                  other_component.is_expanding and
                  not other_component.is_axis):
                other_components.pop()
            else:
                break
        for component in self_components + other_components:
            if not (component.is_contracting and component.is_expanding):
                return False
        return True

    def dominates(self, other):
        if self is other or self == other:
            return True
        self_components = self.unfold()
        other_components = other.unfold()
        while self_components and other_components:
            self_component = self_components[-1]
            other_component = other_components[-1]
            if self_component.resembles(other_component):
                self_components.pop()
                other_components.pop()
            elif (other_component.is_contrating and
                  not other_component.is_axis):
                other_components.pop()
            else:
                break
        for component in self_components:
            if not component.is_expanding:
                return False
        for component in other_components:
            if not component.is_contracting:
                return False
        return True

    def concludes(self, other):
        if self is other or self == other:
            return True
        space = self
        while space is not None:
            if space == other:
                return True
            space = space.parent
        return False

    def resembles(self, other):
        return False


class ScalarSpace(Space):

    is_axis = True

    def __init__(self, parent, mark):
        assert parent is None
        super(ScalarSpace, self).__init__(None, None, False, False, mark,
                                          hash=(self.__class__))

    def resembles(self, other):
        return isinstance(other, ScalarSpace)


class FreeTableSpace(Space):

    is_axis = True

    def __init__(self, parent, table, mark):
        super(FreeTableSpace, self).__init__(parent, table, True, True, mark,
                                             hash=(self.__class__,
                                                   parent.hash, table))

    def resembles(self, other):
        return isinstance(other, FreeTableSpace)


class JoinedTableSpace(Space):

    is_axis = True

    def __init__(self, parent, join, mark):
        assert isinstance(join, Join)
        super(JoinedTableSpace, self).__init__(parent, join.target,
                                               join.is_contracting,
                                               join.is_expanding,
                                               mark,
                                               hash=(self.__class__,
                                                     parent.hash,
                                                     join.__class__,
                                                     join.foreign_key))
        self.join = join

    def resembles(self, other):
        return (isinstance(other, JoinedTableSpace) and
                self.join is other.join)


class ScreenSpace(Space):

    def __init__(self, parent, filter, mark):
        assert isinstance(filter, Code)
        assert isinstance(filter.domain, BooleanDomain)
        super(ScreenSpace, self).__init__(parent, parent.table,
                                          True, False, mark,
                                          hash=(self.__class__,
                                                parent.hash,
                                                filter.hash))
        self.filter = filter

    def resembles(self, other):
        return (isinstance(other, ScreenSpace) and
                self.filter == other.filter)


class RelativeSpace(Space):

    def __init__(self, parent, filter, mark):
        assert isinstance(filter, Space)
        super(RelativeSpace, self).__init__(parent, parent.table,
                                            True, False, mark,
                                            hash=(self.__class__,
                                                  parent.hash,
                                                  filter.hash))
        self.filter = filter

    def resembles(self, other):
        return (isinstance(other, RelativeSpace) and
                self.filter == other.filter)


class OrderedSpace(Space):

    def __init__(self, parent, order, limit, offset, mark):
        assert isinstance(order, listof(tupleof(Expression, int)))
        assert isinstance(limit, maybe(int))
        assert isinstance(offset, maybe(int))
        is_expanding = (limit is None and offset is None)
        super(OrderedSpace, self).__init__(parent, parent.table,
                                           True, is_expanding, mark,
                                           hash=(self.__class__,
                                                 parent.hash,
                                                 tuple(order),
                                                 limit, offset))
        self.order = order
        self.limit = limit
        self.offset = offset

    def resembles(self, other):
        return (isinstance(other, OrderedSpace) and
                self.other == other.order and
                self.limit == other.limit and
                self.offset == other.offset)


class Expression(Code):

    def __init__(self, domain, mark, hash=None):
        assert isinstance(domain, Domain)
        super(Expression, self).__init__(mark, hash=hash)
        self.domain = domain

    def get_units(self):
        return []


class LiteralExpression(Expression):

    def __init__(self, value, domain, mark):
        super(LiteralExpression, self).__init__(domain, mark,
                                                hash=(self.__class__,
                                                      value, domain))
        self.value = value


class EqualityExpression(Expression):

    def __init__(self, left, right, mark):
        assert isinstance(left, Expression)
        assert isinstance(right, Expression)
        domain = BooleanDomain()
        super(EqualityExpression, self).__init__(domain, mark,
                                                 hash=(self.__class__,
                                                       left.hash,
                                                       right.hash))
        self.left = left
        self.right = right

    def get_units(self):
        return self.left.get_units()+self.right.get_units()


class InequalityExpression(Expression):

    def __init__(self, left, right, mark):
        assert isinstance(left, Expression)
        assert isinstance(right, Expression)
        domain = BooleanDomain()
        super(InequalityExpression, self).__init__(domain, mark,
                                                   hash=(self.__class__,
                                                         left.hash,
                                                         right.hash))
        self.left = left
        self.right = right

    def get_units(self):
        return self.left.get_units()+self.right.get_units()


class ConjunctionExpression(Expression):

    def __init__(self, terms, mark):
        assert isinstance(terms, listof(Expression))
        domain = BooleanDomain()
        hash = (self.__class__, tuple(term.hash for term in terms))
        super(ConjunctionExpression, self).__init__(domain, mark, hash=hash)
        self.terms = terms

    def get_units(self):
        units = []
        for term in self.terms:
            units.extend(term.get_units())
        return units


class DisjunctionExpression(Expression):

    def __init__(self, terms, mark):
        assert isinstance(terms, listof(Expression))
        domain = BooleanDomain()
        hash = (self.__class__, tuple(term.hash for term in terms))
        super(DisjunctionExpression, self).__init__(domain, mark, hash=hash)
        self.terms = terms

    def get_units(self):
        units = []
        for term in self.terms:
            units.extend(term.get_units())
        return units


class NegationExpression(Expression):

    def __init__(self, term, mark):
        assert isinstance(term, Expression)
        domain = BooleanDomain()
        hash = (self.__class__, term.hash)
        super(NegationExpression, self).__init__(domain, mark, hash=hash)
        self.term = term

    def get_units(self):
        return self.term.get_units()


class TupleExpression(Expression):

    def __init__(self, space, mark):
        assert space.table is not None
        assert space.table.primary_key is not None
        super(TupleExpression, self).__init__(BooleanDomain(), mark,
                                              hash=(self.__class__,
                                                    space.hash))
        self.space = space
        columns = [space.table.columns[name]
                   for name in space.table.primary_key.origin_column_names]
        self.units = [ColumnUnit(column, space, mark) for column in columns]

    def get_units(self):
        return self.units


class CastExpression(Expression):

    def __init__(self, code, domain, mark):
        super(CastExpression, self).__init__(domain, mark,
                                             hash=(self.__class__, domain))
        self.code = code

    def get_units(self):
        return self.code.get_units()


class ElementExpression(Expression):

    def __init__(self, code):
        assert isinstance(code, Code)
        super(ElementExpression, self).__init__(code.domain, code.mark)
        self.code = code

    def get_units(self):
        return self.code.get_units()


class FunctionExpression(Expression):

    def __init__(self, domain, mark, **arguments):
        arguments_hash = []
        for key in sorted(arguments):
            value = arguments[key]
            if isinstance(value, list):
                value = tuple(item.hash for item in value)
            elif value is not None:
                value = value.hash
            arguments_hash.append((key, value))
        hash = (self.__class__, tuple(arguments_hash))
        super(FunctionExpression, self).__init__(domain, mark, hash=hash)
        self.arguments = arguments
        for key in arguments:
            setattr(self, key, arguments[key])

    def get_units(self):
        units = []
        for key in sorted(self.arguments):
            value = self.arguments[key]
            if isinstance(value, list):
                for item in value:
                    units.extend(item.get_units())
            elif value is not None:
                units.extend(value.get_units())
        return units


class Unit(Expression):

    def __init__(self, domain, space, mark, hash=None):
        assert isinstance(space, Space)
        super(Unit, self).__init__(domain, mark, hash=hash)
        self.space = space

    def get_units(self):
        return [self]


class ColumnUnit(Unit):

    def __init__(self, column, space, mark):
        assert isinstance(column, ColumnEntity)
        super(ColumnUnit, self).__init__(column.domain, space, mark,
                                         hash=(self.__class__,
                                               column, space.hash))
        self.column = column


class AggregateUnit(Unit):

    def __init__(self, expression, plural_space, space, mark):
        assert isinstance(expression, Expression)
        assert isinstance(plural_space, Space)
        super(AggregateUnit, self).__init__(expression.domain, space, mark,
                                            hash=(self.__class__,
                                                  expression.hash,
                                                  plural_space.hash,
                                                  space.hash))
        self.expression = expression
        self.plural_space = plural_space
        self.space = space


class QueryCode(Code):

    def __init__(self, binding, segment, mark):
        assert isinstance(binding, QueryBinding)
        assert isinstance(segment, maybe(SegmentCode))
        super(QueryCode, self).__init__(mark)
        self.binding = binding
        self.syntax = binding.syntax
        self.segment = segment


class SegmentCode(Code):

    def __init__(self, space, elements, mark):
        assert isinstance(space, Space)
        assert isinstance(elements, listof(Expression))
        super(SegmentCode, self).__init__(mark)
        self.space = space
        self.elements = elements