Example #1
0
        public void Create_With_Frozen_Collection_Value()
        {
            string createQuery = null;
            var    sessionMock = new Mock <ISession>();

            sessionMock
            .Setup(s => s.Execute(It.IsAny <string>()))
            .Returns(() => new RowSet())
            .Callback <string>(q => createQuery = q);
            var definition = new Map <UdtAndTuplePoco>()
                             .PartitionKey(c => c.Id1)
                             .Column(c => c.Id1, cm => cm.WithName("id"))
                             .Column(c => c.UdtList1, cm => cm.WithName("my_list").WithFrozenValue())
                             .Column(c => c.TupleMapValue1, cm => cm.WithName("my_map").WithFrozenValue())
                             .ExplicitColumns()
                             .TableName("tbl1");
            var udtInfo = new UdtColumnInfo("song");

            udtInfo.Fields.Add(new ColumnDesc {
                Name = "title", TypeCode = ColumnTypeCode.Ascii
            });
            udtInfo.Fields.Add(new ColumnDesc {
                Name = "releasedate", TypeCode = ColumnTypeCode.Timestamp
            });
            var udtMap = UdtMap.For <Song>();

            udtMap.Build(udtInfo);
            TypeCodec.SetUdtMap("song", udtMap);
            var table = GetTable <UdtAndTuplePoco>(sessionMock.Object, definition);

            table.Create();
            Assert.AreEqual("CREATE TABLE tbl1 (id uuid, my_list list<frozen<song>>, my_map map<text, frozen<tuple<double, double>>>, PRIMARY KEY (id))", createQuery);
        }
Example #2
0
        public RequestFrame GetFrame(short streamId)
        {
            //protocol v2: <type><n><query_1>...<query_n><consistency>
            //protocol v3: <type><n><query_1>...<query_n><consistency><flags>[<serial_consistency>][<timestamp>]
            var wb = new BEBinaryWriter();

            wb.WriteFrameHeader((byte)ProtocolVersion, _headerFlags, streamId, OpCode);
            wb.WriteByte((byte)_type);
            wb.WriteInt16((short)_requests.Count);
            foreach (var br in _requests)
            {
                br.WriteToBatch((byte)ProtocolVersion, wb);
            }
            wb.WriteInt16((short)Consistency);
            if (ProtocolVersion >= 3)
            {
                wb.WriteByte((byte)_batchFlags);
            }
            if (_serialConsistency != null)
            {
                wb.WriteInt16((short)_serialConsistency.Value);
            }
            if (_timestamp != null)
            {
                //Expressed in microseconds
                wb.WriteLong(TypeCodec.ToUnixTime(_timestamp.Value).Ticks / 10);
            }
            return(wb.GetFrame());
        }
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 TooManyFieldsInTuple()
 {
     Assert.Throws <TooManyFieldsInTupleException>(() =>
     {
         byte *ptype = TypeCodec.EncodeType <BigStruct>();
     });
 }
Example #5
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 #6
0
        public object ConvertFrom(byte[] decimalBuf)
        {
            var bigintBytes = new byte[decimalBuf.Length - 4];

            Array.Copy(decimalBuf, 4, bigintBytes, 0, bigintBytes.Length);

            var scale = (byte)TypeCodec.BytesToInt32(decimalBuf, 0);

            Array.Reverse(bigintBytes);
            var bigInteger = new BigInteger(bigintBytes);
            var isNegative = bigInteger < 0;

            bigInteger  = BigInteger.Abs(bigInteger);
            bigintBytes = bigInteger.ToByteArray();
            if (bigintBytes.Length > 13 || (bigintBytes.Length == 13 && bigintBytes[12] != 0))
            {
                throw new ArgumentOutOfRangeException(
                          "decimalBuf",
                          "this java.math.BigDecimal is too big to fit into System.Decimal. Think about using other TypeAdapter for java.math.BigDecimal (e.g. J#, IKVM,...)");
            }

            var intArray = new int[3];

            Buffer.BlockCopy(bigintBytes, 0, intArray, 0, Math.Min(12, bigintBytes.Length));

            return(new decimal(intArray[0], intArray[1], intArray[2], isNegative, scale));
        }
Example #7
0
 public SerializerSessionPoolPolicy(TypeCodec typeCodec, WellKnownTypeCollection wellKnownTypes, CodecProvider codecProvider, Action <SerializerSession> onSessionDisposed)
 {
     _typeCodec         = typeCodec;
     _wellKnownTypes    = wellKnownTypes;
     _codecProvider     = codecProvider;
     _onSessionDisposed = onSessionDisposed;
 }
Example #8
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 #9
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);
                }
            }
        }
Example #10
0
 public void ParseTypeName_Should_Parse_Collections()
 {
     {
         var type = TypeCodec.ParseTypeName(null, null, "list<int>").Result;
         Assert.NotNull(type);
         Assert.AreEqual(ColumnTypeCode.List, type.TypeCode);
         var subTypeInfo = (ListColumnInfo)type.TypeInfo;
         Assert.AreEqual(ColumnTypeCode.Int, subTypeInfo.ValueTypeCode);
     }
     {
         var type = TypeCodec.ParseTypeName(null, null, "set<uuid>").Result;
         Assert.NotNull(type);
         Assert.AreEqual(ColumnTypeCode.Set, type.TypeCode);
         var subTypeInfo = (SetColumnInfo)type.TypeInfo;
         Assert.AreEqual(ColumnTypeCode.Uuid, subTypeInfo.KeyTypeCode);
     }
     {
         var type = TypeCodec.ParseTypeName(null, null, "map<text, timeuuid>").Result;
         Assert.NotNull(type);
         Assert.AreEqual(ColumnTypeCode.Map, type.TypeCode);
         var subTypeInfo = (MapColumnInfo)type.TypeInfo;
         Assert.AreEqual(ColumnTypeCode.Text, subTypeInfo.KeyTypeCode);
         Assert.AreEqual(ColumnTypeCode.Timeuuid, subTypeInfo.ValueTypeCode);
     }
     {
         var type = TypeCodec.ParseTypeName(null, null, "map<text,frozen<list<int>>>").Result;
         Assert.NotNull(type);
         Assert.AreEqual(ColumnTypeCode.Map, type.TypeCode);
         var subTypeInfo = (MapColumnInfo)type.TypeInfo;
         Assert.AreEqual(ColumnTypeCode.Text, subTypeInfo.KeyTypeCode);
         Assert.AreEqual(ColumnTypeCode.List, subTypeInfo.ValueTypeCode);
         var subListTypeInfo = (ListColumnInfo)subTypeInfo.ValueTypeInfo;
         Assert.AreEqual(ColumnTypeCode.Int, subListTypeInfo.ValueTypeCode);
     }
 }
Example #11
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 #12
0
        public byte[] ConvertTo(object value)
        {
            TypeCodec.CheckArgument <decimal>(value);
            var decimalValue = (decimal)value;

            int[] bits = decimal.GetBits(decimalValue);

            int scale = (bits[3] >> 16) & 31;

            byte[] scaleBytes = BeConverter.GetBytes(scale);

            var bigintBytes = new byte[13]; // 13th byte is for making sure that the number is positive

            Buffer.BlockCopy(bits, 0, bigintBytes, 0, 12);

            var bigInteger = new BigInteger(bigintBytes);

            if (decimalValue < 0)
            {
                bigInteger = -bigInteger;
            }

            bigintBytes = bigInteger.ToByteArray();
            Array.Reverse(bigintBytes);

            var resultBytes = new byte[scaleBytes.Length + bigintBytes.Length];

            Array.Copy(scaleBytes, resultBytes, scaleBytes.Length);
            Array.Copy(bigintBytes, 0, resultBytes, scaleBytes.Length, bigintBytes.Length);
            return(resultBytes);
        }
Example #13
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 #14
0
        internal Response(Frame frame)
        {
            if (frame == null)
            {
                throw new ArgumentNullException("frame");
            }
            if (frame.Body == null)
            {
                throw new InvalidOperationException("Response body of the received frame was null");
            }
            if (!frame.Header.Flags.HasFlag(HeaderFlag.Compression) && frame.Header.BodyLength > frame.Body.Length - frame.Body.Position)
            {
                throw new DriverInternalError(string.Format(
                                                  "Response body length should be contained in stream: Expected {0} but was {1} (position {2})",
                                                  frame.Header.BodyLength, frame.Body.Length - frame.Body.Position, frame.Body.Position));
            }

            Reader = new FrameReader(frame.Body);

            if (frame.Header.Flags.HasFlag(HeaderFlag.Tracing))
            {
                //If a response frame has the tracing flag set, the first item in its body is the trace id
                var buffer = new byte[16];
                Reader.Read(buffer, 0, 16);
                TraceId = new Guid(TypeCodec.GuidShuffle(buffer));
            }
        }
Example #15
0
        /// <summary>
        /// Validate values using prepared statement metadata
        /// </summary>
        private void ValidateValues(object[] values)
        {
            if (values == null)
            {
                return;
            }
            if (PreparedStatement.Metadata == null || PreparedStatement.Metadata.Columns == null || PreparedStatement.Metadata.Columns.Length == 0)
            {
                return;
            }
            var paramsMetadata = PreparedStatement.Metadata.Columns;

            if (values.Length > paramsMetadata.Length)
            {
                throw new ArgumentException(
                          String.Format("Provided {0} parameters to bind, expected {1}", values.Length, paramsMetadata.Length));
            }
            for (var i = 0; i < values.Length; i++)
            {
                var p     = paramsMetadata[i];
                var value = values[i];
                if (!TypeCodec.IsAssignableFrom(p, value))
                {
                    throw new InvalidTypeException(
                              String.Format("It is not possible to encode a value of type {0} to a CQL type {1}", value.GetType(), p.TypeCode));
                }
            }
        }
Example #16
0
        public override Task <AggregateMetadata> GetAggregate(string keyspaceName, string aggregateName, string signatureString)
        {
            var query = string.Format(SelectAggregates, keyspaceName, aggregateName, signatureString);

            return(Cc
                   .QueryAsync(query, true)
                   .ContinueSync(rs =>
            {
                var row = rs.FirstOrDefault();
                if (row == null)
                {
                    return null;
                }

                var emptyArray = new string[0];
                var aggregate = new AggregateMetadata
                {
                    Name = row.GetValue <string>("aggregate_name"),
                    KeyspaceName = row.GetValue <string>("keyspace_name"),
                    Signature = row.GetValue <string[]>("signature") ?? emptyArray,
                    StateFunction = row.GetValue <string>("state_func"),
                    StateType = TypeCodec.ParseFqTypeName(row.GetValue <string>("state_type")),
                    FinalFunction = row.GetValue <string>("final_func"),
                    ReturnType = TypeCodec.ParseFqTypeName(row.GetValue <string>("return_type")),
                    ArgumentTypes = (row.GetValue <string[]>("argument_types") ?? emptyArray).Select(s => TypeCodec.ParseFqTypeName(s)).ToArray(),
                };
                var initConditionRaw = TypeCodec.Decode(Cc.ProtocolVersion, row.GetValue <byte[]>("initcond"), aggregate.StateType.TypeCode, aggregate.StateType.TypeInfo);
                if (initConditionRaw != null)
                {
                    aggregate.InitialCondition = initConditionRaw.ToString();
                }
                return aggregate;
            }));
        }
Example #17
0
 public override Task <UdtColumnInfo> GetUdtDefinition(string keyspaceName, string typeName)
 {
     return(Cc
            .QueryAsync(string.Format(SelectUdts, keyspaceName, typeName), true)
            .Then(rs =>
     {
         var row = rs.FirstOrDefault();
         if (row == null)
         {
             return TaskHelper.ToTask <UdtColumnInfo>(null);
         }
         var udt = new UdtColumnInfo(row.GetValue <string>("keyspace_name") + "." + row.GetValue <string>("type_name"));
         var fieldTypeTasks = row.GetValue <string[]>("field_types")
                              .Select(name => TypeCodec.ParseTypeName(_udtResolver, keyspaceName, name))
                              .ToArray();
         return Task.Factory.ContinueWhenAll(fieldTypeTasks, tasks =>
         {
             var ex = tasks.Select(t => t.Exception).FirstOrDefault(e => e != null);
             if (ex != null)
             {
                 throw ex.InnerException;
             }
             var fieldNames = row.GetValue <string[]>("field_names");
             for (var i = 0; i < fieldNames.Length && i < tasks.Length; i++)
             {
                 var field = tasks[i].Result;
                 field.Name = fieldNames[i];
                 udt.Fields.Add(field);
             }
             return udt;
         });
     }));
 }
Example #18
0
        private static ColumnDesc[] AdaptKeyTypes(string typesString)
        {
            if (typesString == null)
            {
                return(new ColumnDesc[0]);
            }
            var indexes = new List <int>();

            for (var i = 1; i < typesString.Length; i++)
            {
                if (typesString[i] == ',')
                {
                    indexes.Add(i + 1);
                }
            }
            if (typesString.StartsWith(CompositeTypeName))
            {
                indexes.Insert(0, CompositeTypeName.Length + 1);
                indexes.Add(typesString.Length);
            }
            else
            {
                indexes.Insert(0, 0);
                //we are talking about indexes
                //the next valid start indexes would be at length + 1
                indexes.Add(typesString.Length + 1);
            }
            var types = new ColumnDesc[indexes.Count - 1];

            for (var i = 0; i < types.Length; i++)
            {
                types[i] = TypeCodec.ParseFqTypeName(typesString, indexes[i], indexes[i + 1] - indexes[i] - 1);
            }
            return(types);
        }
Example #19
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()));
                }
            }
        }
        /// <summary>
        /// Add mapping definition(s) for UDTs, specifying how UDTs should be mapped to .NET types and vice versa.
        /// </summary>
        /// <exception cref="ArgumentException" />
        public void Define(params UdtMap[] udtMaps)
        {
            if (udtMaps == null)
            {
                throw new ArgumentNullException("udtMaps");
            }
            var keyspace = _session.Keyspace;

            if (String.IsNullOrEmpty(keyspace))
            {
                throw new ArgumentException("It is not possible to define a mapping when no keyspace is specified.");
            }
            if (_session.BinaryProtocolVersion < 3)
            {
                throw new NotSupportedException("User defined type mapping is supported with C* 2.1+ and protocol version 3+");
            }
            // Add types to both indexes
            foreach (var map in udtMaps)
            {
                var udtDefition = GetDefinition(keyspace, map);
                map.Build(udtDefition);
                TypeCodec.SetUdtMap(udtDefition.Name, map);
                _udtByNetType.AddOrUpdate(map.NetType, map, (k, oldValue) => map);
            }
        }
Example #21
0
        private static string GetTypeString(PocoColumn column)
        {
            IColumnInfo typeInfo;
            var         typeCode = TypeCodec.GetColumnTypeCodeInfo(column.ColumnType, out typeInfo);

            return(GetTypeString(typeCode, typeInfo));
        }
Example #22
0
        public void ParseTypeName_Should_Parse_Single_Cql_Types()
        {
            var cqlNames = new Dictionary <string, ColumnTypeCode>
            {
                { "varchar", ColumnTypeCode.Varchar },
                { "text", ColumnTypeCode.Text },
                { "ascii", ColumnTypeCode.Ascii },
                { "uuid", ColumnTypeCode.Uuid },
                { "timeuuid", ColumnTypeCode.Timeuuid },
                { "int", ColumnTypeCode.Int },
                { "blob", ColumnTypeCode.Blob },
                { "float", ColumnTypeCode.Float },
                { "double", ColumnTypeCode.Double },
                { "boolean", ColumnTypeCode.Boolean },
                { "inet", ColumnTypeCode.Inet },
                { "date", ColumnTypeCode.Date },
                { "time", ColumnTypeCode.Time },
                { "smallint", ColumnTypeCode.SmallInt },
                { "tinyint", ColumnTypeCode.TinyInt },
                { "timestamp", ColumnTypeCode.Timestamp },
                { "bigint", ColumnTypeCode.Bigint },
                { "decimal", ColumnTypeCode.Decimal },
                { "varint", ColumnTypeCode.Varint },
                { "counter", ColumnTypeCode.Counter }
            };

            foreach (var kv in cqlNames)
            {
                var type = TypeCodec.ParseTypeName(null, null, kv.Key).Result;
                Assert.NotNull(type);
                Assert.AreEqual(kv.Value, type.TypeCode);
                Assert.Null(type.TypeInfo);
            }
        }
        /// <summary>
        /// Gets the definition of a User defined type
        /// </summary>
        public UdtColumnInfo GetUdtDefinition(string keyspace, string typeName)
        {
            var rs  = Query(String.Format(SelectUdts + " WHERE keyspace_name='{0}' AND type_name = '{1}';", keyspace, typeName));
            var row = rs.FirstOrDefault();

            if (row == null)
            {
                return(null);
            }
            var udt        = new UdtColumnInfo(row.GetValue <string>("keyspace_name") + "." + row.GetValue <string>("type_name"));
            var fieldNames = row.GetValue <List <string> >("field_names");
            var fieldTypes = row.GetValue <List <string> >("field_types");

            if (fieldNames.Count != fieldTypes.Count)
            {
                var ex = new DriverInternalError("Field names and types for UDT do not match");
                _logger.Error(ex);
                throw ex;
            }
            for (var i = 0; i < fieldNames.Count; i++)
            {
                var field = TypeCodec.ParseDataType(fieldTypes[i]);
                field.Name = fieldNames[i];
                udt.Fields.Add(field);
            }
            return(udt);
        }
Example #24
0
        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 #25
0
        public override Task <FunctionMetadata> GetFunction(string keyspaceName, string functionName, string signatureString)
        {
            var query = string.Format(SelectFunctions, keyspaceName, functionName, signatureString);

            return(Cc
                   .QueryAsync(query, true)
                   .ContinueSync(rs =>
            {
                var row = rs.FirstOrDefault();
                if (row == null)
                {
                    return null;
                }
                var emptyArray = new string[0];
                return new FunctionMetadata
                {
                    Name = row.GetValue <string>("function_name"),
                    KeyspaceName = row.GetValue <string>("keyspace_name"),
                    Signature = row.GetValue <string[]>("signature") ?? emptyArray,
                    ArgumentNames = row.GetValue <string[]>("argument_names") ?? emptyArray,
                    Body = row.GetValue <string>("body"),
                    CalledOnNullInput = row.GetValue <bool>("called_on_null_input"),
                    Language = row.GetValue <string>("language"),
                    ReturnType = TypeCodec.ParseFqTypeName(row.GetValue <string>("return_type")),
                    ArgumentTypes = (row.GetValue <string[]>("argument_types") ?? emptyArray).Select(s => TypeCodec.ParseFqTypeName(s)).ToArray()
                };
            }));
        }
Example #26
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 #27
0
 public SessionService(ServiceStartInfo start) : base(start)
 {
     this.log       = LoggerFactory.GetLogger(start.Address.ServiceName);
     this.accountID = start.Config["accountID"].ToString();
     this.client_battle_action_codec  = ConnectServer.ClientCodec.Factory.GetCodec(typeof(ClientBattleAction));
     this.session_battle_action_codec = base.ServerCodec.Factory.GetCodec(typeof(SessionBattleAction));
     this.Channel = start.Config["channel"]?.ToString();
 }
Example #28
0
        public void Decode_Fine()
        {
            var ptype = TypeCodec.EncodeType <int>();

            Assert.Equal(typeof(int), TypeCodec.DecodeType(ptype));
            TypeCodec.FreeTypeCode(ptype);

            ptype = TypeCodec.EncodeType <uint>();
            Assert.Equal(typeof(uint), TypeCodec.DecodeType(ptype));
            TypeCodec.FreeTypeCode(ptype);

            ptype = TypeCodec.EncodeType <string>();
            Assert.Equal(typeof(string), TypeCodec.DecodeType(ptype));
            TypeCodec.FreeTypeCode(ptype);

            ptype = TypeCodec.EncodeType <double>();
            Assert.Equal(typeof(double), TypeCodec.DecodeType(ptype));
            TypeCodec.FreeTypeCode(ptype);

            ptype = TypeCodec.EncodeType <List <int> >();
            Assert.Equal(typeof(List <int>), TypeCodec.DecodeType(ptype));
            TypeCodec.FreeTypeCode(ptype);

            ptype = TypeCodec.EncodeType <List <long> >();
            Assert.Equal(typeof(List <long>), TypeCodec.DecodeType(ptype));
            TypeCodec.FreeTypeCode(ptype);

            ptype = TypeCodec.EncodeType <TestStruct_1>();
            Assert.Equal(typeof(ValueTuple <int, double>), TypeCodec.DecodeType(ptype));
            TypeCodec.FreeTypeCode(ptype);

            ptype = TypeCodec.EncodeType <TestStruct_2>();
            Assert.Equal(typeof(ValueTuple <string, string, string, string>), TypeCodec.DecodeType(ptype));
            TypeCodec.FreeTypeCode(ptype);

            ptype = TypeCodec.EncodeType <TestStruct_3>();
            Assert.Equal(typeof(ValueTuple <
                                    ValueTuple <string, string, string, string>,
                                    string,
                                    List <ValueTuple <int, double> > >), TypeCodec.DecodeType(ptype));
            TypeCodec.FreeTypeCode(ptype);

            ptype = TypeCodec.EncodeType <TestClass_1>();
            Assert.Equal(typeof(ValueTuple <int, double>), TypeCodec.DecodeType(ptype));
            TypeCodec.FreeTypeCode(ptype);

            ptype = TypeCodec.EncodeType <TestClass_2>();
            Assert.Equal(typeof(ValueTuple <string, string, string, string>), TypeCodec.DecodeType(ptype));
            TypeCodec.FreeTypeCode(ptype);

            ptype = TypeCodec.EncodeType <TestClass_3>();
            Assert.Equal(typeof(ValueTuple <
                                    ValueTuple <string, string, string, string>,
                                    string,
                                    List <ValueTuple <int, double> > >), TypeCodec.DecodeType(ptype));
            TypeCodec.FreeTypeCode(ptype);
        }
Example #29
0
 public AreaZonePlayer(AreaService svc, AreaZoneNode node, RoleEnterZoneRequest enter)
 {
     Alloc.RecordConstructor(this.GetType());
     this.log                = LoggerFactory.GetLogger(GetType().Name);
     this.service            = svc;
     this.node               = node;
     this.enter              = enter;
     this.client_event_route = TypeCodec.GetAttributeRoute(typeof(ClientBattleEvent));
 }
Example #30
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);
            }
        }