htsql-firebird / src / htsql_tweak / override / pattern.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
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
#
# Copyright (c) 2006-2011, Prometheus Research, LLC
# See `LICENSE` for license information, `AUTHORS` for the list of authors.
#


from htsql.context import context
from htsql.util import Printable, listof, maybe
from htsql.validator import Validator
from htsql.entity import (NamedEntity, SchemaEntity,
                          TableEntity, ColumnEntity, Join, DirectJoin,
                          ReverseJoin)
from htsql.model import (Node, HomeNode, TableNode, TableArc, ColumnArc,
                         ChainArc, SyntaxArc)
from htsql.introspect import introspect
from htsql.classify import normalize
from htsql.tr.parse import parse, GroupParser, TopParser
from htsql.tr.syntax import Syntax
from htsql.tr.bind import BindByName
from htsql.tr.binding import SubstitutionRecipe, ClosedRecipe
from htsql.tr.error import TranslateError
import fnmatch
import re
import weakref


def matches(entity, pattern):
    assert isinstance(entity, maybe(NamedEntity))
    assert isinstance(pattern, maybe(unicode))
    if entity is None:
        return (pattern is None)
    if pattern is None:
        return True
    name = normalize(entity.name) if entity.name else ""
    return fnmatch.fnmatchcase(name, pattern)


class Pattern(Printable):

    def __unicode__(self):
        raise NotImplementedError()

    def __str__(self):
        return unicode(self).encode('utf-8')


class TablePattern(Pattern):

    def __init__(self, schema_pattern, table_pattern):
        assert isinstance(schema_pattern, maybe(unicode))
        assert isinstance(table_pattern, unicode)
        self.schema_pattern = schema_pattern
        self.table_pattern = table_pattern

    def matches(self, entity):
        assert isinstance(entity, (SchemaEntity, TableEntity))
        if isinstance(entity, SchemaEntity):
            return matches(entity, self.schema_pattern)
        return (matches(entity.schema, self.schema_pattern) and
                matches(entity, self.table_pattern))

    def __unicode__(self):
        if self.schema_pattern is not None:
            return u"%s.%s" % (self.schema_pattern, self.table_pattern)
        return self.table_pattern


class ColumnPattern(Pattern):

    def __init__(self, schema_pattern, table_pattern, column_pattern):
        assert isinstance(schema_pattern, maybe(unicode))
        assert isinstance(table_pattern, maybe(unicode))
        assert isinstance(column_pattern, unicode)
        self.schema_pattern = schema_pattern
        self.table_pattern = table_pattern
        self.column_pattern = column_pattern

    def matches(self, entity):
        assert isinstance(entity, (SchemaEntity, TableEntity, ColumnEntity))
        if isinstance(entity, SchemaEntity):
            return matches(entity, self.schema_pattern)
        if isinstance(entity, TableEntity):
            return (matches(entity.schema, self.schema_pattern) and
                    matches(entity, self.table_pattern))
        return (matches(entity.table.schema, self.schema_pattern) and
                matches(entity.table, self.table_pattern) and
                matches(entity, self.column_pattern))

    def __unicode__(self):
        chunks = []
        if self.schema_pattern is not None:
            chunks.append(self.schema_pattern)
        if self.table_pattern is not None:
            chunks.append(self.table_pattern)
        chunks.append(self.column_pattern)
        return u".".join(chunks)


class UniqueKeyPattern(Pattern):

    def __init__(self, schema_pattern, table_pattern, column_patterns,
                 is_primary, is_partial):
        assert isinstance(schema_pattern, maybe(unicode))
        assert isinstance(table_pattern, unicode)
        assert isinstance(column_patterns, listof(unicode))
        assert len(column_patterns) > 0
        assert isinstance(is_primary, bool)
        assert isinstance(is_partial, bool)
        assert not (is_primary and is_partial)
        self.schema_pattern = schema_pattern
        self.table_pattern = table_pattern
        self.column_patterns = column_patterns
        self.is_primary = is_primary
        self.is_partial = is_partial

    def matches(self, entity):
        assert isinstance(entity, (SchemaEntity, TableEntity))
        if isinstance(entity, SchemaEntity):
            return matches(entity, self.schema_pattern)
        return (matches(entity.schema, self.schema_pattern) and
                matches(entity, self.table_pattern))

    def extract(self, table):
        assert isinstance(table, TableEntity)
        assert self.matches(table)
        columns = []
        for pattern in self.column_patterns:
            matching = [column for column in table.columns
                               if matches(column, pattern)]
            if len(matching) != 1:
                return
            [column] = matching
            if column in columns:
                return
            columns.append(column)
        return columns

    def __unicode__(self):
        chunks = []
        if self.schema_pattern is not None:
            chunks.append(self.schema_pattern)
            chunks.append(u".")
        chunks.append(self.table_pattern)
        chunks.append(u"(%s)" % ",".join(self.column_patterns))
        if self.is_primary:
            chunks.append(u"!")
        if self.is_partial:
            chunks.append(u"?")
        return u"".join(chunks)


class ForeignKeyPattern(Pattern):

    def __init__(self, schema_pattern, table_pattern, column_patterns,
                 target_schema_pattern, target_table_pattern,
                 target_column_patterns, is_partial):
        assert isinstance(schema_pattern, maybe(unicode))
        assert isinstance(table_pattern, unicode)
        assert isinstance(column_patterns, listof(unicode))
        assert len(column_patterns) > 0
        assert isinstance(target_schema_pattern, maybe(unicode))
        assert isinstance(target_table_pattern, unicode)
        assert isinstance(target_column_patterns, maybe(listof(unicode)))
        assert (target_column_patterns is None or
                len(target_column_patterns) == len(column_patterns))
        assert isinstance(is_partial, bool)
        self.schema_pattern = schema_pattern
        self.table_pattern = table_pattern
        self.column_patterns = column_patterns
        self.target_schema_pattern = target_schema_pattern
        self.target_table_pattern = target_table_pattern
        self.target_column_patterns = target_column_patterns
        self.is_partial = is_partial

    def matches(self, entity):
        assert isinstance(entity, (SchemaEntity, TableEntity))
        if isinstance(entity, SchemaEntity):
            return matches(entity, self.schema_pattern)
        return (matches(entity.schema, self.schema_pattern) and
                matches(entity, self.table_pattern))

    def matches_target(self, entity):
        assert isinstance(entity, (SchemaEntity, TableEntity))
        if isinstance(entity, SchemaEntity):
            return matches(entity, self.target_schema_pattern)
        return (matches(entity.schema, self.target_schema_pattern) and
                matches(entity, self.target_table_pattern))

    def extract(self, table):
        assert isinstance(table, TableEntity)
        assert self.matches(table)
        columns = []
        for pattern in self.column_patterns:
            matching = [column for column in table.columns
                               if matches(column, pattern)]
            if len(matching) != 1:
                return
            [column] = matching
            if column in columns:
                return
            columns.append(column)
        return columns

    def extract_target(self, table):
        assert isinstance(table, TableEntity)
        assert self.matches_target(table)
        columns = None
        if self.target_column_patterns:
            columns = []
            for pattern in self.target_column_patterns:
                matching = [column for column in table.columns
                                   if matches(column, pattern)]
                if len(matching) != 1:
                    return
                [column] = matching
                if column in columns:
                    return
                columns.append(column)
        else:
            if table.primary_key:
                columns = table.primary_key.origin_columns
                if len(columns) != len(self.column_patterns):
                    return
        return columns

    def __unicode__(self):
        chunks = []
        if self.schema_pattern is not None:
            chunks.append(self.schema_pattern)
            chunks.append(u".")
        chunks.append(self.table_pattern)
        chunks.append(u"(%s)" % u",".join(self.column_patterns))
        if self.is_partial:
            chunks.append("?")
        chunks.append(" -> ")
        if self.target_schema_pattern is not None:
            chunks.append(self.target_schema_pattern)
            chunks.append(u".")
        chunks.append(self.target_table_pattern)
        if self.target_column_patterns is not None:
            chunks.append(u"(%s)" % u",".join(self.target_column_patterns))
        return u"".join(chunks)


class ArcPattern(Pattern):

    is_column = False
    is_table = False
    is_chain = False
    is_syntax = False

    def matches(self, arc):
        return False


class ColumnArcPattern(ArcPattern):

    is_column = True

    def __init__(self, column_pattern):
        assert isinstance(column_pattern, unicode)
        self.column_pattern = column_pattern

    def extract(self, node, parameters):
        assert isinstance(node, Node)
        if not isinstance(node, TableNode):
            return
        if parameters is not None:
            return
        matched_column = None
        for column in node.table.columns:
            if not matches(column, self.column_pattern):
                continue
            if matched_column is not None:
                return
            matched_column = column
        if matched_column is None:
            return
        return ColumnArc(node.table, matched_column)

    def __unicode__(self):
        return self.column_pattern


class TableArcPattern(ArcPattern):

    is_table = True

    def __init__(self, schema_pattern, table_pattern):
        assert isinstance(schema_pattern, maybe(unicode))
        assert isinstance(table_pattern, unicode)
        self.schema_pattern = schema_pattern
        self.table_pattern = table_pattern

    def extract(self, node, parameters):
        assert isinstance(node, Node)
        if not isinstance(node, HomeNode):
            return
        if parameters is not None:
            return
        catalog = introspect()
        matched_table = None
        for schema in catalog.schemas:
            if not matches(schema, self.schema_pattern):
                continue
            for table in schema.tables:
                if not matches(table, self.table_pattern):
                    continue
                if matched_table is not None:
                    return
                matched_table = table
        if matched_table is None:
            return
        return TableArc(matched_table)

    def __unicode__(self):
        if self.schema_pattern is not None:
            return u"%s.%s" % (self.schema_pattern, self.schema_pattern)
        return self.table_pattern


class JoinPattern(Pattern):

    def __init__(self, schema_pattern, table_pattern, column_patterns,
                 target_schema_pattern, target_table_pattern,
                 target_column_patterns):
        assert isinstance(schema_pattern, maybe(unicode))
        assert isinstance(table_pattern, unicode)
        assert isinstance(column_patterns, maybe(listof(unicode)))
        assert column_patterns is None or len(column_patterns) > 0
        assert isinstance(target_schema_pattern, maybe(unicode))
        assert isinstance(target_table_pattern, unicode)
        assert isinstance(target_column_patterns, maybe(listof(unicode)))
        assert (target_column_patterns is None or
                len(target_column_patterns) > 0)
        assert (column_patterns is None or target_column_patterns is None or
                len(column_patterns) == len(target_column_patterns))
        self.schema_pattern = schema_pattern
        self.table_pattern = table_pattern
        self.column_patterns = column_patterns
        self.target_schema_pattern = target_schema_pattern
        self.target_table_pattern = target_table_pattern
        self.target_column_patterns = target_column_patterns

    def matches(self, join):
        assert isinstance(join, Join)
        return (matches(join.origin.schema, self.schema_pattern) and
                matches(join.origin, self.table_pattern) and
                (self.column_patterns is None or
                    (len(join.origin_columns) == len(self.column_patterns) and
                     all(matches(column, pattern)
                         for column, pattern in zip(join.origin_columns,
                                                    self.column_patterns)))) and
                matches(join.target.schema, self.target_schema_pattern) and
                matches(join.target, self.target_table_pattern) and
                (self.target_column_patterns is None or
                    (len(join.target_columns)
                        == len(self.target_column_patterns) and
                     all(matches(column, pattern)
                         for column, pattern
                                in zip(join.target_columns,
                                       self.target_column_patterns)))))

    def extract(self, node):
        assert isinstance(node, TableNode)
        matched_join = None
        for is_direct, foreign_keys in [(True, node.table.foreign_keys),
                                (False, node.table.referring_foreign_keys)]:
            for foreign_key in foreign_keys:
                if is_direct:
                    join = DirectJoin(foreign_key)
                else:
                    join = ReverseJoin(foreign_key)
                if not self.matches(join):
                    continue
                if matched_join is not None:
                    return
                matched_join = join
        if matched_join is None:
            return
        return matched_join

    def __unicode__(self):
        chunks = []
        if self.schema_pattern is not None:
            chunks.append(self.schema_pattern)
            chunks.append(u".")
        chunks.append(self.table_pattern)
        if self.column_patterns is not None:
            chunks.append(u"(%s)" % u",".join(self.column_patterns))
        chunks.append(" -> ")
        if self.target_schema_pattern is not None:
            chunks.append(self.target_schema_pattern)
            chunks.append(u".")
        chunks.append(self.target_table_pattern)
        if self.target_column_patterns is not None:
            chunks.append(u"(%s)" % u",".join(self.target_column_patterns))
        return u"".join(chunks)


class ChainArcPattern(ArcPattern):

    is_chain = True

    def __init__(self, join_patterns):
        assert (isinstance(join_patterns, listof(JoinPattern))
                and len(join_patterns) > 0)
        self.join_patterns = join_patterns

    def extract(self, node, parameters):
        assert isinstance(node, Node)
        if not isinstance(node, TableNode):
            return
        if parameters is not None:
            return
        table = node.table
        joins = []
        for pattern in self.join_patterns:
            join = pattern.extract(node)
            if join is None:
                return
            joins.append(join)
            node = TableNode(join.target)
        return ChainArc(table, joins)

    def __unicode__(self):
        return u", ".join(unicode(pattern) for pattern in self.join_patterns)


class SyntaxArcPattern(ArcPattern):

    is_syntax = True

    def __init__(self, syntax):
        assert isinstance(syntax, Syntax)
        self.syntax = syntax

    def extract(self, node, parameters):
        assert isinstance(node, Node)
        return SyntaxArc(node, parameters, self.syntax)

    def __unicode__(self):
        return unicode(self.syntax)


class BindGlobal(BindByName):

    app = None
    parameters = None
    body = None

    @classmethod
    def active(component):
        if component.app is None:
            return super(BindGlobal, component).active()
        return (component.app() is context.app)

    def __call__(self):
        recipe = SubstitutionRecipe(self.state.scope, [],
                                    self.parameters, self.body)
        recipe = ClosedRecipe(recipe)
        return self.state.use(recipe, self.syntax)


class GlobalPattern(ArcPattern):

    def __init__(self, syntax):
        assert isinstance(syntax, Syntax)
        self.syntax = syntax

    def register(self, app, name, parameters):
        assert isinstance(name, unicode)
        class_name = "Bind%s" % name.title().replace('_', '').encode('utf-8')
        arity = None
        if parameters is not None:
            arity = len(parameters)
            parameters = list(parameters)
        namespace = {
            'app': weakref.ref(app),
            'names': [(name.encode('utf-8'), arity)],
            'parameters': parameters,
            'body': self.syntax,
        }
        bind_class = type(class_name, (BindGlobal,), namespace)
        return bind_class

    def __unicode__(self):
        return unicode(self.syntax)


class TablePatternVal(Validator):

    pattern = r"""
        ^
        (?: (?P<schema> [\w*?]+ ) \s*\.\s* )?
        (?P<table> [\w*?]+ )
        $
    """
    regexp = re.compile(pattern, re.X|re.U)

    def __call__(self, value):
        if value is None:
            return ValueError("the null value is not permitted")
        if isinstance(value, str):
            value = value.decode('utf-8', 'replace')
        if isinstance(value, unicode):
            match = self.regexp.match(value)
            if match is None:
                raise ValueError("expected table pattern, got %r"
                                 % value.encode('utf-8'))
            schema_pattern = match.group('schema')
            if schema_pattern is not None:
                schema_pattern = schema_pattern.lower()
            table_pattern = match.group('table').lower()
            value = TablePattern(schema_pattern, table_pattern)
        if not isinstance(value, TablePattern):
            raise ValueError("expected table pattern, got %r" % value)
        return value


class ColumnPatternVal(Validator):

    pattern = r"""
        ^
        (?: (?: (?P<schema> [\w*?]+ ) \s*\.\s* )?
            (?P<table> [\w*?]+ ) \s*\.\s* )?
        (?P<column> [\w*?]+ )
        $
    """
    regexp = re.compile(pattern, re.X|re.U)

    def __call__(self, value):
        if value is None:
            return ValueError("the null value is not permitted")
        if isinstance(value, str):
            value = value.decode('utf-8', 'replace')
        if isinstance(value, unicode):
            match = self.regexp.match(value)
            if match is None:
                raise ValueError("expected column pattern, got %r"
                                 % value.encode('utf-8'))
            schema_pattern = match.group('schema')
            if schema_pattern is not None:
                schema_pattern = schema_pattern.lower()
            table_pattern = match.group('table')
            if table_pattern is not None:
                table_pattern = table_pattern.lower()
            column_pattern = match.group('column').lower()
            value = ColumnPattern(schema_pattern, table_pattern, column_pattern)
        if not isinstance(value, ColumnPattern):
            raise ValueError("expected column pattern, got %r" % value)
        return value


class UniqueKeyPatternVal(Validator):

    pattern = r"""
        ^
        (?: (?P<schema> [\w*?]+ ) \s*\.\s* )?
        (?P<table> [\w*?]+ )
        \s*
        \(
           \s* (?P<columns> [\w*?]+ (?: \s*,\s* [\w*?]+ )* ) \s*,?\s*
        \)
        \s*
        (?: (?P<primary> ! ) | (?P<partial> \? ) )?
        $
    """
    regexp = re.compile(pattern, re.X|re.U)

    def __call__(self, value):
        if value is None:
            return ValueError("the null value is not permitted")
        if isinstance(value, str):
            value = value.decode('utf-8', 'replace')
        if isinstance(value, unicode):
            match = self.regexp.match(value)
            if match is None:
                raise ValueError("expected unique key pattern, got %r"
                                 % value.encode('utf-8'))
            schema_pattern = match.group('schema')
            if schema_pattern is not None:
                schema_pattern = schema_pattern.lower()
            table_pattern = match.group('table').lower()
            column_patterns = match.group('columns').lower()
            column_patterns = [pattern.strip()
                               for pattern in column_patterns.split(",")
                               if pattern.strip()]
            is_primary = bool(match.group('primary'))
            is_partial = bool(match.group('partial'))
            value = UniqueKeyPattern(schema_pattern, table_pattern,
                                     column_patterns, is_primary, is_partial)
        if not isinstance(value, UniqueKeyPattern):
            raise ValueError("expected unique key pattern, got %r" % value)
        return value


class ForeignKeyPatternVal(Validator):

    pattern = r"""
        ^
        (?: (?P<schema> [\w*?]+ ) \s*\.\s* )?
        (?P<table> [\w*?]+ )
        \s*
        \(
           \s* (?P<columns> [\w*?]+ (?: \s*,\s* [\w*?]+ )* ) \s*,?\s*
        \)
        \s* (?P<partial> \? )?
        \s* -> \s*
        (?: (?P<target_schema> [\w*?]+ ) \s*\.\s* )?
        (?P<target_table> [\w*?]+ )
        \s*
        (?: \(
           \s* (?P<target_columns> [\w*?]+ (?: \s*,\s* [\w*?]+ )* ) \s*,?\s*
        \) )?
        $
    """
    regexp = re.compile(pattern, re.X|re.U)

    def __call__(self, value):
        if value is None:
            return ValueError("the null value is not permitted")
        if isinstance(value, str):
            value = value.decode('utf-8', 'replace')
        if isinstance(value, unicode):
            match = self.regexp.match(value)
            if match is None:
                raise ValueError("expected foreign key pattern, got %r"
                                 % value.encode('utf-8'))
            schema_pattern = match.group('schema')
            if schema_pattern is not None:
                schema_pattern = schema_pattern.lower()
            table_pattern = match.group('table').lower()
            column_patterns = match.group('columns').lower()
            column_patterns = [pattern.strip()
                               for pattern in column_patterns.split(",")
                               if pattern.strip()]
            target_schema_pattern = match.group('target_schema')
            if target_schema_pattern is not None:
                target_schema_pattern = target_schema_pattern.lower()
            target_table_pattern = match.group('target_table').lower()
            target_column_patterns = match.group('target_columns')
            if target_column_patterns is not None:
                target_column_patterns = \
                        [pattern.strip().lower()
                         for pattern in target_column_patterns.split(",")
                         if pattern.strip()]
                if len(target_column_patterns) != len(column_patterns):
                    raise ValueError("origin and target columns do not match"
                                     " in foreign key pattern %r"
                                     % value.encode('utf-8'))
            is_partial = bool(match.group('partial'))
            value = ForeignKeyPattern(schema_pattern, table_pattern,
                        column_patterns, target_schema_pattern,
                        target_table_pattern, target_column_patterns,
                        is_partial)
        if not isinstance(value, ForeignKeyPattern):
            raise ValueError("expected foreign key pattern, got %r" % value)
        return value


class ClassPatternVal(Validator):

    pattern = r"""
        ^ (?:
        (?P<is_table>
            (?: (?P<schema> [\w*?]+ ) \s*\.\s* )?
            (?P<table> [\w*?]+ ) )
        |
        (?P<is_syntax>
            (?P<syntax> \( .+ \) ) )
        ) $
    """
    regexp = re.compile(pattern, re.X|re.U)

    def __call__(self, value):
        if value is None:
            return ValueError("the null value is not permitted")
        if isinstance(value, str):
            value = value.decode('utf-8', 'replace')
        if isinstance(value, unicode):
            match = self.regexp.match(value)
            if match is None:
                raise ValueError("expected class pattern, got %r"
                                 % value.encode('utf-8'))
            if match.group('is_table'):
                schema_pattern = match.group('schema')
                if schema_pattern is not None:
                    schema_pattern = schema_pattern.lower()
                table_pattern = match.group('table').lower()
                value = TableArcPattern(schema_pattern, table_pattern)
            elif match.group('is_syntax'):
                input = match.group('syntax')
                try:
                    syntax = parse(input, GroupParser)
                except TranslateError, exc:
                    raise ValueError(str(exc))
                value = SyntaxArcPattern(syntax)
            else:
                assert False
        if not isinstance(value, ArcPattern):
            raise ValueError("expected class pattern, got %r" % value)
        return value


class FieldPatternVal(Validator):

    pattern = r"""
        ^ (?:
        (?P<is_column>
            (?P<column> [\w*?]+ ) )
        |
        (?P<is_chain>
            (?: [\w*?]+ \s*\.\s* )? [\w*?]+
            \s* (?: \( \s* [\w*?]+ (?: \s*,\s* [\w*?]+ )* \s*,?\s* \) )?
            \s* -> \s*
            (?: [\w*?]+ \s*\.\s* )? [\w*?]+
            \s* (?: \( \s* [\w*?]+ (?: \s*,\s* [\w*?]+ )* \s*,?\s* \) )?
            (?: \s*,\s*
                (?: [\w*?]+ \s*\.\s* )? [\w*?]+
                \s* (?: \( \s* [\w*?]+ (?: \s*,\s* [\w*?]+ )* \s*,?\s* \) )?
                \s* -> \s*
                (?: [\w*?]+ \s*\.\s* )? [\w*?]+
                \s* (?: \( \s* [\w*?]+ (?: \s*,\s* [\w*?]+ )* \s*,?\s* \) )?
                \s*,?\s* )* )
        |
        (?P<is_syntax>
            (?P<syntax> \( .+ \) ) )
        ) $
    """
    regexp = re.compile(pattern, re.X|re.U)
    join_pattern = r"""
        (?: (?P<schema> [\w*?]+ ) \s*\.\s* )?
        (?P<table> [\w*?]+ )
        \s*
        (?: \(
           \s* (?P<columns> [\w*?]+ (?: \s*,\s* [\w*?]+ )* ) \s*,?\s*
        \) )?
        \s* -> \s*
        (?: (?P<target_schema> [\w*?]+ ) \s*\.\s* )?
        (?P<target_table> [\w*?]+ )
        \s*
        (?: \(
           \s* (?P<target_columns> [\w*?]+ (?: \s*,\s* [\w*?]+ )* ) \s*,?\s*
        \) )?
        \s*,?\s*
    """
    join_regexp = re.compile(join_pattern, re.X|re.U)

    def __call__(self, value):
        if value is None:
            return ValueError("the null value is not permitted")
        if isinstance(value, str):
            value = value.decode('utf-8', 'replace')
        if isinstance(value, unicode):
            match = self.regexp.match(value)
            if match is None:
                raise ValueError("expected field pattern, got %r"
                                 % value.encode('utf-8'))
            if match.group('is_column'):
                column_pattern = match.group('column').lower()
                value = ColumnArcPattern(column_pattern)
            elif match.group('is_chain'):
                join_patterns = []
                start = 0
                while start < len(value):
                    match = self.join_regexp.match(value, start)
                    assert match is not None
                    schema_pattern = match.group('schema')
                    if schema_pattern is not None:
                        schema_pattern = schema_pattern.lower()
                    table_pattern = match.group('table').lower()
                    column_patterns = match.group('columns')
                    if column_patterns is not None:
                        column_patterns = \
                                [pattern.strip().lower()
                                 for pattern in column_patterns.split(",")
                                 if pattern.strip()]
                    target_schema_pattern = match.group('target_schema')
                    if target_schema_pattern is not None:
                        target_schema_pattern = target_schema_pattern.lower()
                    target_table_pattern = match.group('target_table').lower()
                    target_column_patterns = match.group('target_columns')
                    if target_column_patterns is not None:
                        target_column_patterns = \
                                [pattern.strip().lower()
                                 for pattern in target_column_patterns.split(",")
                                 if pattern.strip()]
                    if (column_patterns is not None and
                            target_column_patterns is not None and
                            len(column_patterns) != len(target_column_patterns)):
                        raise ValueError("origin and target columns do not match"
                                         " in join pattern %r"
                                         % value.encode('utf-8'))
                    join_pattern = JoinPattern(schema_pattern, table_pattern,
                                               column_patterns,
                                               target_schema_pattern,
                                               target_table_pattern,
                                               target_column_patterns)
                    join_patterns.append(join_pattern)
                    start = match.end()
                value = ChainArcPattern(join_patterns)
            elif match.group('is_syntax'):
                input = match.group('syntax')
                try:
                    syntax = parse(input, GroupParser)
                except TranslateError, exc:
                    raise ValueError(str(exc))
                value = SyntaxArcPattern(syntax)
            else:
                assert False
        if not isinstance(value, ArcPattern):
            raise ValueError("expected field pattern, got %r" % value)
        return value


class GlobalPatternVal(Validator):

    def __call__(self, value):
        if value is None:
            return ValueError("the null value is not permitted")
        if isinstance(value, str):
            value = value.decode('utf-8', 'replace')
        if isinstance(value, unicode):
            try:
                syntax = parse(value, TopParser)
            except TranslateError, exc:
                raise ValueError(str(exc))
            value = GlobalPattern(syntax)
        if not isinstance(value, GlobalPattern):
            raise ValueError("expected global pattern, got %r" % value)
        return value


class LabelVal(Validator):

    pattern = """
        ^
        (?P<label> \w+ )
        \s*
        (?: \( \s*
            (?P<parameters> (?: \$?\w+ (?: \s*,\s* \$?\w+ )* \s*,? )? )
        \s* \) )?
        $
    """
    regexp = re.compile(pattern, re.X|re.U)

    def __call__(self, value):
        if value is None:
            return ValueError("the null value is not permitted")
        if isinstance(value, str):
            value = value.decode('utf-8', 'replace')
        if isinstance(value, unicode):
            match = self.regexp.match(value)
            if match is None:
                raise ValueError("expected label, got %r"
                                 % value.encode('utf-8'))
            label = normalize(match.group('label'))
            parameters = None
            if match.group('parameters') is not None:
                parameters = []
                for parameter in match.group('parameters').split(','):
                    name = parameter.strip()
                    if not name:
                        continue
                    is_reference = False
                    if name.startswith(u"$"):
                        is_reference = True
                        name = name[1:]
                    name = normalize(name)
                    parameters.append((name, is_reference))
                parameters = tuple(parameters)
            value = (label, parameters)
        else:
            raise ValueError("expected label, got %r" % value)
        return value


class QLabelVal(Validator):

    pattern = """
        ^
        (?P<qualifier> \w+ )
        \s*\.\s* (?P<label> \w+ )
        \s*
        (?: \( \s*
            (?P<parameters> (?: \$?\w+ (?: \s*,\s* \$?\w+ )* \s*,? )? )
        \s* \) )?
        $
    """
    regexp = re.compile(pattern, re.X|re.U)

    def __call__(self, value):
        if value is None:
            return ValueError("the null value is not permitted")
        if isinstance(value, str):
            value = value.decode('utf-8', 'replace')
        if isinstance(value, unicode):
            match = self.regexp.match(value)
            if match is None:
                raise ValueError("expected label, got %r"
                                 % value.encode('utf-8'))
            qualifier = normalize(match.group('qualifier'))
            label = normalize(match.group('label'))
            parameters = None
            if match.group('parameters') is not None:
                parameters = []
                for parameter in match.group('parameters').split(','):
                    name = parameter.strip()
                    if not name:
                        continue
                    is_reference = False
                    if name.startswith(u"$"):
                        is_reference = True
                        name = name[1:]
                    name = normalize(name)
                    parameters.append((name, is_reference))
                parameters = tuple(parameters)
            value = (qualifier, label, parameters)
        else:
            raise ValueError("expected label, got %r" % value)
        return value
Tip: Filter by directory path e.g. /media app.js to search for public/media/app.js.
Tip: Use camelCasing e.g. ProjME to search for ProjectModifiedEvent.java.
Tip: Filter by extension type e.g. /repo .js to search for all .js files in the /repo directory.
Tip: Separate your search with spaces e.g. /ssh pom.xml to search for src/ssh/pom.xml.
Tip: Use ↑ and ↓ arrow keys to navigate and return to view the file.
Tip: You can also navigate files with Ctrl+j (next) and Ctrl+k (previous) and view the file with Ctrl+o.
Tip: You can also navigate files with Alt+j (next) and Alt+k (previous) and view the file with Alt+o.