Source

htsql-charset-option / src / htsql / validator.py

Full commit
  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
#
# Copyright (c) 2006-2010, Prometheus Research, LLC
# Authors: Clark C. Evans <cce@clarkevans.com>,
#          Kirill Simonov <xi@resolvent.net>
#


"""
:mod:`htsql.validator`
======================

This module provides utilities for data validation and conversion.
"""


from util import DB, maybe, oneof, listof
import re


class Val(object):
    """
    Validators check if a given value conforms the specified format.

    A validator acts as function that takes a value, checks if it conforms
    the format, normalizes and returns the value.  Example::

        validator = IntVal()
        value = validator(value)

    If the value does not conform the format, :exc:`ValueError` is raised.

    Attribute `hint` gives a short textual description of the format.

    :class:`Val` is the base abstract class for validators.  Its subclasses
    provide validators for specific formats.

    To create a validator for a new format, create a subclass of :class:`Val`
    and override the :meth:`__call__()` method.  The method should accept
    values of any type.  If the value does not conform to the format,
    :exc:`ValueError` should be raised; otherwise the value should be
    normalized and returned.

    Example::

        class IntVal(Val):

            hint = "an integer"

            def __call__(self, value):
                if isinstance(value, str):
                    value = int(value)
                if not isinstance(value, int):
                    raise ValueError("an integer is expected")
                return value
    """

    hint = None

    def __call__(self, value):
        # Override when subclassing.
        raise NotImplementedError()

    def get_hint(self):
        # Override when the hint is not static.
        return self.hint


class AnyVal(Val):
    """
    A no-op validator.
    """

    hint = """an arbitrary value"""

    def __call__(self, value):
        # All values are passed through.
        return value


class StrVal(Val):
    """
    Verifies if the value is a UTF-8 encoded string.

    `pattern` (a regular expression or ``None``)
        Checks if the string matches the given regular expression.

    `is_nullable` (Boolean)
        If set, ``None`` values are permitted.
    """

    hint = """a string"""

    def __init__(self, pattern=None, is_nullable=False):
        # Sanity check on the arguments.
        assert isinstance(pattern, maybe(str))
        assert isinstance(is_nullable, bool)

        self.pattern = pattern
        self.is_nullable = is_nullable

    def __call__(self, value):
        # `None` is allowed if the `is_nullable` flag is set.
        if value is None:
            if self.is_nullable:
                return None
            else:
                raise ValueError("the null value is not permitted")

        # A byte or a Unicode string is expected.
        if not isinstance(value, (str, unicode)):
            raise ValueError("a string value is expected; got %r" % value)

        # Byte strings must be UTF-8 encoded.
        if isinstance(value, str):
            try:
                value.decode('utf-8')
            except UnicodeDecodeError, exc:
                raise ValueError("unable to decode %r: %s" % (value, exc))

        # Translate Unicode strings to UTF-8 encoded byte strings.
        if isinstance(value, unicode):
            value = value.encode('utf-8')

        # Verify that the value does not contain the NUL character.
        if '\0' in value:
            raise ValueError("NUL character is not allowed; got %r" % value)

        # Check if the value matches the pattern.
        if self.pattern is not None:
            regexp = re.compile(self.pattern)
            if not regexp.match(value):
                raise ValueError("%r does not match pattern %r"
                                 % (value, self.pattern))

        # We are done, return a string.
        assert isinstance(value, str)
        return value


class WordVal(Val):
    """
    Verifies if the value is a word.

    A word is a string containing alphanumeric characters, dashes,
    underscores, or spaces.  In the normalized form, underscores and
    spaces are replaced with dashes.

    `is_nullable` (Boolean)
        If set, ``None`` values are permitted.
    """

    hint = """a word"""

    # A regular expression for matching words.
    regexp = re.compile(r'^[0-9a-zA-Z_ -]+$')

    def __init__(self, is_nullable=False):
        # Sanity check on the arguments.
        assert isinstance(is_nullable, bool)

        self.is_nullable = is_nullable

    def __call__(self, value):
        # `None` is allowed if the `is_nullable` flag is set.
        if value is None:
            if self.is_nullable:
                return None
            else:
                raise ValueError("the null value is not permitted")

        # A byte or a Unicode string is expected.
        if not isinstance(value, (str, unicode)):
            raise ValueError("a string value is expected; got %r" % value)

        # Byte strings must be UTF-8 encoded.
        if isinstance(value, str):
            try:
                value.decode('utf-8')
            except UnicodeDecodeError, exc:
                raise ValueError("unable to decode %r: %s" % (value, exc))

        # Translate Unicode strings to UTF-8 encoded byte strings.
        if isinstance(value, unicode):
            value = value.encode('utf-8')

        # Check if the string matches the word pattern.
        if not self.regexp.match(value):
            raise ValueError("a string containing alphanumeric characters,"
                             " dashes, underscores or spaces is expected;"
                             " got %r" % value)

        # Normalize and return the value.
        value = value.replace('_', '-').replace(' ', '-')
        return value


class ChoiceVal(Val):
    """
    Verifies if the value belongs to a specified set of string constants.

    ``choices`` (a list of strings)
        List of valid choices.

    `is_nullable` (Boolean)
        If set, ``None`` values are permitted.
    """

    hint = """a choice (%s)"""

    def __init__(self, choices, is_nullable=False):
        # Sanity check on the arguments.
        assert isinstance(choices, listof(str))
        assert isinstance(is_nullable, bool)

        self.choices = choices
        self.is_nullable = is_nullable

    def __call__(self, value):
        # `None` is allowed if the `is_nullable` flag is set.
        if value is None:
            if self.is_nullable:
                return None
            else:
                raise ValueError("the null value is not permitted")

        # A byte or a Unicode string is expected.
        if not isinstance(value, (str, unicode)):
            raise ValueError("a string value is expected; got %r" % value)

        # Translate Unicode strings to UTF-8 encoded byte strings.
        if isinstance(value, unicode):
            value = value.encode('utf-8')

        # Check if the value belongs to the specified set of choices.
        if value not in self.choices:
            choice_list = ", ".join(repr(choice) for choice in self.choices)
            raise ValueError("one of %s expected; got %r"
                             % (choice_list, value))

        return value


class BoolVal(Val):
    """
    Verifies if the value is Boolean.

    Besides ``True`` and ``False`` constants, the following values
    are accepted:

    * ``1``, ``'1'``, ``'true'`` (as ``True``);
    * ``0``, ``''``, ``'0'``, ``'false'`` (as ``False``).

    `is_nullable` (Boolean)
        If set, ``None`` values are permitted.
    """

    hint = """a Boolean value"""

    def __init__(self, is_nullable=False):
        # Sanity check on the arguments.
        assert isinstance(is_nullable, bool)

        self.is_nullable = is_nullable

    def __call__(self, value):
        # `None` is allowed if the `is_nullable` flag is set.
        if value is None:
            if self.is_nullable:
                return None
            else:
                raise ValueError("the null value is not permitted")

        # Valid values are: False, True, 0, 1, '', '0', '1', 'false', 'true';
        # anything else triggers an exception.
        if value in [0, '', '0', 'false']:
            value = False
        if value in [1, '1', 'true']:
            value = True
        if not isinstance(value, bool):
            raise ValueError("a Boolean value is expected; got %r" % value)

        # The value must be Boolean here.
        assert isinstance(value, bool)
        return value


class IntVal(Val):
    """
    Verifies if the value is an integer.

    Strings containing numeric characters are also accepted.

    `min_bound` (integer or ``None``)
        If set, check that the value is greater or equal to `min_bound`.

    `max_bound` (integer or ``None``)
        If set, check that the value is less or equal to `max_bound`.

    `is_nullable` (Boolean)
        If set, ``None`` values are permitted.
    """


    hint = """an integer"""

    def __init__(self, min_bound=None, max_bound=None, is_nullable=False):
        # Sanity check on the arguments.
        assert isinstance(min_bound, maybe(oneof(int, long)))
        assert isinstance(max_bound, maybe(oneof(int, long)))
        assert isinstance(is_nullable, bool)

        self.min_bound = min_bound
        self.max_bound = max_bound
        self.is_nullable = is_nullable

    def __call__(self, value):
        # `None` is allowed if the `is_nullable` flag is set.
        if value is None:
            if self.is_nullable:
                return None
            else:
                raise ValueError("the null value is not permitted")

        # Convert string values; a non-numeric string triggers `ValueError`.
        if isinstance(value, (str, unicode)):
            value = int(value)
        if not isinstance(value, (int, long)):
            raise ValueError("an integer value is required; got %r" % value)

        # Check the boundary conditions.
        if self.min_bound is not None and value < self.min_bound:
            raise ValueError("a value greater or equal to %s is required;"
                             " got %s" % (self.min_bound, value))
        if self.max_bound is not None and value > self.max_bound:
            raise ValueError("a value less or equal to %s is required;"
                             " got %s" % (self.max_bound, value))

        # `value` is an integer or a long integer here.
        assert isinstance(value, (int, long))
        return value


class UIntVal(IntVal):
    """
    Verifies if the value is a non-negative integer.
    """

    hint = """a non-negative integer"""

    def __init__(self, max_bound=None, is_nullable=False):
        super(UIntVal, self).__init__(0, max_bound, is_nullable)


class PIntVal(IntVal):
    """
    Verifies if the value is a positive integer.
    """

    hint = """a positive integer"""

    def __init__(self, max_bound=None, is_nullable=False):
        super(PIntVal, self).__init__(1, max_bound, is_nullable)


class FloatVal(Val):
    """
    Verifies if the value is an integer.

    Strings representing numeric values in a decimal or a scientific format
    are also accepted.

    `min_bound` (float or ``None``)
        If set, check that the value is greater or equal to `min_bound`.

    `max_bound` (float or ``None``)
        If set, check that the value is less or equal to `max_bound`.

    `is_nullable` (Boolean)
        If set, ``None`` values are permitted.
    """

    hint = """a float number"""

    def __init__(self, min_bound=None, max_bound=None, is_nullable=False):
        # Sanity check on the arguments.
        assert isinstance(min_bound, maybe(float))
        assert isinstance(max_bound, maybe(float))
        assert isinstance(is_nullable, bool)

        self.min_bound = min_bound
        self.max_bound = max_bound
        self.is_nullable = is_nullable

    def __call__(self, value):
        # `None` is allowed if the `is_nullable` flag is set.
        if value is None:
            if self.is_nullable:
                return None
            else:
                raise ValueError("the null value is not permitted")

        # Convert string and integer values.
        if isinstance(value, (str, unicode)):
            value = float(value)
        if isinstance(value, (int, long)):
            value = float(value)
        if not isinstance(value, float):
            raise ValueError("a float value is required; got %r" % value)

        # Check the boundary conditions.
        if self.min_bound is not None and value < self.min_bound:
            raise ValueError("a value greater or equal to %s is required;"
                             " got %s" % (self.min_bound, value))
        if self.max_bound is not None and value > self.max_bound:
            raise ValueError("a value less or equal to %s is required;"
                             " got %s" % (self.max_bound, value))

        # `value` is a float number here.
        assert isinstance(value, float)
        return value


class UFloatVal(IntVal):
    """
    Verifies if the value is a non-negative float number.
    """

    hint = """a non-negative float number"""

    def __init__(self, max_bound=None, is_nullable=False):
        super(UFloatVal, self).__init__(0, max_bound, is_nullable)


class SeqVal(Val):
    """
    Verifies if the value is a list with each list item conforming
    the specified format.

    Also accepted are strings that agree with the following grammar::

        value ::= <empty> | item ( [,] value )*
        item  ::= <any non-space character or comma>+
                | ['] ( <any non-quote character> | [']['] )* [']

    That is, the string must represent a comma-separated list of elements.
    If an element contains no whitespace characters and no commas, it could
    be represented literally; otherwise it should be quited with ``'`` and
    any single quote character should be duplicated.

    `item_validator` (:class:`Val`)
        Validator for the sequence elements.

    `length` (an integer or ``None``)
        If set, check that the length of the sequence is equal to `length`.

    `is_nullable` (Boolean)
        If set, ``None`` values are permitted.
    """

    hint = """a sequence [%s]"""

    # A regular expression to match tokens when the sequence is represented
    # by a string.
    pattern = r"""
        (?P<space> \s+ ) |
        (?P<comma> , ) |
        (?P<item> [^ \t\r\n',]+ | ' (?: [^'] | '')* ' )
    """
    regexp = re.compile(pattern, re.X)

    def __init__(self, item_validator, length=None, is_nullable=False):
        # Sanity check on the arguments.
        assert isinstance(item_validator, Val)
        assert isinstance(length, maybe(int))
        assert isinstance(is_nullable, bool)

        self.item_validator = item_validator
        self.length = length
        self.is_nullable = is_nullable

    def get_hint(self):
        # Provide short description of the form:
        #   a sequence [{item hint}]
        item_hint = self.item_validator.get_hint()
        return self.hint % item_hint

    def __call__(self, value):
        # `None` is allowed if the `is_nullable` flag is set.
        if value is None:
            if self.is_nullable:
                return None
            else:
                raise ValueError("the null value is not permitted")

        # Translate Unicode strings to UTF-8 byte strings.
        if isinstance(value, unicode):
            value = value.encode('utf-8')

        # If the value is a string, parse it and extract the elements.
        if isinstance(value, str):

            # List of elements.
            items = []
            # The beginning of the next token.
            start = 0
            # The current parsing state.
            is_comma_expected = False

            # Parse the string till it ends.  Error conditions are signalled
            # by ending the loop prematurely.
            while start < len(value):
                # Fetch the next token.
                match = self.regexp.match(value)
                if match is None:
                    break
                # A simple state machine.  The `is_comma_expected` variable
                # represents the machine state; the token type represents
                # conditions.  The transition table:
                #   is_comma_expected is on:
                #       token type is 'space' => no-op
                #       token type is 'comma' => turn is_comma_expected off
                #       token type is 'item'  => ERROR
                #   is_comma_expected is off:
                #       token type is 'space' => no-op
                #       token type is 'comma' => ERROR
                #       token type is 'item'  => extract the element,
                #                                turn is_comma_expected on
                if match.group('item') is not None:
                    if is_comma_expected:
                        break
                    item = match.group('item')
                    if item[0] == item[-1] == '\'':
                        item = item[1:-1].replace('\'\'', '\'')
                    items.append(item)
                    is_comma_expected = True
                elif match.group('comma') is not None:
                    if not is_comma_expected:
                        break
                    is_comma_expected = False
                # Move to the beginning of the next token.
                start = match.end()

            # If the loop ended prematurely, it must have been
            # a parsing error.
            if start < len(value):
                raise ValueError("a comma-separated list is expected;"
                                 " got %r" % value)

            # Now `value` is a list of elements.
            value = items

        # By this step, `value` must be converted to a proper list.
        if not isinstance(value, list):
            raise ValueError("a list is expected; got %r" % value)

        # Check the length is specified.
        if self.length is not None:
            if len(value) != self.length:
                raise ValueError("a sequence of length %s is expected;"
                                 " got %r" % (self.length, value))

        # Validate and normalize the list elements.
        items = []
        for idx, item in enumerate(value):
            try:
                item = self.item_validator(item)
            except ValueError, exc:
                raise ValueError("invalid sequence item"
                                 " #%s (%s)" % (idx+1, exc))
            items.append(item)
        value = items

        # Here `value` is a list of normalized elements.
        return value


class MapVal(Val):
    """
    Verifies if the value is a dictionary with keys and items conforming
    the specified formats.

    Also accepted are strings that agree with the following grammar::

        value     ::= <empty> | key ( [:] | [=] ) item ( [,] value )*
        key, item ::= <any non-space character except for [:], [=] or [,]>+
                    | ['] ( <any non-quote character> | [']['] )* [']

    That is, the string must represent a comma-separated list of ``key=item``
    pairs.  The key and the item could be quoted or unquoted.  An unquoted
    element contains no whitespace, ``:``, ``=``, ``,`` characters.  A quoted
    element is enclosed with ``'`` and has any single quote character
    duplicated.

    `key_validator` (:class:`Val`)
        Validator for the mapping keys.

    `item_validator` (:class:`Val`)
        Validator for the mapping values.

    `is_nullable` (Boolean)
        If set, ``None`` values are permitted.
    """

    hint = """a mapping {%s -> %s}"""

    # A regular expression to match tokens when the mapping is represented
    # by a string.
    pattern = r"""
        (?P<space> \s+ ) |
        (?P<comma> , ) |
        (?P<colon> [:=] ) |
        (?P<item> [^ \t\r\n',:]+ | ' (?: [^'] | '')* ' )
    """
    regexp = re.compile(pattern, re.X)

    def __init__(self, key_validator, item_validator, is_nullable=False):
        # Sanity check on the arguments.
        assert isinstance(key_validator, Val)
        assert isinstance(item_validator, Val)
        assert isinstance(is_nullable, bool)

        self.key_validator = key_validator
        self.item_validator = item_validator
        self.is_nullable = is_nullable

    def get_hint(self):
        # Provide short description of the form:
        #   a mapping {{key hint} -> {item hint}}
        key_hint = self.key_validator.get_hint()
        item_hint = self.item_validator.get_hint()
        return self.hint % (key_hint, item_hint)

    def __call__(self, value):
        # `None` is allowed if the `is_nullable` flag is set.
        if value is None:
            if self.is_nullable:
                return None
            else:
                raise ValueError("the null value is not permitted")

        # Translate Unicode strings to UTF-8 encoded byte strings.
        if isinstance(value, unicode):
            value = value.encode('utf-8')

        # If the value is a string, parse it and extract the elements.
        if isinstance(value, str):

            # List of `(key, item)` pairs.
            pairs = []
            # The beginning of the next token.
            start = 0
            # The current parsing state.
            is_key_expected = True
            is_colon_expected = False
            is_item_expected = False
            is_comma_expected = False
            # Keeps the current key till we extract the corresponding item.
            current_key = None

            # Parse the string till it ends.  Error conditions are signalled
            # by ending the loop prematurely.
            while start < len(value):
                # Fetch the next token.
                match = self.regexp.match(value)
                if match is None:
                    break
                # This loop represents a simple state machine.  The
                # `is_key/colon/item/comma_expected` variables keep the
                # current state; the token type represents conditions.
                # The transition table:
                #   state is 'key':
                #       token type is 'space' => no-op
                #       token type is 'colon' => ERROR
                #       token type is 'comma' => ERROR
                #       token type is 'item'  => extract the element
                #                                as the current key,
                #                                set state to 'colon'
                #   state is 'colon':
                #       token type is 'space' => no-op
                #       token type is 'colon' => set state to 'item'
                #       token type is 'comma' => ERROR
                #       token type is 'item'  => ERROR
                #   state is 'item':
                #       token type is 'space' => no-op
                #       token type is 'colon' => ERROR
                #       token type is 'comma' => ERROR
                #       token type is 'item'  => extract the element
                #                                as the item corresponding
                #                                to the current key,
                #                                set state to 'comma'
                #   state is 'comma':
                #       token type is 'space' => no-op
                #       token type is 'colon' => ERROR
                #       token type is 'comma' => set state to 'key'
                #       token type is 'item'  => ERROR
                # Note that the final state must be either 'comma' or 'key'.
                if match.group('item') is not None:
                    item = match.group('item')
                    if item[0] == item[-1] == '\'':
                        item = item[1:-1].replace('\'\'', '\'')
                    if is_key_expected:
                        current_key = item
                        is_key_expected = False
                        is_colon_expected = True
                    elif is_item_expected:
                        pairs.append((current_key, item))
                        current_key = None
                        is_item_expected = False
                        is_comma_expected = True
                    else:
                        break
                elif match.group('colon') is not None:
                    if not is_colon_expected:
                        break
                    is_colon_expected = False
                    is_item_expected = True
                elif match.group('comma') is not None:
                    if not is_comma_expected:
                        break
                    is_comma_expected = False
                    is_key_expected = True
                # Move to the next token.
                start = match.end()

            # Check if the parsing loop ended prematurely, or if the final
            # state is invalid.
            if start < len(value) or is_colon_expected or is_item_expected:
                raise ValueError("a comma-separated list of key=value pairs"
                                 " is expected; got %r" % value)

            # Now `value` is a dictionary.
            value = dict(pairs)

        # By this time, `value` must be a dictionary.
        if not isinstance(value, dict):
            raise ValueError("a dictionary is required; got %r" % value)

        # Validate and normalize the mapping keys and values.  Note that
        # we need to check for duplicate keys since normalization may
        # convert two distinct keys to the same normalized key.
        pairs = []
        key_set = set()
        for key in sorted(value):
            try:
                validated_key = self.key_validator(key)
            except ValueError, exc:
                raise ValueError("invalid mapping key (%s)" % exc)
            if validated_key in key_set:
                raise ValueError("duplicate mapping key %r" % key)
            key_set.add(validated_key)
            item = value[key]
            try:
                validated_item = self.item_validator(item)
            except ValueError, exc:
                raise ValueError("invalid mapping item for key %r (%s)"
                                 % (key, item))
            pairs.append((validated_key, validated_item))
        value = dict(pairs)

        # Here `value` is a mapping with normalized keys and items.
        return value


class ClassVal(Val):
    """
    Verifies if the value is an instance of the specified class.

    `class_type`
        A class or a type object.

    `is_nullable` (Boolean)
        If set, ``None`` values are permitted.
    """

    hint = """a class instance (%s)"""

    def __init__(self, class_type, is_nullable=False):
        # Sanity check on the arguments.
        assert isinstance(class_type, type)
        assert isinstance(is_nullable, bool)

        self.class_type = class_type
        self.is_nullable = is_nullable

    def get_hint(self):
        # Provide short description of the form
        #   a class instance({class name})
        return self.hint % self.class_type.__name__

    def __call__(self, value):
        # `None` is allowed if the `is_nullable` flag is set.
        if value is None:
            if self.is_nullable:
                return None
            else:
                raise ValueError("the null value is not permitted")

        # Check if the value is an instance of the specified class.
        if not isinstance(value, self.class_type):
            raise ValueError("an instance of %s is expected; got %r"
                             % (self.class_type.__name__, value))

        return value


class DBVal(Val):
    """
    Verifies if the value is a connection URI.

    For description of the connection URI format, see
    :meth:`htsql.util.DB.parse`.

    `is_nullable` (Boolean)
        If set, ``None`` values are permitted.
    """

    hint = """a connection URI"""

    def __init__(self, is_nullable=False):
        # Sanity check on the arguments.
        assert isinstance(is_nullable, bool)

        self.is_nullable = is_nullable

    def __call__(self, value):
        # `None` is allowed if the `is_nullable` flag is set.
        if value is None:
            if self.is_nullable:
                return None
            else:
                raise ValueError("the null value is not permitted")

        # The `DB` class provides its own conversion routine.
        return DB.parse(value)