예제 #1
0
        /// <summary>
        /// <para>
        /// Creates a new <see cref="BoundStatement"/> instance with the provided parameter values.
        /// </para>
        /// <para>
        /// You can specify the parameter values by the position of the markers in the query, or by name
        /// using a single instance of an anonymous type, with property names as parameter names.
        /// </para>
        /// <para>
        /// Note that while no more <c>values</c> than bound variables can be provided, it is allowed to
        /// provide less <c>values</c> that there is variables.
        /// </para>
        /// <para>
        /// You can provide a comma-separated variable number of arguments to the <c>Bind()</c> method. When providing
        /// an array, the reference might be used by the driver making it not safe to modify its content.
        /// </para>
        /// </summary>
        /// <param name="values">The values to bind to the variables of the newly created BoundStatement.</param>
        /// <returns>The newly created <see cref="BoundStatement"/> with the query parameters set.</returns>
        /// <example>
        /// Binding different parameters:
        /// <code>
        /// PreparedStatement ps = session.Prepare("INSERT INTO table (id, name) VALUES (?, ?)");
        /// BoundStatement statement = ps.Bind(Guid.NewGuid(), "Franz Ferdinand");
        /// session.Execute(statement);
        /// </code>
        /// </example>
        public virtual BoundStatement Bind(params object[] values)
        {
            var bs = new BoundStatement(this);

            bs.SetRoutingKey(_routingKey);
            if (values == null)
            {
                return(bs);
            }
            var valuesByPosition   = values;
            var useNamedParameters = values.Length == 1 && Utils.IsAnonymousType(values[0]);

            if (useNamedParameters)
            {
                //Using named parameters
                //Reorder the params according the position in the query
                valuesByPosition = Utils.GetValues(_variablesRowsMetadata.Columns.Select(c => c.Name), values[0]).ToArray();
            }

            var serializer = _serializerManager.GetCurrentSerializer();

            bs.SetValues(valuesByPosition, serializer);
            bs.CalculateRoutingKey(serializer, useNamedParameters, RoutingIndexes, _routingNames, valuesByPosition, values);
            return(bs);
        }
예제 #2
0
        /// <summary>
        /// Add mapping definition(s) for UDTs, specifying how UDTs should be mapped to .NET types and vice versa.
        /// </summary>
        /// <exception cref="ArgumentException" />
        public async Task DefineAsync(params UdtMap[] udtMaps)
        {
            if (udtMaps == null)
            {
                throw new ArgumentNullException("udtMaps");
            }
            var sessionKeyspace = _session.Keyspace;

            if (string.IsNullOrEmpty(sessionKeyspace) && udtMaps.Any(map => map.Keyspace == null))
            {
                throw new ArgumentException("It is not possible to define a mapping when no keyspace is specified. " +
                                            "You can specify it while creating the UdtMap, while creating the Session and" +
                                            " while creating the Cluster (default keyspace config setting).");
            }
            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 = await GetDefinitionAsync(map.Keyspace ?? sessionKeyspace, map).ConfigureAwait(false);

                map.SetSerializer(_serializer.GetCurrentSerializer());
                map.Build(udtDefition);
                _serializer.SetUdtMap(udtDefition.Name, map);
                _udtByNetType.AddOrUpdate(map.NetType, map, (k, oldValue) => map);
            }
        }
예제 #3
0
 private static Mock <Connection> GetConnectionMock(Configuration config = null, ISerializerManager serializer = null)
 {
     config = config ?? new Configuration();
     return(new Mock <Connection>(
                MockBehavior.Loose,
                serializer?.GetCurrentSerializer() ?? new SerializerManager(ProtocolVersion.MaxSupported).GetCurrentSerializer(),
                new ConnectionEndPoint(ConnectionTests.Address, null),
                config,
                new StartupRequestFactory(config.StartupOptionsFactory),
                NullConnectionObserver.Instance));
 }
예제 #4
0
        public async Task <IConnection> ChangeProtocolVersion(
            Configuration config,
            ISerializerManager serializer,
            ProtocolVersion nextVersion,
            IConnection previousConnection,
            UnsupportedProtocolVersionException ex = null,
            ProtocolVersion?previousVersion        = null)
        {
            if (!nextVersion.IsSupported() || nextVersion == previousVersion)
            {
                nextVersion = nextVersion.GetLowerSupported();
            }

            if (nextVersion == 0)
            {
                if (ex != null)
                {
                    // We have downgraded the version until is 0 and none of those are supported
                    throw ex;
                }

                // There was no exception leading to the downgrade, signal internal error
                throw new DriverInternalError("Connection was unable to STARTUP using protocol version 0");
            }

            ControlConnection.Logger.Info(ex != null
                ? $"{ex.Message}, trying with version {nextVersion:D}"
                : $"Changing protocol version to {nextVersion:D}");

            serializer.ChangeProtocolVersion(nextVersion);

            previousConnection.Dispose();

            var c = config.ConnectionFactory.CreateUnobserved(
                serializer.GetCurrentSerializer(),
                previousConnection.EndPoint,
                config);

            try
            {
                await c.Open().ConfigureAwait(false);

                return(c);
            }
            catch
            {
                c.Dispose();
                throw;
            }
        }
예제 #5
0
        public virtual async Task <IConnection> DoCreateAndOpen(bool isReconnection)
        {
            var endPoint = await _config.EndPointResolver.GetConnectionEndPointAsync(_host, isReconnection).ConfigureAwait(false);

            var c = _config.ConnectionFactory.Create(_serializerManager.GetCurrentSerializer(), endPoint, _config, _observerFactory.CreateConnectionObserver(_host));

            try
            {
                await c.Open().ConfigureAwait(false);
            }
            catch
            {
                c.Dispose();
                throw;
            }
            if (_poolingOptions.GetHeartBeatInterval() > 0)
            {
                c.OnIdleRequestException += ex => OnIdleRequestException(c, ex);
            }
            c.Closing += OnConnectionClosing;
            return(c);
        }
        public void Should_Parse_ErrorResponse_Of_Syntax_Error()
        {
            var body     = GetErrorBody(0x2000, "Test syntax error");
            var header   = FrameHeader.ParseResponseHeader(Version, GetHeaderBuffer(body.Length), 0);
            var response = FrameParser.Parse(new Frame(header, new MemoryStream(body), Serializer.GetCurrentSerializer()));
            var ex       = IsErrorResponse <SyntaxError>(response);

            Assert.AreEqual("Test syntax error", ex.Message);
        }