This file is indexed.

/usr/lib/python2.7/dist-packages/pycassa/columnfamily.py is in python-pycassa 1.11.1-2.

This file is owned by root:root, with mode 0o644.

The actual contents of the file can be viewed below.

   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
 923
 924
 925
 926
 927
 928
 929
 930
 931
 932
 933
 934
 935
 936
 937
 938
 939
 940
 941
 942
 943
 944
 945
 946
 947
 948
 949
 950
 951
 952
 953
 954
 955
 956
 957
 958
 959
 960
 961
 962
 963
 964
 965
 966
 967
 968
 969
 970
 971
 972
 973
 974
 975
 976
 977
 978
 979
 980
 981
 982
 983
 984
 985
 986
 987
 988
 989
 990
 991
 992
 993
 994
 995
 996
 997
 998
 999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
"""
Provides an abstraction of Cassandra's data model to allow for easy
manipulation of data inside Cassandra.

.. seealso:: :mod:`pycassa.columnfamilymap`
"""

import time
import struct
from UserDict import DictMixin

from pycassa.cassandra.ttypes import Column, ColumnOrSuperColumn,\
    ColumnParent, ColumnPath, ConsistencyLevel, NotFoundException,\
    SlicePredicate, SliceRange, SuperColumn, KeyRange,\
    IndexExpression, IndexClause, CounterColumn, Mutation
import pycassa.marshal as marshal
import pycassa.types as types
from pycassa.batch import CfMutator
try:
    from collections import OrderedDict
except ImportError:
    from pycassa.util import OrderedDict # NOQA

__all__ = ['gm_timestamp', 'ColumnFamily', 'PooledColumnFamily']

class ColumnValidatorDict(DictMixin):

    def __init__(self, other_dict={}, name_packer=None, name_unpacker=None):
        self.name_packer = name_packer or (lambda x: x)
        self.name_unpacker = name_unpacker or (lambda x: x)

        self.type_map = {}
        self.packers = {}
        self.unpackers = {}
        for item, value in other_dict.items():
            packed_item = self.name_packer(item)
            self[packed_item] = value

    def __getitem__(self, item):
        packed_item = self.name_packer(item)
        return self.type_map[packed_item]

    def __setitem__(self, item, value):
        packed_item = self.name_packer(item)
        if isinstance(value, types.CassandraType):
            self.type_map[packed_item] = value
            self.packers[packed_item] = value.pack
            self.unpackers[packed_item] = value.unpack
        else:
            self.type_map[packed_item] = marshal.extract_type_name(value)
            self.packers[packed_item] = marshal.packer_for(value)
            self.unpackers[packed_item] = marshal.unpacker_for(value)

    def __delitem__(self, item):
        packed_item = self.name_packer(item)
        del self.type_map[packed_item]
        del self.packers[packed_item]
        del self.unpackers[packed_item]

    def keys(self):
        return map(self.name_unpacker, self.type_map.keys())

def gm_timestamp():
    """ Returns the number of microseconds since the Unix Epoch. """
    return int(time.time() * 1e6)

class ColumnFamily(object):
    """
    An abstraction of a Cassandra column family or super column family.
    Operations on this, such as :meth:`get` or :meth:`insert` will get data from or
    insert data into the corresponding Cassandra column family.
    """

    buffer_size = 1024
    """ When calling :meth:`get_range()` or :meth:`get_indexed_slices()`,
    the intermediate results need to be buffered if we are fetching many
    rows, otherwise performance may suffer and the Cassandra server may
    overallocate memory and fail. This is the size of that buffer in number
    of rows. The default is 1024. """

    column_buffer_size = 1024
    """ The number of columns fetched at once for :meth:`xget()` """

    read_consistency_level = ConsistencyLevel.ONE
    """ The default consistency level for every read operation, such as
    :meth:`get` or :meth:`get_range`. This may be overridden per-operation. This should be
    an instance of :class:`~pycassa.cassandra.ttypes.ConsistencyLevel`.
    The default level is ``ONE``. """

    write_consistency_level = ConsistencyLevel.ONE
    """ The default consistency level for every write operation, such as
    :meth:`insert` or :meth:`remove`. This may be overridden per-operation. This should be
    an instance of :class:`.~pycassa.cassandra.ttypes.ConsistencyLevel`.
    The default level is ``ONE``. """

    timestamp = gm_timestamp
    """ Each :meth:`insert()` or :meth:`remove` sends a timestamp with every
    column. This attribute is a function that is used to get
    this timestamp when needed.  The default function is :meth:`gm_timestamp()`."""

    dict_class = OrderedDict
    """ Results are returned as dictionaries. By default, python 2.7's
    :class:`collections.OrderedDict` is used if available, otherwise
    :class:`~pycassa.util.OrderedDict` is used so that order is maintained.
    A different class, such as :class:`dict`, may be instead by used setting
    this. """

    autopack_names = True
    """ Controls whether column names are automatically converted to or from
    their natural type to the binary string format that Cassandra uses.
    The data type used is controlled by :attr:`column_name_class` for
    column names and :attr:`super_column_name_class` for super column names.
    By default, this is :const:`True`. """

    autopack_values = True
    """ Whether column values are automatically converted to or from
    their natural type to the binary string format that Cassandra uses.
    The data type used is controlled by :attr:`default_validation_class`
    and :attr:`column_validators`.
    By default, this is :const:`True`. """

    autopack_keys = True
    """ Whether row keys are automatically converted to or from
    their natural type to the binary string format that Cassandra uses.
    The data type used is controlled by :attr:`key_validation_class`.
    By default, this is :const:`True`.
    """

    retry_counter_mutations = False
    """ Whether to retry failed counter mutations. Counter mutations are
    not idempotent so retrying could result in double counting.
    By default, this is :const:`False`.

    .. versionadded:: 1.5.0

    """

    def _set_column_name_class(self, t):
        if isinstance(t, types.CassandraType):
            self._column_name_class = t
            self._name_packer = t.pack
            self._name_unpacker = t.unpack
        else:
            self._column_name_class = marshal.extract_type_name(t)
            self._name_packer = marshal.packer_for(t)
            self._name_unpacker = marshal.unpacker_for(t)

    def _get_column_name_class(self):
        return self._column_name_class

    column_name_class = property(_get_column_name_class, _set_column_name_class)
    """ The data type of column names, which pycassa will use
    to determine how to pack and unpack them.

    This is set automatically by inspecting the column family's
    ``comparator_type``, but it may also be set manually if you want
    autopacking behavior without setting a ``comparator_type``. Options
    include an instance of any class in :mod:`pycassa.types`, such as ``LongType()``.
    """

    def _set_super_column_name_class(self, t):
        if isinstance(t, types.CassandraType):
            self._super_column_name_class = t
            self._super_name_packer = t.pack
            self._super_name_unpacker = t.unpack
        else:
            self._super_column_name_class = marshal.extract_type_name(t)
            self._super_name_packer = marshal.packer_for(t)
            self._super_name_unpacker = marshal.unpacker_for(t)

    def _get_super_column_name_class(self):
        return self._super_column_name_class

    super_column_name_class = property(_get_super_column_name_class,
                                       _set_super_column_name_class)
    """ Like :attr:`column_name_class`, but for
    super column names. """

    def _set_default_validation_class(self, t):
        if isinstance(t, types.CassandraType):
            self._default_validation_class = t
            self._default_value_packer = t.pack
            self._default_value_unpacker = t.unpack
            self._have_counters = isinstance(t, types.CounterColumnType)
        else:
            self._default_validation_class = marshal.extract_type_name(t)
            self._default_value_packer = marshal.packer_for(t)
            self._default_value_unpacker = marshal.unpacker_for(t)
            self._have_counters = self._default_validation_class == "CounterColumnType"

        if not self.super:
            if self._have_counters:
                def _make_counter_cosc(name, value, timestamp, ttl):
                    return ColumnOrSuperColumn(counter_column=CounterColumn(name, value))
                self._make_cosc = _make_counter_cosc
            else:
                def _make_normal_cosc(name, value, timestamp, ttl):
                    return ColumnOrSuperColumn(Column(name, value, timestamp, ttl))
                self._make_cosc = _make_normal_cosc
        else:
            if self._have_counters:
                def _make_column(name, value, timestamp, ttl):
                    return CounterColumn(name, value)
                self._make_column = _make_column

                def _make_counter_super_cosc(scol_name, subcols):
                    return ColumnOrSuperColumn(counter_super_column=(SuperColumn(scol_name, subcols)))
                self._make_cosc = _make_counter_super_cosc
            else:
                self._make_column = Column

                def _make_super_cosc(scol_name, subcols):
                    return ColumnOrSuperColumn(super_column=(SuperColumn(scol_name, subcols)))
                self._make_cosc = _make_super_cosc

    def _get_default_validation_class(self):
        return self._default_validation_class

    default_validation_class = property(_get_default_validation_class,
                                        _set_default_validation_class)
    """ The default data type of column values, which pycassa
    will use to determine how to pack and unpack them.

    This is set automatically by inspecting the column family's
    ``default_validation_class``, but it may also be set manually if you want
    autopacking behavior without setting a ``default_validation_class``. Options
    include an instance of any class in :mod:`pycassa.types`, such as ``LongType()``.
    """

    @property
    def _allow_retries(self):
        return not self._have_counters or self.retry_counter_mutations

    def _set_column_validators(self, other_dict):
        self._column_validators = ColumnValidatorDict(other_dict, self._pack_name, self._unpack_name)

    def _get_column_validators(self):
        return self._column_validators

    column_validators = property(_get_column_validators, _set_column_validators)
    """ Like :attr:`default_validation_class`, but is a
    :class:`dict` mapping individual columns to types. """

    def _set_key_validation_class(self, t):
        if isinstance(t, types.CassandraType):
            self._key_validation_class = t
            self._key_packer = t.pack
            self._key_unpacker = t.unpack
        else:
            self._key_validation_class = marshal.extract_type_name(t)
            self._key_packer = marshal.packer_for(t)
            self._key_unpacker = marshal.unpacker_for(t)

    def _get_key_validation_class(self):
        return self._key_validation_class

    key_validation_class = property(_get_key_validation_class,
                                    _set_key_validation_class)
    """ The data type of row keys, which pycassa will use
    to determine how to pack and unpack them.

    This is set automatically by inspecting the column family's
    ``key_validation_class`` (which only exists in Cassandra 0.8 or greater),
    but may be set manually if you want the autopacking behavior without
    setting a ``key_validation_class`` or if you are using Cassandra 0.7.
    Options include an instance of any class in :mod:`pycassa.types`,
    such as ``LongType()``.
    """

    def __init__(self, pool, column_family, **kwargs):
        """
        `pool` is a :class:`~pycassa.pool.ConnectionPool` that the column
        family will use for all operations. A connection is drawn from the
        pool before each operations and is returned afterwards.

        `column_family` should be the name of the column family that you
        want to use in Cassandra. Note that the keyspace to be used is
        determined by the pool.
        """

        self.pool = pool
        self.column_family = column_family
        self.timestamp = gm_timestamp
        self.load_schema()

        recognized_kwargs = ("buffer_size", "read_consistency_level",
                             "write_consistency_level", "timestamp",
                             "dict_class", "buffer_size", "autopack_names",
                             "autopack_values", "autopack_keys",
                             "retry_counter_mutations")
        for k, v in kwargs.iteritems():
            if k in recognized_kwargs:
                setattr(self, k, v)
            else:
                raise TypeError(
                        "ColumnFamily.__init__() got an unexpected keyword "
                        "argument '%s'" % (k,))

    def load_schema(self):
        """
        Loads the schema definition for this column family from
        Cassandra and updates comparator and validation classes if
        neccessary.
        """
        ksdef = self.pool.execute('get_keyspace_description',
                                  use_dict_for_col_metadata=True)
        try:
            self._cfdef = ksdef[self.column_family]
        except KeyError:
            nfe = NotFoundException()
            nfe.why = 'Column family %s not found.' % self.column_family
            raise nfe

        self.super = self._cfdef.column_type == 'Super'
        self._load_comparator_classes()
        self._load_validation_classes()
        self._load_key_class()

    def _load_comparator_classes(self):
        if not self.super:
            self.column_name_class = self._cfdef.comparator_type
            self.super_column_name_class = None
        else:
            self.column_name_class = self._cfdef.subcomparator_type
            self.super_column_name_class = self._cfdef.comparator_type

    def _load_validation_classes(self):
        self.default_validation_class = self._cfdef.default_validation_class
        self.column_validators = {}
        for name, coldef in self._cfdef.column_metadata.items():
            unpacked_name = self._unpack_name(name)
            self.column_validators[unpacked_name] = coldef.validation_class

    def _load_key_class(self):
        if hasattr(self._cfdef, "key_validation_class"):
            self.key_validation_class = self._cfdef.key_validation_class
        else:
            self.key_validation_class = 'BytesType'

    def _col_to_dict(self, column, include_timestamp, include_ttl):
        value = self._unpack_value(column.value, column.name)
        if include_timestamp and include_ttl:
            return (value, column.timestamp, column.ttl)
        elif include_timestamp:
            return (value, column.timestamp)
        elif include_ttl:
            return (value, column.ttl)
        else:
            return value

    def _scol_to_dict(self, super_column, include_timestamp, include_ttl):
        ret = self.dict_class()
        for column in super_column.columns:
            ret[self._unpack_name(column.name)] = self._col_to_dict(column, include_timestamp, include_ttl)
        return ret

    def _scounter_to_dict(self, counter_super_column):
        ret = self.dict_class()
        for counter in counter_super_column.columns:
            ret[self._unpack_name(counter.name)] = counter.value
        return ret

    def _cosc_to_dict(self, list_col_or_super, include_timestamp, include_ttl):
        ret = self.dict_class()
        for cosc in list_col_or_super:
            if cosc.column:
                col = cosc.column
                ret[self._unpack_name(col.name)] = self._col_to_dict(col, include_timestamp, include_ttl)
            elif cosc.counter_column:
                counter = cosc.counter_column
                ret[self._unpack_name(counter.name)] = counter.value
            elif cosc.super_column:
                scol = cosc.super_column
                ret[self._unpack_name(scol.name, True)] = self._scol_to_dict(scol, include_timestamp, include_ttl)
            else:
                scounter = cosc.counter_super_column
                ret[self._unpack_name(scounter.name, True)] = self._scounter_to_dict(scounter)
        return ret

    def _column_path(self, super_column=None, column=None):
        return ColumnPath(self.column_family,
                          self._pack_name(super_column, is_supercol_name=True),
                          self._pack_name(column, False))

    def _column_parent(self, super_column=None):
        return ColumnParent(column_family=self.column_family,
                            super_column=self._pack_name(super_column, is_supercol_name=True))

    def _slice_predicate(self, columns, column_start, column_finish,
                         column_reversed, column_count, super_column=None, pack=True):
        is_supercol_name = self.super and super_column is None
        if columns is not None:
            packed_cols = []
            for col in columns:
                packed_cols.append(self._pack_name(col, is_supercol_name=is_supercol_name))
            return SlicePredicate(column_names=packed_cols)
        else:
            if column_start != '' and pack:
                column_start = self._pack_name(column_start,
                                               is_supercol_name=is_supercol_name,
                                               slice_start=(not column_reversed))
            if column_finish != '' and pack:
                column_finish = self._pack_name(column_finish,
                                                is_supercol_name=is_supercol_name,
                                                slice_start=column_reversed)

            sr = SliceRange(start=column_start, finish=column_finish,
                            reversed=column_reversed, count=column_count)
            return SlicePredicate(slice_range=sr)

    def _pack_name(self, value, is_supercol_name=False, slice_start=None):
        if value is None:
            return

        if not self.autopack_names:
            if not isinstance(value, basestring):
                raise TypeError("A str or unicode column name was expected, " +
                                "but %s was received instead (%s)"
                                % (value.__class__.__name__, str(value)))
            return value

        try:
            if is_supercol_name:
                return self._super_name_packer(value, slice_start)
            else:
                return self._name_packer(value, slice_start)
        except struct.error:
            if is_supercol_name:
                d_type = self.super_column_name_class
            else:
                d_type = self.column_name_class

            raise TypeError("%s is not a compatible type for %s" %
                            (value.__class__.__name__, d_type))

    def _unpack_name(self, b, is_supercol_name=False):
        if not self.autopack_names:
            return b

        try:
            if is_supercol_name:
                return self._super_name_unpacker(b)
            else:
                return self._name_unpacker(b)
        except struct.error:
            if is_supercol_name:
                d_type = self.super_column_name_class
            else:
                d_type = self.column_name_class
            raise TypeError("%s cannot be converted to a type matching %s" %
                            (b, d_type))

    def _pack_value(self, value, col_name):
        if value is None:
            return

        if not self.autopack_values:
            if not isinstance(value, basestring):
                raise TypeError("A str or unicode column value was expected for " +
                                "column '%s', but %s was received instead (%s)"
                                % (str(col_name), value.__class__.__name__, str(value)))
            return value

        packed_col_name = self._pack_name(col_name, False)
        packer = self._column_validators.packers.get(packed_col_name, self._default_value_packer)
        try:
            return packer(value)
        except struct.error:
            d_type = self.column_validators.get(col_name, self._default_validation_class)
            raise TypeError("%s is not a compatible type for %s" %
                            (value.__class__.__name__, d_type))

    def _unpack_value(self, value, col_name):
        if not self.autopack_values:
            return value
        unpacker = self._column_validators.unpackers.get(col_name, self._default_value_unpacker)
        try:
            return unpacker(value)
        except struct.error:
            d_type = self.column_validators.get(col_name, self.default_validation_class)
            raise TypeError("%s cannot be converted to a type matching %s" %
                            (value, d_type))

    def _pack_key(self, key):
        if not self.autopack_keys or key == '':
            return key
        try:
            return self._key_packer(key)
        except struct.error:
            d_type = self.key_validation_class
            raise TypeError("%s is not a compatible type for %s" %
                            (key.__class__.__name__, d_type))

    def _unpack_key(self, b):
        if not self.autopack_keys:
            return b
        try:
            return self._key_unpacker(b)
        except struct.error:
            d_type = self.key_validation_class
            raise TypeError("%s cannot be converted to a type matching %s" %
                            (b, d_type))

    def _make_mutation_list(self, columns, timestamp, ttl):
        _pack_name = self._pack_name
        _pack_value = self._pack_value
        if not self.super:
            return map(lambda (c, v): Mutation(self._make_cosc(_pack_name(c), _pack_value(v, c), timestamp, ttl)),
                       columns.iteritems())
        else:
            mut_list = []
            for super_col, subcs in columns.items():
                subcols = map(lambda (c, v): self._make_column(_pack_name(c), _pack_value(v, c), timestamp, ttl),
                              subcs.iteritems())
                mut_list.append(Mutation(self._make_cosc(_pack_name(super_col, True), subcols)))
            return mut_list

    def xget(self, key, column_start="", column_finish="", column_reversed=False,
             column_count=None, include_timestamp=False, read_consistency_level=None,
             buffer_size=None, include_ttl=False):
        """
        Like :meth:`get()`, but creates a generator that pages over the columns
        automatically.

        The number of columns fetched at once can be controlled with the
        `buffer_size` parameter. The default is :attr:`column_buffer_size`.

        The generator returns `(name, value)` tuples.
        """

        packed_key = self._pack_key(key)
        cp = self._column_parent(None)
        rcl = read_consistency_level or self.read_consistency_level

        if buffer_size is None:
            buffer_size = self.column_buffer_size

        count = i = 0
        last_name = finish = ""
        if column_start != "":
            last_name = self._pack_name(column_start,
                    is_supercol_name=self.super,
                    slice_start=(not column_reversed))
        if column_finish != "":
            finish = self._pack_name(column_finish,
                    is_supercol_name=self.super,
                    slice_start=column_reversed)

        while True:
            if column_count is not None:
                if i == 0 and column_count <= buffer_size:
                    buffer_size = column_count
                else:
                    buffer_size = min(column_count - count + 1, buffer_size)

            sp = self._slice_predicate(None, last_name, finish,
                                       column_reversed, buffer_size, None, pack=False)
            list_cosc = self.pool.execute('get_slice', packed_key, cp, sp, rcl)

            if not list_cosc:
                return

            for j, cosc in enumerate(list_cosc):
                if j == 0 and i != 0:
                    continue

                if self.super:
                    if self._have_counters:
                        scol = cosc.counter_super_column
                    else:
                        scol = cosc.super_column
                    yield (self._unpack_name(scol.name, True), self._scol_to_dict(scol, include_timestamp, include_ttl))
                else:
                    if self._have_counters:
                        col = cosc.counter_column
                    else:
                        col = cosc.column
                    yield (self._unpack_name(col.name, False), self._col_to_dict(col, include_timestamp, include_ttl))

                count += 1
                if column_count is not None and count >= column_count:
                    return

            if len(list_cosc) != buffer_size:
                return

            if self.super:
                if self._have_counters:
                    last_name = list_cosc[-1].counter_super_column.name
                else:
                    last_name = list_cosc[-1].super_column.name
            else:
                if self._have_counters:
                    last_name = list_cosc[-1].counter_column.name
                else:
                    last_name = list_cosc[-1].column.name
            i += 1

    def get(self, key, columns=None, column_start="", column_finish="",
            column_reversed=False, column_count=100, include_timestamp=False,
            super_column=None, read_consistency_level=None, include_ttl=False):
        """
        Fetches all or part of the row with key `key`.

        The columns fetched may be limited to a specified list of column names
        using `columns`.

        Alternatively, you may fetch a slice of columns or super columns from a row
        using `column_start`, `column_finish`, and `column_count`.
        Setting these will cause columns or super columns to be fetched starting with
        `column_start`, continuing until `column_count` columns or super columns have
        been fetched or `column_finish` is reached.  If `column_start` is left as the
        empty string, the slice will begin with the start of the row; leaving
        `column_finish` blank will cause the slice to extend to the end of the row.
        Note that `column_count` defaults to 100, so rows over this size will not be
        completely fetched by default.

        If `column_reversed` is ``True``, columns are fetched in reverse sorted order,
        beginning with `column_start`.  In this case, if `column_start` is the empty
        string, the slice will begin with the end of the row.

        You may fetch all or part of only a single super column by setting `super_column`.
        If this is set, `column_start`, `column_finish`, `column_count`, and `column_reversed`
        will apply to the subcolumns of `super_column`.

        To include every column's timestamp in the result set, set `include_timestamp` to
        ``True``.  Results will include a ``(value, timestamp)`` tuple for each column.

        To include every column's ttl in the result set, set `include_ttl` to
        ``True``.  Results will include a ``(value, ttl)`` tuple for each column.

        If this is a standard column family, the return type is of the form
        ``{column_name: column_value}``.  If this is a super column family and `super_column`
        is not specified, the results are of the form
        ``{super_column_name: {column_name, column_value}}``.  If `super_column` is set,
        the super column name will be excluded and the results are of the form
        ``{column_name: column_value}``.

        """

        packed_key = self._pack_key(key)
        single_column = columns is not None and len(columns) == 1
        if (not self.super and single_column) or \
           (self.super and super_column is not None and single_column):
            column = None
            if self.super and super_column is None:
                super_column = columns[0]
            else:
                column = columns[0]
            cp = self._column_path(super_column, column)
            col_or_super = self.pool.execute('get', packed_key, cp,
                    read_consistency_level or self.read_consistency_level)
            return self._cosc_to_dict([col_or_super], include_timestamp, include_ttl)
        else:
            cp = self._column_parent(super_column)
            sp = self._slice_predicate(columns, column_start, column_finish,
                                       column_reversed, column_count, super_column)

            list_col_or_super = self.pool.execute('get_slice', packed_key, cp, sp,
                read_consistency_level or self.read_consistency_level)

            if len(list_col_or_super) == 0:
                raise NotFoundException()
            return self._cosc_to_dict(list_col_or_super, include_timestamp, include_ttl)

    def get_indexed_slices(self, index_clause, columns=None, column_start="", column_finish="",
                           column_reversed=False, column_count=100, include_timestamp=False,
                           read_consistency_level=None, buffer_size=None, include_ttl=False):
        """
        Similar to :meth:`get_range()`, but an :class:`~pycassa.cassandra.ttypes.IndexClause`
        is used instead of a key range.

        `index_clause` limits the keys that are returned based on expressions
        that compare the value of a column to a given value.  At least one of the
        expressions in the :class:`.IndexClause` must be on an indexed column.

        Note that Cassandra does not support secondary indexes or get_indexed_slices()
        for super column families.

            .. seealso:: :meth:`~pycassa.index.create_index_clause()` and
                         :meth:`~pycassa.index.create_index_expression()`

        """

        assert not self.super, "get_indexed_slices() is not " \
                "supported by super column families"

        cl = read_consistency_level or self.read_consistency_level
        cp = self._column_parent()
        sp = self._slice_predicate(columns, column_start, column_finish,
                                   column_reversed, column_count)

        new_exprs = []
        # Pack the values in the index clause expressions
        for expr in index_clause.expressions:
            value = self._pack_value(expr.value, expr.column_name)
            name = self._pack_name(expr.column_name)
            new_exprs.append(IndexExpression(name, expr.op, value))

        packed_start_key = self._pack_key(index_clause.start_key)
        clause = IndexClause(new_exprs, packed_start_key, index_clause.count)

        # Figure out how we will chunk the request
        if buffer_size is None:
            buffer_size = self.buffer_size
        row_count = clause.count

        count = 0
        i = 0
        last_key = clause.start_key
        while True:
            if row_count is not None:
                if i == 0 and row_count <= buffer_size:
                    # We don't need to chunk, grab exactly the number of rows
                    buffer_size = row_count
                else:
                    buffer_size = min(row_count - count + 1, buffer_size)
            clause.count = buffer_size
            clause.start_key = last_key
            key_slices = self.pool.execute('get_indexed_slices', cp, clause, sp, cl)

            if key_slices is None:
                return
            for j, key_slice in enumerate(key_slices):
                # Ignore the first element after the first iteration
                # because it will be a duplicate.
                if j == 0 and i != 0:
                    continue
                unpacked_key = self._unpack_key(key_slice.key)
                yield (unpacked_key,
                       self._cosc_to_dict(key_slice.columns, include_timestamp, include_ttl))

                count += 1
                if row_count is not None and count >= row_count:
                    return

            if len(key_slices) != buffer_size:
                return
            last_key = key_slices[-1].key
            i += 1

    def multiget(self, keys, columns=None, column_start="", column_finish="",
                 column_reversed=False, column_count=100, include_timestamp=False,
                 super_column=None, read_consistency_level=None, buffer_size=None, include_ttl=False):
        """
        Fetch multiple rows from a Cassandra server.

        `keys` should be a list of keys to fetch.

        `buffer_size` is the number of rows from the total list to fetch at a time.
        If left as ``None``, the ColumnFamily's :attr:`buffer_size` will be used.

        All other parameters are the same as :meth:`get()`, except that a list of keys may
        be passed in.

        Results will be returned in the form: ``{key: {column_name: column_value}}``. If
        an OrderedDict is used, the rows will have the same order as `keys`.

        """

        packed_keys = map(self._pack_key, keys)
        cp = self._column_parent(super_column)
        sp = self._slice_predicate(columns, column_start, column_finish,
                                   column_reversed, column_count, super_column)
        consistency = read_consistency_level or self.read_consistency_level

        buffer_size = buffer_size or self.buffer_size
        offset = 0
        keymap = {}
        while offset < len(packed_keys):
            new_keymap = self.pool.execute('multiget_slice',
                packed_keys[offset:offset + buffer_size], cp, sp, consistency)
            keymap.update(new_keymap)
            offset += buffer_size

        ret = self.dict_class()

        # Keep the order of keys
        for key in keys:
            ret[key] = None

        empty_keys = []
        for packed_key, columns in keymap.iteritems():
            unpacked_key = self._unpack_key(packed_key)
            if len(columns) > 0:
                ret[unpacked_key] = self._cosc_to_dict(columns, include_timestamp, include_ttl)
            else:
                empty_keys.append(unpacked_key)

        for key in empty_keys:
            try:
                del ret[key]
            except KeyError:
                pass

        return ret

    MAX_COUNT = 2 ** 31 - 1

    def get_count(self, key, super_column=None, read_consistency_level=None,
                  columns=None, column_start="", column_finish="",
                  column_reversed=False, max_count=None):
        """
        Count the number of columns in the row with key `key`.

        You may limit the columns or super columns counted to those in `columns`.
        Additionally, you may limit the columns or super columns counted to
        only those between `column_start` and `column_finish`.

        You may also count only the number of subcolumns in a single super column
        using `super_column`.  If this is set, `columns`, `column_start`, and
        `column_finish` only apply to the subcolumns of `super_column`.

        To put an upper bound on the number of columns that are counted,
        set `max_count`.

        """
        if max_count is None:
            max_count = self.MAX_COUNT

        packed_key = self._pack_key(key)
        cp = self._column_parent(super_column)
        sp = self._slice_predicate(columns, column_start, column_finish,
                                   column_reversed, max_count, super_column)

        return self.pool.execute('get_count', packed_key, cp, sp,
                read_consistency_level or self.read_consistency_level)

    def multiget_count(self, keys, super_column=None,
                       read_consistency_level=None,
                       columns=None, column_start="",
                       column_finish="", buffer_size=None,
                       column_reversed=False, max_count=None):
        """
        Perform a column count in parallel on a set of rows.

        The parameters are the same as for :meth:`multiget()`, except that a list
        of keys may be used. A dictionary of the form ``{key: int}`` is
        returned.

        `buffer_size` is the number of rows from the total list to count at a time.
        If left as ``None``, the ColumnFamily's :attr:`buffer_size` will be used.

        To put an upper bound on the number of columns that are counted,
        set `max_count`.

        """
        if max_count is None:
            max_count = self.MAX_COUNT

        packed_keys = map(self._pack_key, keys)
        cp = self._column_parent(super_column)
        sp = self._slice_predicate(columns, column_start, column_finish,
                                   column_reversed, max_count, super_column)
        consistency = read_consistency_level or self.read_consistency_level

        buffer_size = buffer_size or self.buffer_size
        offset = 0
        keymap = {}
        while offset < len(packed_keys):
            new_keymap = self.pool.execute('multiget_count',
                packed_keys[offset:offset + buffer_size], cp, sp, consistency)
            keymap.update(new_keymap)
            offset += buffer_size

        ret = self.dict_class()

        # Keep the order of keys
        for key in keys:
            ret[key] = None

        for packed_key, count in keymap.iteritems():
            ret[self._unpack_key(packed_key)] = count

        return ret

    def get_range(self, start="", finish="", columns=None, column_start="",
                  column_finish="", column_reversed=False, column_count=100,
                  row_count=None, include_timestamp=False,
                  super_column=None, read_consistency_level=None,
                  buffer_size=None, filter_empty=True, include_ttl=False,
                  start_token=None, finish_token=None):
        """
        Get an iterator over rows in a specified key range.

        The key range begins with `start` and ends with `finish`. If left
        as empty strings, these extend to the beginning and end, respectively.
        Note that if RandomPartitioner is used, rows are stored in the
        order of the MD5 hash of their keys, so getting a lexicographical range
        of keys is not feasible.

        In place of `start` and `finish`, you may use `start_token` and
        `finish_token` or a combination of `start` and `finish_token`.  In this
        case, you are specifying a token range to fetch instead of a key
        range.  This can be useful for fetching all data owned
        by a node or for parallelizing a full data set scan. Otherwise,
        you should typically just use `start` and `finish`.  When using
        RandomPartitioner or Murmur3Partitioner, `start_token`
        and `finish_token` should be string versions of the numeric tokens;
        for ByteOrderedPartitioner, they should be hex-encoded string versions
        of the token.

        The `row_count` parameter limits the total number of rows that may be
        returned. If left as ``None``, the number of rows that may be returned
        is unlimited (this is the default).

        When calling `get_range()`, the intermediate results need to be
        buffered if we are fetching many rows, otherwise the Cassandra
        server will overallocate memory and fail. `buffer_size` is the
        size of that buffer in number of rows. If left as ``None``, the
        ColumnFamily's :attr:`buffer_size` attribute will be used.

        When `filter_empty` is left as ``True``, empty rows (including
        `range ghosts <http://wiki.apache.org/cassandra/FAQ#range_ghosts>`_)
        will be skipped and will not count towards `row_count`.

        All other parameters are the same as those of :meth:`get()`.

        A generator over ``(key, {column_name: column_value})`` is returned.
        To convert this to a list, use ``list()`` on the result.

        """

        cl = read_consistency_level or self.read_consistency_level
        cp = self._column_parent(super_column)
        sp = self._slice_predicate(columns, column_start, column_finish,
                                   column_reversed, column_count, super_column)

        kr_args = {}
        count = 0
        i = 0

        if start_token is not None and (start not in ("", None) or finish not in ("", None)):
            raise ValueError(
                "ColumnFamily.get_range() received incompatible arguments: "
                "'start_token' may not be used with 'start' or 'finish'")

        if finish_token is not None and finish not in ("", None):
            raise ValueError(
                "ColumnFamily.get_range() received incompatible arguments: "
                "'finish_token' may not be used with 'finish'")

        if start_token is not None:
            kr_args['start_token'] = start_token
            kr_args['end_token'] = "" if finish_token is None else finish_token
        elif finish_token is not None:
            kr_args['start_key'] = self._pack_key(start)
            kr_args['end_token'] = finish_token
        else:
            kr_args['start_key'] = self._pack_key(start)
            kr_args['end_key'] = self._pack_key(finish)

        if buffer_size is None:
            buffer_size = self.buffer_size
        while True:
            if row_count is not None:
                if i == 0 and row_count <= buffer_size:
                    # We don't need to chunk, grab exactly the number of rows
                    buffer_size = row_count
                else:
                    buffer_size = min(row_count - count + 1, buffer_size)
            kr_args['count'] = buffer_size
            key_range = KeyRange(**kr_args)
            key_slices = self.pool.execute('get_range_slices', cp, sp, key_range, cl)
            # This may happen if nothing was ever inserted
            if key_slices is None:
                return
            for j, key_slice in enumerate(key_slices):
                # Ignore the first element after the first iteration
                # because it will be a duplicate.
                if j == 0 and i != 0:
                    continue
                if filter_empty and not key_slice.columns:
                    continue
                yield (self._unpack_key(key_slice.key),
                       self._cosc_to_dict(key_slice.columns, include_timestamp, include_ttl))
                count += 1
                if row_count is not None and count >= row_count:
                    return

            if len(key_slices) != buffer_size:
                return
            if 'start_token' in kr_args:
                del kr_args['start_token']
            kr_args['start_key'] = key_slices[-1].key
            i += 1

    def insert(self, key, columns, timestamp=None, ttl=None,
               write_consistency_level=None):
        """
        Insert or update columns in the row with key `key`.

        `columns` should be a dictionary of columns or super columns to insert
        or update.  If this is a standard column family, `columns` should
        look like ``{column_name: column_value}``.  If this is a super
        column family, `columns` should look like
        ``{super_column_name: {sub_column_name: value}}``.  If this is a
        counter column family, you may use integers as values and those will
        be used as counter adjustments.

        A timestamp may be supplied for all inserted columns with `timestamp`.

        `ttl` sets the "time to live" in number of seconds for the inserted
        columns. After this many seconds, Cassandra will mark the columns as
        deleted.

        The timestamp Cassandra reports as being used for insert is returned.

        """
        if timestamp is None:
            timestamp = self.timestamp()

        packed_key = self._pack_key(key)
        mut_list = self._make_mutation_list(columns, timestamp, ttl)
        mutations = {packed_key: {self.column_family: mut_list}}
        self.pool.execute('batch_mutate', mutations,
                write_consistency_level or self.write_consistency_level,
                allow_retries=self._allow_retries)

        return timestamp

    def batch_insert(self, rows, timestamp=None, ttl=None, write_consistency_level=None):
        """
        Like :meth:`insert()`, but multiple rows may be inserted at once.

        The `rows` parameter should be of the form ``{key: {column_name: column_value}}``
        if this is a standard column family or
        ``{key: {super_column_name: {column_name: column_value}}}`` if this is a super
        column family.

        """

        if timestamp == None:
            timestamp = self.timestamp()

        cf = self.column_family
        mutations = {}
        for key, columns in rows.iteritems():
            packed_key = self._pack_key(key)
            mut_list = self._make_mutation_list(columns, timestamp, ttl)
            mutations[packed_key] = {cf: mut_list}

        if mutations:
            self.pool.execute('batch_mutate', mutations,
                    write_consistency_level or self.write_consistency_level,
                    allow_retries=self._allow_retries)

        return timestamp

    def add(self, key, column, value=1, super_column=None, write_consistency_level=None):
        """
        Increment or decrement a counter.

        `value` should be an integer, either positive or negative, to be added
        to a counter column. By default, `value` is 1.

        .. versionadded:: 1.1.0
            Available in Cassandra 0.8.0 and later.

        """
        packed_key = self._pack_key(key)
        cp = self._column_parent(super_column)
        column = self._pack_name(column)
        self.pool.execute('add', packed_key, cp, CounterColumn(column, value),
                          write_consistency_level or self.write_consistency_level,
                          allow_retries=self._allow_retries)

    def remove(self, key, columns=None, super_column=None,
               write_consistency_level=None, timestamp=None, counter=None):
        """
        Remove a specified row or a set of columns within the row with key `key`.

        A set of columns or super columns to delete may be specified using
        `columns`.

        A single super column may be deleted by setting `super_column`. If
        `super_column` is specified, `columns` will apply to the subcolumns
        of `super_column`.

        If `columns` and `super_column` are both ``None``, the entire row is
        removed.

        The timestamp used for the mutation is returned.
        """

        if timestamp is None:
            timestamp = self.timestamp()
        batch = self.batch(write_consistency_level=write_consistency_level)
        batch.remove(key, columns, super_column, timestamp)
        batch.send()
        return timestamp

    def remove_counter(self, key, column, super_column=None, write_consistency_level=None):
        """
        Remove a counter at the specified location.

        Note that counters have limited support for deletes: if you remove a
        counter, you must wait to issue any following update until the delete
        has reached all the nodes and all of them have been fully compacted.

        .. versionadded:: 1.1.0
            Available in Cassandra 0.8.0 and later.

        """
        packed_key = self._pack_key(key)
        cp = self._column_path(super_column, column)
        self.pool.execute('remove_counter', packed_key, cp,
                          write_consistency_level or self.write_consistency_level)

    def batch(self, queue_size=100, write_consistency_level=None, atomic=None):
        """
        Create batch mutator for doing multiple insert, update, and remove
        operations using as few roundtrips as possible.

        The `queue_size` parameter sets the max number of mutations per request.

        A :class:`~pycassa.batch.CfMutator` is returned.

        """

        return CfMutator(self, queue_size,
                         write_consistency_level or self.write_consistency_level,
                         allow_retries=self._allow_retries,
                         atomic=atomic)

    def truncate(self):
        """
        Marks the entire ColumnFamily as deleted.

        From the user's perspective, a successful call to ``truncate`` will
        result complete data deletion from this column family. Internally,
        however, disk space will not be immediately released, as with all
        deletes in Cassandra, this one only marks the data as deleted.

        The operation succeeds only if all hosts in the cluster at available
        and will throw an :exc:`.UnavailableException` if some hosts are
        down.

        """
        self.pool.execute('truncate', self.column_family)

PooledColumnFamily = ColumnFamily