Example #1
0
        public void EncodeDecodeListSetFactoryTest()
        {
            var initialValues = new object[]
            {
                new object[] { new List <int>(new [] { 1, 2, 1000 }), ColumnTypeCode.List, new ListColumnInfo()
                               {
                                   ValueTypeCode = ColumnTypeCode.Int
                               } },
                new object[] { new List <double>(new [] { -1D, 2.333D, 1.2D }), ColumnTypeCode.List, new ListColumnInfo()
                               {
                                   ValueTypeCode = ColumnTypeCode.Double
                               } },
                new object[] { new List <decimal>(new [] { -1M, 2.333M, 1.2M, 256M }), ColumnTypeCode.Set, new SetColumnInfo()
                               {
                                   KeyTypeCode = ColumnTypeCode.Decimal
                               } }
            };

            foreach (var version in _protocolVersions)
            {
                foreach (object[] value in initialValues)
                {
                    var valueToEncode = (IList)value[0];
                    var encoded       = TypeCodec.Encode(version, valueToEncode);
                    var decoded       = (IList)TypeCodec.Decode(version, encoded, (ColumnTypeCode)value[1], (IColumnInfo)value[2], value[0].GetType());
                    Assert.AreEqual(valueToEncode.Count, decoded.Count);
                    Assert.AreEqual(valueToEncode, decoded);
                }
            }
        }
Example #2
0
        public override byte[] Encode(IFieldValue fieldValue, Group encodeTemplate, Context context,
                                      BitVectorBuilder presenceMapBuilder)
        {
            IDictionary dict = context.GetDictionary(Dictionary);

            ScalarValue priorValue = context.Lookup(dict, encodeTemplate, Key);
            var         value      = (ScalarValue)fieldValue;

            if (!_operatorCodec.CanEncode(value, this))
            {
                Global.ErrorHandler.OnError(null, DynError.CantEncodeValue,
                                            "The scalar {0} cannot encode the value {1}", this, value);
            }
            ScalarValue valueToEncode = _operatorCodec.GetValueToEncode(value, priorValue, this,
                                                                        presenceMapBuilder);

            if (_operator.ShouldStoreValue(value))
            {
                context.Store(dict, encodeTemplate, Key, value);
            }
            if (valueToEncode == null)
            {
                return(ByteUtil.EmptyByteArray);
            }
            byte[] encoding = _typeCodec.Encode(valueToEncode);
            if (context.TraceEnabled && encoding.Length > 0)
            {
                context.EncodeTrace.Field(this, fieldValue, valueToEncode, encoding, presenceMapBuilder.Index);
            }
            return(encoding);
        }
Example #3
0
        public void PreparedStatement_Bind_SetsRoutingKey_Single()
        {
            const int protocolVersion = 2;
            var       metadata        = new RowSetMetadata(null)
            {
                Columns = new[]
                {
                    new CqlColumn {
                        Name = "name"
                    },
                    new CqlColumn {
                        Name = "id"
                    }
                }
            };
            var ps = GetPrepared("SELECT * FROM tbl1 WHERE name = ? and id = ?", metadata, protocolVersion);

            ps.SetPartitionKeys(new[] { new TableColumn()
                                        {
                                            Name = "id"
                                        } });
            //The routing key is at position 1
            CollectionAssert.AreEqual(new[] { 1 }, ps.RoutingIndexes);
            Assert.Null(ps.RoutingKey);
            var bound = ps.Bind("dummy name", 1000);

            Assert.NotNull(bound.RoutingKey);
            CollectionAssert.AreEqual(TypeCodec.Encode(protocolVersion, 1000), bound.RoutingKey.RawRoutingKey);
        }
Example #4
0
        public void EncodeDecodeNestedSet()
        {
            var initialValues = new object[]
            {
                new object[] { new SortedSet <IEnumerable <int> > {
                                   new SortedSet <int>(new [] { 1, 2, 1000 })
                               }, ColumnTypeCode.Set, GetNestedSetColumnInfo(1, ColumnTypeCode.Int) },
                new object[] { new SortedSet <IEnumerable <IEnumerable <int> > > {
                                   new SortedSet <IEnumerable <int> > {
                                       new SortedSet <int>(new [] { 1, 2, 1000 })
                                   }
                               }, ColumnTypeCode.Set, GetNestedSetColumnInfo(2, ColumnTypeCode.Int) }
            };

            foreach (var version in _protocolVersions)
            {
                foreach (object[] value in initialValues)
                {
                    var originalType  = value[0].GetType();
                    var valueToEncode = (IEnumerable)value[0];
                    var encoded       = TypeCodec.Encode(version, valueToEncode);
                    var decoded       = (IEnumerable)TypeCodec.Decode(version, encoded, (ColumnTypeCode)value[1], (IColumnInfo)value[2], originalType);
                    //The return type is not respected
                    CollectionAssert.AreEqual(valueToEncode, decoded);
                }
            }
        }
        public static Row CreateRow(IDictionary <string, object> valueMap)
        {
            var columns   = new List <CqlColumn>();
            var rowValues = new List <byte[]>();

            foreach (var kv in valueMap)
            {
                if (kv.Value != null)
                {
                    IColumnInfo typeInfo;
                    var         typeCode = TypeCodec.GetColumnTypeCodeInfo(kv.Value.GetType(), out typeInfo);
                    columns.Add(new CqlColumn()
                    {
                        Name = kv.Key, TypeCode = typeCode, TypeInfo = typeInfo
                    });
                }
                else
                {
                    columns.Add(new CqlColumn()
                    {
                        Name = kv.Key, TypeCode = ColumnTypeCode.Text
                    });
                }
                rowValues.Add(TypeCodec.Encode(2, kv.Value));
            }
            var i = 0;

            return(new Row(2, rowValues.ToArray(), columns.ToArray(), valueMap.ToDictionary(kv => kv.Key, kv => i++)));
        }
Example #6
0
        public void EncodeDecodeSingleValuesFactoryTest()
        {
            var initialValues = new object[]
            {
                new object[] { "just utf8 text olé!", ColumnTypeCode.Text },
                new object[] { "just ascii text", ColumnTypeCode.Ascii },
                new object[] { 123, ColumnTypeCode.Int },
                new object[] { Int64.MinValue + 100, ColumnTypeCode.Bigint },
                new object[] { 44F, ColumnTypeCode.Float },
                new object[] { -320D, ColumnTypeCode.Double },
                new object[] { 99.89770M, ColumnTypeCode.Decimal },
                new object[] { Decimal.MaxValue, ColumnTypeCode.Decimal },
                new object[] { new DateTime(2010, 4, 29), ColumnTypeCode.Timestamp },
                new object[] { new DateTimeOffset(new DateTime(2010, 4, 29)), ColumnTypeCode.Timestamp },
                new object[] { new IPAddress(new byte[] { 10, 0, 5, 5 }), ColumnTypeCode.Inet },
                new object[] { Guid.NewGuid(), ColumnTypeCode.Uuid },
                new object[] { false, ColumnTypeCode.Boolean },
                new object[] { new byte [] { 1, 2 }, ColumnTypeCode.Blob }
            };

            foreach (var version in _protocolVersions)
            {
                foreach (object[] value in initialValues)
                {
                    byte[] encoded = TypeCodec.Encode(version, value[0]);
                    Assert.AreEqual(value[0], TypeCodec.Decode(version, encoded, (ColumnTypeCode)value[1], null, value[0].GetType()));
                }
            }
        }
Example #7
0
        public void Encode_Decode_Nested_List()
        {
            var initialValues = new object[]
            {
                new object[] { new List <IEnumerable <int> > {
                                   new List <int>(new [] { 1, 2, 1000 })
                               }, ColumnTypeCode.List, GetNestedListColumnInfo(1, ColumnTypeCode.Int) },
                new object[] { new List <IEnumerable <IEnumerable <int> > > {
                                   new List <IEnumerable <int> > {
                                       new List <int>(new [] { 1, 2, 1000 })
                                   }
                               }, ColumnTypeCode.List, GetNestedListColumnInfo(2, ColumnTypeCode.Int) }
            };

            foreach (var version in _protocolVersions)
            {
                foreach (object[] value in initialValues)
                {
                    var originalType  = value[0].GetType();
                    var valueToEncode = (IEnumerable)value[0];
                    var encoded       = TypeCodec.Encode(version, valueToEncode);
                    var decoded       = (IEnumerable)TypeCodec.Decode(version, encoded, (ColumnTypeCode)value[1], (IColumnInfo)value[2], originalType);
                    Assert.IsInstanceOf(originalType, decoded);
                    CollectionAssert.AreEqual(valueToEncode, decoded);
                }
            }
        }
Example #8
0
        public void EncodeDecodeSingleValuesDefaultsFactory()
        {
            var initialValues = new object[]
            {
                new object[] { "just utf8 text olé!", ColumnTypeCode.Text },
                new object[] { 123, ColumnTypeCode.Int },
                new object[] { Int64.MinValue + 100, ColumnTypeCode.Bigint },
                new object[] { -144F, ColumnTypeCode.Float },
                new object[] { 1120D, ColumnTypeCode.Double },
                new object[] { -9999.89770M, ColumnTypeCode.Decimal },
                new object[] { -256M, ColumnTypeCode.Decimal },
                new object[] { new DateTimeOffset(new DateTime(2010, 4, 29)), ColumnTypeCode.Timestamp },
                new object[] { new IPAddress(new byte[] { 10, 0, 5, 5 }), ColumnTypeCode.Inet },
                new object[] { Guid.NewGuid(), ColumnTypeCode.Uuid },
                new object[] { true, ColumnTypeCode.Boolean },
                new object[] { new byte [] { 255, 128, 64, 32, 16, 9, 9 }, ColumnTypeCode.Blob }
            };

            foreach (var version in _protocolVersions)
            {
                foreach (object[] value in initialValues)
                {
                    byte[] encoded = TypeCodec.Encode(version, value[0]);
                    //Set object as the target CSharp type, it should get the default value
                    Assert.AreEqual(value[0], TypeCodec.Decode(version, encoded, (ColumnTypeCode)value[1], null, typeof(object)));
                }
            }
        }
Example #9
0
        //TODO: Move to ExecuteRequest and QueryRequest
        internal void Write(FrameWriter wb, byte protocolVersion, bool isPrepared)
        {
            //protocol v1: <query><n><value_1>....<value_n><consistency>
            //protocol v2: <query><consistency><flags>[<n><value_1>...<value_n>][<result_page_size>][<paging_state>][<serial_consistency>]
            //protocol v3: <query><consistency><flags>[<n>[name_1]<value_1>...[name_n]<value_n>][<result_page_size>][<paging_state>][<serial_consistency>][<timestamp>]
            var flags = GetFlags();

            if (protocolVersion > 1)
            {
                wb.WriteUInt16((ushort)Consistency);
                wb.WriteByte((byte)flags);
            }

            if (flags.HasFlag(QueryFlags.Values))
            {
                wb.WriteUInt16((ushort)Values.Length);
                for (var i = 0; i < Values.Length; i++)
                {
                    if (flags.HasFlag(QueryFlags.WithNameForValues))
                    {
                        var name = ValueNames[i];
                        wb.WriteString(name);
                    }
                    var v     = Values[i];
                    var bytes = TypeCodec.Encode(protocolVersion, v);
                    wb.WriteBytes(bytes);
                }
            }
            else if (protocolVersion == 1 && isPrepared)
            {
                //n values is not optional on protocol v1
                //Write 0 values
                wb.WriteUInt16(0);
            }

            if (protocolVersion == 1)
            {
                //Protocol v1 ends here
                wb.WriteUInt16((ushort)Consistency);
                return;
            }
            if ((flags & QueryFlags.PageSize) == QueryFlags.PageSize)
            {
                wb.WriteInt32(PageSize);
            }
            if ((flags & QueryFlags.WithPagingState) == QueryFlags.WithPagingState)
            {
                wb.WriteBytes(PagingState);
            }
            if ((flags & QueryFlags.WithSerialConsistency) == QueryFlags.WithSerialConsistency)
            {
                wb.WriteUInt16((ushort)SerialConsistency);
            }
            if (Timestamp != null)
            {
                //Expressed in microseconds
                wb.WriteLong(TypeCodec.ToUnixTime(Timestamp.Value).Ticks / 10);
            }
        }
Example #10
0
        public void EncodeDecodeTupleAsSubtypeFactoryTest()
        {
            const int version       = 3;
            var       initialValues = new object[]
            {
                new object[]
                {
                    new List <Tuple <string> > {
                        new Tuple <string>("val1")
                    },
                    ColumnTypeCode.List,
                    new ListColumnInfo {
                        ValueTypeCode = ColumnTypeCode.Tuple, ValueTypeInfo = new TupleColumnInfo()
                        {
                            Elements = new List <ColumnDesc>()
                            {
                                new ColumnDesc()
                                {
                                    TypeCode = ColumnTypeCode.Text
                                }
                            }
                        }
                    }
                },
                new object[]
                {
                    new List <Tuple <string, int> > {
                        new Tuple <string, int>("val2ZZ", 0)
                    },
                    ColumnTypeCode.List,
                    new ListColumnInfo {
                        ValueTypeCode = ColumnTypeCode.Tuple, ValueTypeInfo = new TupleColumnInfo()
                        {
                            Elements = new List <ColumnDesc>()
                            {
                                new ColumnDesc()
                                {
                                    TypeCode = ColumnTypeCode.Text
                                }, new ColumnDesc()
                                {
                                    TypeCode = ColumnTypeCode.Int
                                }
                            }
                        }
                    }
                }
            };

            foreach (object[] value in initialValues)
            {
                var valueToEncode = (IList)value[0];
                var encoded       = TypeCodec.Encode(version, valueToEncode);
                var decoded       = (IList)TypeCodec.Decode(version, encoded, (ColumnTypeCode)value[1], (IColumnInfo)value[2]);
                Assert.AreEqual(valueToEncode, decoded);
            }
        }
Example #11
0
        public void BatchStatement_Bind_SetsRoutingValues_Single()
        {
            const int protocolVersion = 2;
            var       batch           = new BatchStatement();

            Assert.Null(batch.RoutingKey);
            batch.SetRoutingValues("id1-value");
            batch.ProtocolVersion = protocolVersion;
            CollectionAssert.AreEqual(TypeCodec.Encode(protocolVersion, "id1-value"), batch.RoutingKey.RawRoutingKey);
        }
Example #12
0
        public void SimpleStatement_Bind_SetsRoutingValues_Single()
        {
            const int protocolVersion = 2;
            var       stmt            = new SimpleStatement(Query, "id1");

            Assert.Null(stmt.RoutingKey);
            stmt.SetRoutingValues("id1");
            stmt.ProtocolVersion = protocolVersion;
            CollectionAssert.AreEqual(TypeCodec.Encode(protocolVersion, "id1"), stmt.RoutingKey.RawRoutingKey);
        }
Example #13
0
        public void EncodeDecodeNestedMap()
        {
            var initialValues = new object[]
            {
                new object[] {
                    new SortedDictionary <string, IEnumerable <int> > {
                        { "first", new List <int>(new [] { 1, 2, 1000 }) }
                    },
                    ColumnTypeCode.Map,
                    new MapColumnInfo {
                        KeyTypeCode = ColumnTypeCode.Text, ValueTypeCode = ColumnTypeCode.List, ValueTypeInfo = new ListColumnInfo {
                            ValueTypeCode = ColumnTypeCode.Int
                        }
                    }
                },
                new object[] {
                    new SortedDictionary <int, IEnumerable <string> > {
                        { 120, new SortedSet <string>(new [] { "a", "b", "c" }) }
                    },
                    ColumnTypeCode.Map,
                    new MapColumnInfo {
                        KeyTypeCode = ColumnTypeCode.Int, ValueTypeCode = ColumnTypeCode.Set, ValueTypeInfo = new SetColumnInfo {
                            KeyTypeCode = ColumnTypeCode.Text
                        }
                    }
                },
                new object[] {
                    new SortedDictionary <string, IDictionary <string, int> > {
                        { "first-b", new SortedDictionary <string, int> {
                              { "A", 1 }, { "B", 2 }
                          } }
                    },
                    ColumnTypeCode.Map,
                    new MapColumnInfo {
                        KeyTypeCode = ColumnTypeCode.Text, ValueTypeCode = ColumnTypeCode.Map, ValueTypeInfo = new MapColumnInfo {
                            KeyTypeCode = ColumnTypeCode.Text, ValueTypeCode = ColumnTypeCode.Int
                        }
                    }
                }
            };

            foreach (var version in _protocolVersions)
            {
                foreach (object[] value in initialValues)
                {
                    var originalType  = value[0].GetType();
                    var valueToEncode = (IEnumerable)value[0];
                    var encoded       = TypeCodec.Encode(version, valueToEncode);
                    var decoded       = (IEnumerable)TypeCodec.Decode(version, encoded, (ColumnTypeCode)value[1], (IColumnInfo)value[2], originalType);
                    Assert.IsInstanceOf(originalType, decoded);
                    CollectionAssert.AreEqual(valueToEncode, decoded);
                }
            }
        }
Example #14
0
 public void WriteToBatch(byte protocolVersion, BEBinaryWriter wb)
 {
     wb.WriteByte(1); //prepared query
     wb.WriteShortBytes(_id);
     wb.WriteUInt16((ushort)_queryOptions.Values.Length);
     for (int i = 0; i < _metadata.Columns.Length; i++)
     {
         byte[] bytes = TypeCodec.Encode(protocolVersion, _queryOptions.Values[i]);
         wb.WriteBytes(bytes);
     }
 }
Example #15
0
        public void EncodeDecodeTupleFactoryTest()
        {
            const int version       = 3;
            var       initialValues = new object[]
            {
                new object[] { new Tuple <string>("val1"), ColumnTypeCode.Tuple, new TupleColumnInfo()
                               {
                                   Elements = new List <ColumnDesc>()
                                   {
                                       new ColumnDesc()
                                       {
                                           TypeCode = ColumnTypeCode.Text
                                       }
                                   }
                               } },
                new object[] { new Tuple <string, int>("val2", 2), ColumnTypeCode.Tuple, new TupleColumnInfo()
                               {
                                   Elements = new List <ColumnDesc>()
                                   {
                                       new ColumnDesc()
                                       {
                                           TypeCode = ColumnTypeCode.Text
                                       }, new ColumnDesc()
                                       {
                                           TypeCode = ColumnTypeCode.Int
                                       }
                                   }
                               } },
                new object[] { new Tuple <string, int>(null, -1234), ColumnTypeCode.Tuple, new TupleColumnInfo()
                               {
                                   Elements = new List <ColumnDesc>()
                                   {
                                       new ColumnDesc()
                                       {
                                           TypeCode = ColumnTypeCode.Text
                                       }, new ColumnDesc()
                                       {
                                           TypeCode = ColumnTypeCode.Int
                                       }
                                   }
                               } }
            };

            foreach (object[] value in initialValues)
            {
                var valueToEncode = (IStructuralEquatable)value[0];
                var encoded       = TypeCodec.Encode(version, valueToEncode);
                var decoded       = (IStructuralEquatable)TypeCodec.Decode(version, encoded, (ColumnTypeCode)value[1], (IColumnInfo)value[2]);
                Assert.AreEqual(valueToEncode, decoded);
            }
        }
Example #16
0
        public void EncodeDecodeListSetFactoryTest()
        {
            var initialValues = new object[]
            {
                //Lists
                new object[] { new List <int>(new [] { 1, 2, 1000 }), ColumnTypeCode.List, new ListColumnInfo()
                               {
                                   ValueTypeCode = ColumnTypeCode.Int
                               } },
                new object[] { new List <double>(new [] { -1D, 2.333D, 1.2D }), ColumnTypeCode.List, new ListColumnInfo()
                               {
                                   ValueTypeCode = ColumnTypeCode.Double
                               } },
                new object[] { new double[] { 5D, 4.333D, 1.2D }, ColumnTypeCode.List, new ListColumnInfo()
                               {
                                   ValueTypeCode = ColumnTypeCode.Double
                               } },
                //Sets
                new object[] { new List <decimal>(new [] { -1M, 2.333M, 1.2M, 256M }), ColumnTypeCode.Set, new SetColumnInfo()
                               {
                                   KeyTypeCode = ColumnTypeCode.Decimal
                               } },
                new object[] { new SortedSet <string>(new [] { "a", "b", "c" }), ColumnTypeCode.Set, new SetColumnInfo()
                               {
                                   KeyTypeCode = ColumnTypeCode.Text
                               } },
                new object[] { new HashSet <string>(new [] { "ADADD", "AA", "a" }), ColumnTypeCode.Set, new SetColumnInfo()
                               {
                                   KeyTypeCode = ColumnTypeCode.Text
                               } },
                new object[] { new string[] { "ADADD", "AA", "a" }, ColumnTypeCode.Set, new SetColumnInfo()
                               {
                                   KeyTypeCode = ColumnTypeCode.Text
                               } }
            };

            foreach (var version in _protocolVersions)
            {
                foreach (object[] value in initialValues)
                {
                    var originalType  = value[0].GetType();
                    var valueToEncode = (IEnumerable)value[0];
                    var encoded       = TypeCodec.Encode(version, valueToEncode);
                    var decoded       = (IEnumerable)TypeCodec.Decode(version, encoded, (ColumnTypeCode)value[1], (IColumnInfo)value[2], originalType);
                    Assert.IsInstanceOf(originalType, decoded);
                    CollectionAssert.AreEqual(valueToEncode, decoded);
                }
            }
        }
Example #17
0
 internal void CalculateRoutingKey(bool useNamedParameters, int[] routingIndexes, string[] routingNames, object[] valuesByPosition, object[] rawValues)
 {
     if (_routingKey != null)
     {
         //The routing key was specified by the user
         return;
     }
     if (routingIndexes != null)
     {
         var keys = new RoutingKey[routingIndexes.Length];
         for (var i = 0; i < routingIndexes.Length; i++)
         {
             var index = routingIndexes[i];
             var key   = TypeCodec.Encode(ProtocolVersion, valuesByPosition[index]);
             if (key == null)
             {
                 //The partition key can not be null
                 //Get out and let any node reply a Response Error
                 return;
             }
             keys[i] = new RoutingKey(key);
         }
         SetRoutingKey(keys);
         return;
     }
     if (routingNames != null && useNamedParameters)
     {
         var keys          = new RoutingKey[routingNames.Length];
         var routingValues = Utils.GetValues(routingNames, rawValues[0]).ToArray();
         if (routingValues.Length != keys.Length)
         {
             //The routing names are not valid
             return;
         }
         for (var i = 0; i < routingValues.Length; i++)
         {
             var key = TypeCodec.Encode(ProtocolVersion, routingValues[i]);
             if (key == null)
             {
                 //The partition key can not be null
                 return;
             }
             keys[i] = new RoutingKey(key);
         }
         SetRoutingKey(keys);
     }
 }
Example #18
0
        public void EncodeListSetInvalid()
        {
            var values = new object[]
            {
                new List <object>(),
                //any class
                new List <TypeCodecTests>()
            };

            foreach (var version in _protocolVersions)
            {
                foreach (var value in values)
                {
                    Assert.Throws <InvalidTypeException>(() => TypeCodec.Encode(version, value));
                }
            }
        }
Example #19
0
        public void EncodeDecodeMapFactoryTest()
        {
            var initialValues = new object[]
            {
                new object[] { new SortedDictionary <string, string>(), ColumnTypeCode.Map, new MapColumnInfo()
                               {
                                   KeyTypeCode = ColumnTypeCode.Text, ValueTypeCode = ColumnTypeCode.Text
                               } },
                new object[] { new SortedDictionary <string, string> {
                                   { "key100", "value100" }
                               }, ColumnTypeCode.Map, new MapColumnInfo()
                               {
                                   KeyTypeCode = ColumnTypeCode.Text, ValueTypeCode = ColumnTypeCode.Text
                               } },
                new object[] { new SortedDictionary <string, string> {
                                   { "key1", "value1" }, { "key2", "value2" }
                               }, ColumnTypeCode.Map, new MapColumnInfo()
                               {
                                   KeyTypeCode = ColumnTypeCode.Text, ValueTypeCode = ColumnTypeCode.Text
                               } },
                new object[] { new SortedDictionary <string, int> {
                                   { "key1", 1 }, { "key2", 2 }
                               }, ColumnTypeCode.Map, new MapColumnInfo()
                               {
                                   KeyTypeCode = ColumnTypeCode.Text, ValueTypeCode = ColumnTypeCode.Int
                               } },
                new object[] { new SortedDictionary <Guid, string> {
                                   { Guid.NewGuid(), "value1" }, { Guid.NewGuid(), "value2" }
                               }, ColumnTypeCode.Map, new MapColumnInfo()
                               {
                                   KeyTypeCode = ColumnTypeCode.Uuid, ValueTypeCode = ColumnTypeCode.Text
                               } },
            };

            foreach (var version in _protocolVersions)
            {
                foreach (object[] value in initialValues)
                {
                    var valueToEncode = (IDictionary)value[0];
                    var encoded       = TypeCodec.Encode(version, valueToEncode);
                    var decoded       = (IDictionary)TypeCodec.Decode(version, encoded, (ColumnTypeCode)value[1], (IColumnInfo)value[2], typeof(IDictionary));
                    CollectionAssert.AreEquivalent(valueToEncode, decoded);
                }
            }
        }
Example #20
0
        public void BatchStatement_Bind_SetsRoutingValues_Multiple()
        {
            const int protocolVersion = 2;
            var       batch           = new BatchStatement();

            Assert.Null(batch.RoutingKey);
            batch.SetRoutingValues("id11", "id22");
            batch.ProtocolVersion = protocolVersion;
            var expectedRoutingKey = new byte[0]
                                     .Concat(new byte[] { 0, 4 })
                                     .Concat(TypeCodec.Encode(protocolVersion, "id11"))
                                     .Concat(new byte[] { 0 })
                                     .Concat(new byte[] { 0, 4 })
                                     .Concat(TypeCodec.Encode(protocolVersion, "id22"))
                                     .Concat(new byte[] { 0 });

            CollectionAssert.AreEqual(expectedRoutingKey, batch.RoutingKey.RawRoutingKey);
        }
Example #21
0
        public void SimpleStatement_Bind_SetsRoutingValues_Multiple()
        {
            const int protocolVersion = 2;
            var       stmt            = new SimpleStatement(Query, "id1", "id2", "val1");

            Assert.Null(stmt.RoutingKey);
            stmt.SetRoutingValues("id1", "id2");
            stmt.ProtocolVersion = protocolVersion;
            var expectedRoutingKey = new byte[0]
                                     .Concat(new byte[] { 0, 3 })
                                     .Concat(TypeCodec.Encode(protocolVersion, "id1"))
                                     .Concat(new byte[] { 0 })
                                     .Concat(new byte[] { 0, 3 })
                                     .Concat(TypeCodec.Encode(protocolVersion, "id2"))
                                     .Concat(new byte[] { 0 });

            CollectionAssert.AreEqual(expectedRoutingKey, stmt.RoutingKey.RawRoutingKey);
        }
Example #22
0
 public void WriteToBatch(byte protocolVersion, BEBinaryWriter wb)
 {
     //not a prepared query
     wb.WriteByte(0);
     wb.WriteLongString(_cqlQuery);
     if (_queryOptions.Values == null || _queryOptions.Values.Length == 0)
     {
         //not values
         wb.WriteInt16(0);
     }
     else
     {
         wb.WriteUInt16((ushort)_queryOptions.Values.Length);
         for (var i = 0; i < _queryOptions.Values.Length; i++)
         {
             var bytes = TypeCodec.Encode(protocolVersion, _queryOptions.Values[i]);
             wb.WriteBytes(bytes);
         }
     }
 }
Example #23
0
        /// <summary>
        /// Returns a RowSet with 1 column
        /// </summary>
        public static RowSet GetSingleColumnRowSet <T>(string columnName, T[] values)
        {
            var         rs = new RowSet();
            IColumnInfo typeInfo;
            var         typeCode = TypeCodec.GetColumnTypeCodeInfo(typeof(T), out typeInfo);

            rs.Columns = new[]
            {
                new CqlColumn {
                    Name = columnName, TypeCode = typeCode, TypeInfo = typeInfo, Type = typeof(T), Index = 0
                }
            };
            var columnIndexes = rs.Columns.ToDictionary(c => c.Name, c => c.Index);

            foreach (var v in values)
            {
                var row = new Row(ProtocolVersion, new [] { TypeCodec.Encode(ProtocolVersion, v) }, rs.Columns, columnIndexes);
                rs.AddRow(row);
            }
            return(rs);
        }
Example #24
0
        public void PreparedStatement_Bind_SetsRoutingKey_Multiple()
        {
            const int protocolVersion = 2;
            var       metadata        = new RowSetMetadata(null)
            {
                Columns = new[]
                {
                    new CqlColumn {
                        Name = "id2"
                    },
                    new CqlColumn {
                        Name = "id1"
                    }
                }
            };
            var ps = GetPrepared("SELECT * FROM tbl1 WHERE id2 = ? and id1", metadata, protocolVersion);

            ps.SetPartitionKeys(new[] { new TableColumn()
                                        {
                                            Name = "id1"
                                        }, new TableColumn()
                                        {
                                            Name = "id2"
                                        } });
            //The routing key is formed by the parameters at position 1 and 0
            CollectionAssert.AreEqual(new[] { 1, 0 }, ps.RoutingIndexes);
            Assert.Null(ps.RoutingKey);
            var bound = ps.Bind(2001, 1001);

            Assert.NotNull(bound.RoutingKey);
            var expectedRoutingKey = new byte[0]
                                     .Concat(new byte[] { 0, 4 })
                                     .Concat(TypeCodec.Encode(protocolVersion, 1001))
                                     .Concat(new byte[] { 0 })
                                     .Concat(new byte[] { 0, 4 })
                                     .Concat(TypeCodec.Encode(protocolVersion, 2001))
                                     .Concat(new byte[] { 0 });

            CollectionAssert.AreEqual(expectedRoutingKey, bound.RoutingKey.RawRoutingKey);
        }
Example #25
0
        public void Fetch_Maps_NullableDateTime_Test()
        {
            var rs = new RowSet
            {
                Columns = new[]
                {
                    new CqlColumn {
                        Name = "id", TypeCode = ColumnTypeCode.Uuid, Type = typeof(Guid), Index = 0
                    },
                    new CqlColumn {
                        Name = "title", TypeCode = ColumnTypeCode.Text, Type = typeof(string), Index = 1
                    },
                    new CqlColumn {
                        Name = "releasedate", TypeCode = ColumnTypeCode.Timestamp, Type = typeof(DateTimeOffset), Index = 2
                    }
                }
            };
            var values = new object[] { Guid.NewGuid(), "Come Away with Me", DateTimeOffset.Parse("2002-01-01 +0") }
            .Select(v => TypeCodec.Encode(2, v));
            var row = new Row(2, values.ToArray(), rs.Columns, rs.Columns.ToDictionary(c => c.Name, c => c.Index));

            rs.AddRow(row);
            var sessionMock = new Mock <ISession>(MockBehavior.Strict);

            sessionMock
            .Setup(s => s.ExecuteAsync(It.IsAny <BoundStatement>()))
            .Returns(TestHelper.DelayedTask(rs, 100))
            .Verifiable();
            sessionMock
            .Setup(s => s.PrepareAsync(It.IsAny <string>()))
            .Returns(TaskHelper.ToTask(GetPrepared()))
            .Verifiable();
            var mapper = GetMappingClient(sessionMock);
            var song   = mapper.Fetch <Song2>(new Cql("SELECT * FROM songs")).First();

            Assert.AreEqual("Come Away with Me", song.Title);
            Assert.AreEqual(DateTimeOffset.Parse("2002-01-01 +0").DateTime, song.ReleaseDate);
        }
Example #26
0
        T[] FetchAnonymous <T>(Func <Song2, T> justHereToCreateAnonymousType)
        {
            var rs = new RowSet
            {
                Columns = new[]
                {
                    new CqlColumn {
                        Name = "title", TypeCode = ColumnTypeCode.Text, Type = typeof(string), Index = 0
                    },
                    new CqlColumn {
                        Name = "releasedate", TypeCode = ColumnTypeCode.Timestamp, Type = typeof(DateTimeOffset), Index = 1
                    }
                }
            };
            var values = new object[] { "Come Away with Me", DateTimeOffset.Parse("2002-01-01 +0") }
            .Select(v => TypeCodec.Encode(2, v));
            var row = new Row(2, values.ToArray(), rs.Columns, rs.Columns.ToDictionary(c => c.Name, c => c.Index));

            rs.AddRow(row);
            values = new object[] { "Come Away with Me", null }
            .Select(v => TypeCodec.Encode(2, v));
            row = new Row(2, values.ToArray(), rs.Columns, rs.Columns.ToDictionary(c => c.Name, c => c.Index));
            rs.AddRow(row);
            var sessionMock = new Mock <ISession>(MockBehavior.Strict);

            sessionMock
            .Setup(s => s.ExecuteAsync(It.IsAny <BoundStatement>()))
            .Returns(TestHelper.DelayedTask(rs, 100))
            .Verifiable();
            sessionMock
            .Setup(s => s.PrepareAsync(It.IsAny <string>()))
            .Returns(TaskHelper.ToTask(GetPrepared()))
            .Verifiable();
            var mapper = GetMappingClient(sessionMock);

            return(mapper.Fetch <T>(new Cql("SELECT title,releasedate FROM songs")).ToArray());
        }
Example #27
0
        public static RowSet CreateMultipleValuesRowSet <T>(string[] columnNames, T[] genericValues, int rowLength = 1)
        {
            var rs = new RowSet();

            rs.Columns = new CqlColumn[columnNames.Length];
            for (var i = 0; i < columnNames.Length; i++)
            {
                IColumnInfo typeInfo;
                var         type = typeof(T);
                if (type == typeof(Object))
                {
                    //Try to guess by value
                    if (genericValues[i] == null)
                    {
                        throw new Exception("Test data could not be generated, value at index " + i + " could not be encoded");
                    }
                    type = genericValues[i].GetType();
                }
                var typeCode = TypeCodec.GetColumnTypeCodeInfo(type, out typeInfo);
                rs.Columns[i] =
                    new CqlColumn {
                    Name = columnNames[i], TypeCode = typeCode, TypeInfo = typeInfo, Type = typeof(T), Index = i
                };
            }
            var columnIndexes = rs.Columns.ToDictionary(c => c.Name, c => c.Index);

            for (var i = 0; i < rowLength; i++)
            {
                var values = genericValues
                             .Select(v => TypeCodec.Encode(ProtocolVersion, v))
                             .ToArray();
                var row = new Row(ProtocolVersion, values, rs.Columns, columnIndexes);
                rs.AddRow(row);
            }
            return(rs);
        }
Example #28
0
 protected static void AssertEncodeDecode(ScalarValue value, String bitString, TypeCodec type)
 {
     Assert.AreEqual(ByteUtil.ConvertBitStringToFastByteArray(bitString), type.Encode(value ?? ScalarValue.Null));
     Assert.AreEqual(value, type.Decode(ByteUtil.CreateByteStream(bitString)));
 }
Example #29
0
        public static RowSet GetUsersRowSet(IEnumerable <PlainUser> users)
        {
            var rs = new RowSet();

            rs.Columns = new[]
            {
                new CqlColumn {
                    Name = "userid", TypeCode = ColumnTypeCode.Uuid, Type = typeof(Guid), Index = 0
                },
                new CqlColumn {
                    Name = "name", TypeCode = ColumnTypeCode.Text, Type = typeof(string), Index = 1
                },
                new CqlColumn {
                    Name = "age", TypeCode = ColumnTypeCode.Int, Type = typeof(int), Index = 2
                },
                new CqlColumn {
                    Name = "createddate", TypeCode = ColumnTypeCode.Timestamp, Type = typeof(DateTimeOffset), Index = 3
                },
                new CqlColumn {
                    Name = "isactive", TypeCode = ColumnTypeCode.Boolean, Type = typeof(bool), Index = 4
                },
                new CqlColumn {
                    Name = "lastlogindate", TypeCode = ColumnTypeCode.Timestamp, Type = typeof(DateTimeOffset), Index = 5
                },
                new CqlColumn {
                    Name = "loginhistory", TypeCode = ColumnTypeCode.List, TypeInfo = new ListColumnInfo {
                        ValueTypeCode = ColumnTypeCode.Timestamp
                    }, Type = typeof(List <DateTimeOffset>), Index = 6
                },
                new CqlColumn {
                    Name = "luckynumbers", TypeCode = ColumnTypeCode.Set, TypeInfo = new SetColumnInfo {
                        KeyTypeCode = ColumnTypeCode.Int
                    }, Type = typeof(HashSet <int>), Index = 7
                },
                new CqlColumn {
                    Name = "childrenages", TypeCode = ColumnTypeCode.Map, TypeInfo = new MapColumnInfo {
                        KeyTypeCode = ColumnTypeCode.Text, ValueTypeCode = ColumnTypeCode.Int
                    }, Type = typeof(IDictionary <string, int>), Index = 8
                },
                new CqlColumn {
                    Name = "favoritecolor", TypeCode = ColumnTypeCode.Int, Type = typeof(int), Index = 9
                },
                new CqlColumn {
                    Name = "typeofuser", TypeCode = ColumnTypeCode.Int, Type = typeof(int), Index = 10
                },
                new CqlColumn {
                    Name = "preferredcontactmethod", TypeCode = ColumnTypeCode.Int, Type = typeof(int), Index = 11
                },
                new CqlColumn {
                    Name = "haircolor", TypeCode = ColumnTypeCode.Int, Type = typeof(int), Index = 12
                },
            };
            var columnIndexes = rs.Columns.ToDictionary(c => c.Name, c => c.Index);

            foreach (var user in users)
            {
                var values = new List <object>
                {
                    user.UserId,
                    user.Name,
                    user.Age,
                    user.CreatedDate,
                    user.IsActive,
                    user.LastLoginDate,
                    user.LoginHistory,
                    user.LuckyNumbers,
                    user.ChildrenAges,
                    (int)user.FavoriteColor,
                    (int?)user.TypeOfUser,
                    (int)user.PreferredContactMethod,
                    (int?)user.HairColor
                }.Select(v => TypeCodec.Encode(ProtocolVersion, v));
                var row = new Row(ProtocolVersion, values.ToArray(), rs.Columns, columnIndexes);
                rs.AddRow(row);
            }
            return(rs);
        }
Example #30
0
 protected static void AssertEncodeDecode(ScalarValue value, String bitString, TypeCodec type)
 {
     Assert.AreEqual(bitString, type.Encode(value ?? ScalarValue.NULL));
     Assert.AreEqual(value, type.Decode(ByteUtil.CreateByteStream(bitString)));
 }