/// <include file='Doc/en_EN/FbConnection.xml' path='doc/class[@name="FbConnection"]/method[@name="CreateDatabase(System.String,System.Int32,System.Boolean,System.Boolean)"]/*'/> public static void CreateDatabase( string connectionString, int pageSize, bool forcedWrites, bool overwrite) { FbConnectionString options = new FbConnectionString(connectionString); options.Validate(); try { // DPB configuration DatabaseParameterBuffer dpb = new DatabaseParameterBuffer(); // Dpb version dpb.Append(IscCodes.isc_dpb_version1); // Dummy packet interval dpb.Append(IscCodes.isc_dpb_dummy_packet_interval, new byte[] { 120, 10, 0, 0 }); // User name dpb.Append(IscCodes.isc_dpb_user_name, options.UserID); // User password dpb.Append(IscCodes.isc_dpb_password, options.Password); // Database dialect dpb.Append(IscCodes.isc_dpb_sql_dialect, new byte[] { options.Dialect, 0, 0, 0 }); // Database overwrite dpb.Append(IscCodes.isc_dpb_overwrite, (short)(overwrite ? 1 : 0)); // Character set if (options.Charset.Length > 0) { int index = Charset.SupportedCharsets.IndexOf(options.Charset); if (index == -1) { throw new ArgumentException("Character set is not valid."); } else { dpb.Append( IscCodes.isc_dpb_set_db_charset, Charset.SupportedCharsets[index].Name); } } // Page Size if (pageSize > 0) { dpb.Append(IscCodes.isc_dpb_page_size, pageSize); } // Forced writes dpb.Append(IscCodes.isc_dpb_force_write, (short)(forcedWrites ? 1 : 0)); if (!overwrite) { // Check if the database exists FbConnectionInternal c = new FbConnectionInternal(options); try { c.Connect(); c.Disconnect(); IscException ex = new IscException(IscCodes.isc_db_or_file_exists); throw new FbException(ex.Message, ex); } catch (FbException ex) { if (ex.ErrorCode != 335544344) { throw; } } } // Create the new database FbConnectionInternal db = new FbConnectionInternal(options); db.CreateDatabase(dpb); } catch (IscException ex) { throw new FbException(ex.Message, ex); } }
private byte[] GenerateSDL(ArrayDesc desc) { int n; int from; int to; int increment; int dimensions; ArrayBound tail; BinaryWriter sdl; dimensions = desc.Dimensions; if (dimensions > 16) { throw IscException.ForErrorCode(IscCodes.isc_invalid_dimension); } sdl = new BinaryWriter(new MemoryStream()); Stuff( sdl, 4, IscCodes.isc_sdl_version1, IscCodes.isc_sdl_struct, 1, desc.DataType); switch (desc.DataType) { case IscCodes.blr_short: case IscCodes.blr_long: case IscCodes.blr_int64: case IscCodes.blr_quad: StuffSdl(sdl, (byte)desc.Scale); break; case IscCodes.blr_text: case IscCodes.blr_cstring: case IscCodes.blr_varying: StuffWord(sdl, desc.Length); break; default: break; } StuffString(sdl, IscCodes.isc_sdl_relation, desc.RelationName); StuffString(sdl, IscCodes.isc_sdl_field, desc.FieldName); if ((desc.Flags & IscCodes.ARRAY_DESC_COLUMN_MAJOR) == IscCodes.ARRAY_DESC_COLUMN_MAJOR) { from = dimensions - 1; to = -1; increment = -1; } else { from = 0; to = dimensions; increment = 1; } for (n = from; n != to; n += increment) { tail = desc.Bounds[n]; if (tail.LowerBound == 1) { Stuff(sdl, 2, IscCodes.isc_sdl_do1, n); } else { Stuff(sdl, 2, IscCodes.isc_sdl_do2, n); StuffLiteral(sdl, tail.LowerBound); } StuffLiteral(sdl, tail.UpperBound); } Stuff(sdl, 5, IscCodes.isc_sdl_element, 1, IscCodes.isc_sdl_scalar, 0, dimensions); for (n = 0; n < dimensions; n++) { Stuff(sdl, 2, IscCodes.isc_sdl_variable, n); } StuffSdl(sdl, IscCodes.isc_sdl_eoc); return(((MemoryStream)sdl.BaseStream).ToArray()); }
public static IscException ParseStatusVector(IntPtr[] statusVector, Charset charset) { IscException exception = null; bool eof = false; for (int i = 0; i < statusVector.Length;) { IntPtr arg = statusVector[i++]; switch (arg.AsInt()) { case IscCodes.isc_arg_gds: default: IntPtr er = statusVector[i++]; if (er != IntPtr.Zero) { if (exception == null) { exception = IscException.ForBuilding(); } exception.Errors.Add(new IscError(arg.AsInt(), er.AsInt())); } break; case IscCodes.isc_arg_end: exception?.BuildExceptionData(); eof = true; break; case IscCodes.isc_arg_interpreted: case IscCodes.isc_arg_string: { IntPtr ptr = statusVector[i++]; string s = Marshal.PtrToStringAnsi(ptr); string arg_value = charset.GetString(Encoding2.Default.GetBytes(s)); exception.Errors.Add(new IscError(arg.AsInt(), arg_value)); } break; case IscCodes.isc_arg_cstring: { i++; IntPtr ptr = statusVector[i++]; string s = Marshal.PtrToStringAnsi(ptr); string arg_value = charset.GetString(Encoding2.Default.GetBytes(s)); exception.Errors.Add(new IscError(arg.AsInt(), arg_value)); } break; case IscCodes.isc_arg_win32: case IscCodes.isc_arg_number: exception.Errors.Add(new IscError(arg.AsInt(), statusVector[i++].AsInt())); break; case IscCodes.isc_arg_sql_state: { IntPtr ptr = statusVector[i++]; string s = Marshal.PtrToStringAnsi(ptr); string arg_value = charset.GetString(Encoding2.Default.GetBytes(s)); exception.Errors.Add(new IscError(arg.AsInt(), arg_value)); } break; } if (eof) { break; } } return(exception); }
protected void ParseTruncSqlInfo(byte[] info, byte[] items, ref Descriptor[] rowDescs) { var currentPosition = 0; var currentDescriptorIndex = -1; var currentItemIndex = 0; while (info[currentPosition] != IscCodes.isc_info_end) { byte item; while ((item = info[currentPosition++]) != IscCodes.isc_info_sql_describe_end) { switch (item) { case IscCodes.isc_info_truncated: currentItemIndex--; var newItems = new List <byte>(items.Length); var part = 0; var chock = 0; for (var i = 0; i < items.Length; i++) { if (items[i] == IscCodes.isc_info_sql_describe_end) { newItems.Insert(chock, IscCodes.isc_info_sql_sqlda_start); newItems.Insert(chock + 1, 2); var processedItems = (rowDescs[part] != null ? rowDescs[part].Count : (short)0); newItems.Insert(chock + 2, (byte)((part == currentDescriptorIndex ? currentItemIndex : processedItems) & 255)); newItems.Insert(chock + 3, (byte)((part == currentDescriptorIndex ? currentItemIndex : processedItems) >> 8)); part++; chock = i + 4 + 1; } newItems.Add(items[i]); } info = GetSqlInfo(newItems.ToArray(), info.Length); currentPosition = 0; currentDescriptorIndex = -1; goto Break; case IscCodes.isc_info_sql_select: case IscCodes.isc_info_sql_bind: currentDescriptorIndex++; if (info[currentPosition] == IscCodes.isc_info_truncated) { break; } currentPosition++; var len = IscHelper.VaxInteger(info, currentPosition, 2); currentPosition += 2; if (rowDescs[currentDescriptorIndex] == null) { var n = IscHelper.VaxInteger(info, currentPosition, len); rowDescs[currentDescriptorIndex] = new Descriptor((short)n); if (n == 0) { currentPosition += len; goto Break; } } currentPosition += len; break; case IscCodes.isc_info_sql_sqlda_seq: len = IscHelper.VaxInteger(info, currentPosition, 2); currentPosition += 2; currentItemIndex = IscHelper.VaxInteger(info, currentPosition, len); currentPosition += len; break; case IscCodes.isc_info_sql_type: len = IscHelper.VaxInteger(info, currentPosition, 2); currentPosition += 2; rowDescs[currentDescriptorIndex][currentItemIndex - 1].DataType = (short)IscHelper.VaxInteger(info, currentPosition, len); currentPosition += len; break; case IscCodes.isc_info_sql_sub_type: len = IscHelper.VaxInteger(info, currentPosition, 2); currentPosition += 2; rowDescs[currentDescriptorIndex][currentItemIndex - 1].SubType = (short)IscHelper.VaxInteger(info, currentPosition, len); currentPosition += len; break; case IscCodes.isc_info_sql_scale: len = IscHelper.VaxInteger(info, currentPosition, 2); currentPosition += 2; rowDescs[currentDescriptorIndex][currentItemIndex - 1].NumericScale = (short)IscHelper.VaxInteger(info, currentPosition, len); currentPosition += len; break; case IscCodes.isc_info_sql_length: len = IscHelper.VaxInteger(info, currentPosition, 2); currentPosition += 2; rowDescs[currentDescriptorIndex][currentItemIndex - 1].Length = (short)IscHelper.VaxInteger(info, currentPosition, len); currentPosition += len; break; case IscCodes.isc_info_sql_field: len = IscHelper.VaxInteger(info, currentPosition, 2); currentPosition += 2; rowDescs[currentDescriptorIndex][currentItemIndex - 1].Name = _database.Charset.GetString(info, currentPosition, len); currentPosition += len; break; case IscCodes.isc_info_sql_relation: len = IscHelper.VaxInteger(info, currentPosition, 2); currentPosition += 2; rowDescs[currentDescriptorIndex][currentItemIndex - 1].Relation = _database.Charset.GetString(info, currentPosition, len); currentPosition += len; break; case IscCodes.isc_info_sql_owner: len = IscHelper.VaxInteger(info, currentPosition, 2); currentPosition += 2; rowDescs[currentDescriptorIndex][currentItemIndex - 1].Owner = _database.Charset.GetString(info, currentPosition, len); currentPosition += len; break; case IscCodes.isc_info_sql_alias: len = IscHelper.VaxInteger(info, currentPosition, 2); currentPosition += 2; rowDescs[currentDescriptorIndex][currentItemIndex - 1].Alias = _database.Charset.GetString(info, currentPosition, len); currentPosition += len; break; default: throw IscException.ForErrorCode(IscCodes.isc_dsql_sqlda_err); } } // just to get out of the loop Break: { } } }
private void OnWarningMessage(IscException warning) { InfoMessage?.Invoke(this, new FbInfoMessageEventArgs(warning)); }
public override void Execute(int timeout, IDescriptorFiller descriptorFiller) { EnsureNotDeallocated(); Clear(); try { RecordsAffected = -1; SendExecuteToBuffer(timeout, descriptorFiller); _database.Xdr.Flush(); var numberOfResponses = (StatementType == DbStatementType.StoredProcedure ? 1 : 0) + 1; try { SqlResponse sqlStoredProcedureResponse = null; if (StatementType == DbStatementType.StoredProcedure) { numberOfResponses--; sqlStoredProcedureResponse = (SqlResponse)_database.ReadResponse(); ProcessStoredProcedureExecuteResponse(sqlStoredProcedureResponse); } numberOfResponses--; var executeResponse = (GenericResponse)_database.ReadResponse(); ProcessExecuteResponse(executeResponse); } finally { (Database as GdsDatabase).SafeFinishFetching(numberOfResponses); } // we need to split this in two, to allow server handle op_cancel properly if (DoRecordsAffected) { SendInfoSqlToBuffer(RowsAffectedInfoItems, IscCodes.ROWS_AFFECTED_BUFFER_SIZE); _database.Xdr.Flush(); numberOfResponses = 1; try { numberOfResponses--; var rowsAffectedResponse = (GenericResponse)_database.ReadResponse(); RecordsAffected = ProcessRecordsAffectedBuffer(ProcessInfoSqlResponse(rowsAffectedResponse)); } finally { (Database as GdsDatabase).SafeFinishFetching(numberOfResponses); } } State = StatementState.Executed; } catch (IOException ex) { State = StatementState.Error; throw IscException.ForIOException(ex); } }
private byte[] ReceiveSliceResponse(ArrayDesc desc) { try { int operation = _database.ReadOperation(); if (operation == IscCodes.op_slice) { // Read slice length bool isVariying = false; int elements = 0; int length = _database.XdrStream.ReadInt32(); length = _database.XdrStream.ReadInt32(); switch (desc.DataType) { case IscCodes.blr_text: case IscCodes.blr_text2: case IscCodes.blr_cstring: case IscCodes.blr_cstring2: elements = length / desc.Length; length += elements * ((4 - desc.Length) & 3); break; case IscCodes.blr_varying: case IscCodes.blr_varying2: elements = length / desc.Length; isVariying = true; break; case IscCodes.blr_short: length = length * desc.Length; break; } if (isVariying) { XdrStream xdr = new XdrStream(); for (int i = 0; i < elements; i++) { byte[] buffer = _database.XdrStream.ReadOpaque(_database.XdrStream.ReadInt32()); xdr.WriteBuffer(buffer, buffer.Length); } return(xdr.ToArray()); } else { return(_database.XdrStream.ReadOpaque(length)); } } else { _database.SetOperation(operation); _database.ReadResponse(); return(null); } } catch (IOException ex) { throw IscException.ForErrorCode(IscCodes.isc_net_read_err, ex); } }
public override void Execute() { if (State == StatementState.Deallocated) { throw new InvalidOperationException("Statement is not correctly created."); } Clear(); try { RecordsAffected = -1; SendExecuteToBuffer(); var readRowsAffectedResponse = false; if (DoRecordsAffected) { SendInfoSqlToBuffer(RowsAffectedInfoItems, IscCodes.ROWS_AFFECTED_BUFFER_SIZE); readRowsAffectedResponse = true; } _database.Xdr.Flush(); var numberOfResponses = (StatementType == DbStatementType.StoredProcedure ? 1 : 0) + 1 + (readRowsAffectedResponse ? 1 : 0); try { SqlResponse sqlStoredProcedureResponse = null; if (StatementType == DbStatementType.StoredProcedure) { numberOfResponses--; sqlStoredProcedureResponse = _database.ReadResponse <SqlResponse>(); ProcessStoredProcedureExecuteResponse(sqlStoredProcedureResponse); } numberOfResponses--; var executeResponse = _database.ReadResponse <GenericResponse>(); GenericResponse rowsAffectedResponse = null; if (readRowsAffectedResponse) { numberOfResponses--; rowsAffectedResponse = _database.ReadResponse <GenericResponse>(); } ProcessExecuteResponse(executeResponse); if (readRowsAffectedResponse) { RecordsAffected = ProcessRecordsAffectedBuffer(ProcessInfoSqlResponse(rowsAffectedResponse)); } } finally { SafeFinishFetching(ref numberOfResponses); } State = StatementState.Executed; } catch (IOException ex) { State = StatementState.Error; throw IscException.ForErrorCode(IscCodes.isc_network_error, ex); } }
public void Identify(string database) { try { Xdr.Write(IscCodes.op_connect); Xdr.Write(IscCodes.op_attach); Xdr.Write(IscCodes.CONNECT_VERSION3); Xdr.Write(IscCodes.GenericAchitectureClient); Xdr.Write(database); var protocols = ProtocolsSupported.Get(_compression); Xdr.Write(protocols.Count()); #warning These out params are ugly, refactor var userIdentificationData = UserIdentificationData(out var srp, out var sspi); using (sspi) { Xdr.WriteBuffer(userIdentificationData); var priority = 0; foreach (var protocol in protocols) { Xdr.Write(protocol.Version); Xdr.Write(IscCodes.GenericAchitectureClient); Xdr.Write(protocol.MinPType); Xdr.Write(protocol.MaxPType); Xdr.Write(priority); priority++; } Xdr.Flush(); var operation = Xdr.ReadOperation(); if (operation == IscCodes.op_accept || operation == IscCodes.op_cond_accept || operation == IscCodes.op_accept_data) { var wireCryptInitialized = false; ProtocolVersion = Xdr.ReadInt32(); ProtocolArchitecture = Xdr.ReadInt32(); ProtocolMinimunType = Xdr.ReadInt32(); if (ProtocolVersion < 0) { ProtocolVersion = (ushort)(ProtocolVersion & IscCodes.FB_PROTOCOL_MASK) | IscCodes.FB_PROTOCOL_FLAG; } if (_compression && !((ProtocolMinimunType & IscCodes.pflag_compress) != 0)) { _compression = false; } if (operation == IscCodes.op_cond_accept || operation == IscCodes.op_accept_data) { var serverData = Xdr.ReadBuffer(); var acceptPluginName = Xdr.ReadString(); var isAuthenticated = Xdr.ReadBoolean(); var serverKeys = Xdr.ReadBuffer(); if (!isAuthenticated) { switch (acceptPluginName) { case SrpClient.PluginName: AuthData = Encoding.ASCII.GetBytes(srp.ClientProof(NormalizeLogin(_userID), Password, serverData).ToHexString()); break; case SspiHelper.PluginName: AuthData = sspi.GetClientSecurity(serverData); break; default: throw new ArgumentOutOfRangeException(nameof(acceptPluginName), $"{nameof(acceptPluginName)}={acceptPluginName}"); } } if (_compression) { // after reading before writing _firebirdNetworkStream.StartCompression(); } if (operation == IscCodes.op_cond_accept) { Xdr.Write(IscCodes.op_cont_auth); Xdr.WriteBuffer(AuthData); Xdr.Write(acceptPluginName); // like CNCT_plugin_name Xdr.Write(acceptPluginName); // like CNCT_plugin_list Xdr.WriteBuffer(serverKeys); Xdr.Flush(); var response = (GenericResponse)ProcessOperation(Xdr.ReadOperation(), Xdr); serverKeys = response.Data; isAuthenticated = true; if (_wireCrypt != WireCryptOption.Disabled) { Xdr.Write(IscCodes.op_crypt); Xdr.Write(FirebirdNetworkStream.EncryptionName); Xdr.Write(SrpClient.SessionKeyName); Xdr.Flush(); // after writing before reading _firebirdNetworkStream.StartEncryption(srp.SessionKey); ProcessOperation(Xdr.ReadOperation(), Xdr); wireCryptInitialized = true; } } } // fbclient does not care about wirecrypt in older protocols either if (ProtocolVersion == IscCodes.PROTOCOL_VERSION13 && _wireCrypt == WireCryptOption.Required && !wireCryptInitialized) { throw IscException.ForErrorCode(IscCodes.isc_wirecrypt_incompatible); } } else if (operation == IscCodes.op_response) { var response = (GenericResponse)ProcessOperation(operation, Xdr); throw response.Exception; } else { try { Disconnect(); } catch { } finally { throw IscException.ForErrorCode(IscCodes.isc_connect_reject); } } } } catch (IOException ex) { throw IscException.ForErrorCode(IscCodes.isc_network_error, ex); } }
public override async Task <DbValue[]> Fetch(AsyncWrappingCommonArgs async) { EnsureNotDeallocated(); if (StatementType == DbStatementType.StoredProcedure && !_allRowsFetched) { _allRowsFetched = true; return(GetOutputParameters()); } else if (StatementType == DbStatementType.Insert && _allRowsFetched) { return(null); } else if (StatementType != DbStatementType.Select && StatementType != DbStatementType.SelectForUpdate) { return(null); } if (!_allRowsFetched && _rows.Count == 0) { try { await _database.Xdr.Write(IscCodes.op_fetch, async).ConfigureAwait(false); await _database.Xdr.Write(_handle, async).ConfigureAwait(false); await _database.Xdr.WriteBuffer(_fields.ToBlrArray(), async).ConfigureAwait(false); await _database.Xdr.Write(0, async).ConfigureAwait(false); // p_sqldata_message_number await _database.Xdr.Write(_fetchSize, async).ConfigureAwait(false); // p_sqldata_messages await _database.Xdr.Flush(async).ConfigureAwait(false); var operation = await _database.ReadOperation(async).ConfigureAwait(false); if (operation == IscCodes.op_fetch_response) { var hasOperation = true; while (!_allRowsFetched) { var response = hasOperation ? await _database.ReadResponse(operation, async).ConfigureAwait(false) : await _database.ReadResponse(async).ConfigureAwait(false); hasOperation = false; if (response is FetchResponse fetchResponse) { if (fetchResponse.Count > 0 && fetchResponse.Status == 0) { _rows.Enqueue(await ReadRow(async).ConfigureAwait(false)); } else if (fetchResponse.Status == 100) { _allRowsFetched = true; } else { break; } } else { break; } } } else { await _database.ReadResponse(operation, async).ConfigureAwait(false); } } catch (IOException ex) { throw IscException.ForIOException(ex); } } if (_rows != null && _rows.Count > 0) { return(_rows.Dequeue()); } else { _rows.Clear(); return(null); } }
protected async Task WriteRawParameter(IXdrWriter xdr, DbField field, AsyncWrappingCommonArgs async) { if (field.DbDataType != DbDataType.Null) { await field.FixNull(async).ConfigureAwait(false); switch (field.DbDataType) { case DbDataType.Char: if (field.Charset.IsOctetsCharset) { await xdr.WriteOpaque(await field.DbValue.GetBinary(async).ConfigureAwait(false), field.Length, async).ConfigureAwait(false); } else if (field.Charset.IsNoneCharset) { var bvalue = field.Charset.GetBytes(await field.DbValue.GetString(async).ConfigureAwait(false)); if (bvalue.Length > field.Length) { throw IscException.ForErrorCodes(new[] { IscCodes.isc_arith_except, IscCodes.isc_string_truncation }); } await xdr.WriteOpaque(bvalue, field.Length, async).ConfigureAwait(false); } else { var svalue = await field.DbValue.GetString(async).ConfigureAwait(false); if ((field.Length % field.Charset.BytesPerCharacter) == 0 && svalue.Length > field.CharCount) { throw IscException.ForErrorCodes(new[] { IscCodes.isc_arith_except, IscCodes.isc_string_truncation }); } await xdr.WriteOpaque(field.Charset.GetBytes(svalue), field.Length, async).ConfigureAwait(false); } break; case DbDataType.VarChar: if (field.Charset.IsOctetsCharset) { await xdr.WriteBuffer(await field.DbValue.GetBinary(async).ConfigureAwait(false), async).ConfigureAwait(false); } else if (field.Charset.IsNoneCharset) { var bvalue = field.Charset.GetBytes(await field.DbValue.GetString(async).ConfigureAwait(false)); if (bvalue.Length > field.Length) { throw IscException.ForErrorCodes(new[] { IscCodes.isc_arith_except, IscCodes.isc_string_truncation }); } await xdr.WriteBuffer(bvalue, async).ConfigureAwait(false); } else { var svalue = await field.DbValue.GetString(async).ConfigureAwait(false); if ((field.Length % field.Charset.BytesPerCharacter) == 0 && svalue.Length > field.CharCount) { throw IscException.ForErrorCodes(new[] { IscCodes.isc_arith_except, IscCodes.isc_string_truncation }); } await xdr.WriteBuffer(field.Charset.GetBytes(svalue), async).ConfigureAwait(false); } break; case DbDataType.SmallInt: await xdr.Write(await field.DbValue.GetInt16(async).ConfigureAwait(false), async).ConfigureAwait(false); break; case DbDataType.Integer: await xdr.Write(await field.DbValue.GetInt32(async).ConfigureAwait(false), async).ConfigureAwait(false); break; case DbDataType.BigInt: case DbDataType.Array: case DbDataType.Binary: case DbDataType.Text: await xdr.Write(await field.DbValue.GetInt64(async).ConfigureAwait(false), async).ConfigureAwait(false); break; case DbDataType.Decimal: case DbDataType.Numeric: await xdr.Write(await field.DbValue.GetDecimal(async).ConfigureAwait(false), field.DataType, field.NumericScale, async).ConfigureAwait(false); break; case DbDataType.Float: await xdr.Write(await field.DbValue.GetFloat(async).ConfigureAwait(false), async).ConfigureAwait(false); break; case DbDataType.Guid: await xdr.Write(await field.DbValue.GetGuid(async).ConfigureAwait(false), async).ConfigureAwait(false); break; case DbDataType.Double: await xdr.Write(await field.DbValue.GetDouble(async).ConfigureAwait(false), async).ConfigureAwait(false); break; case DbDataType.Date: await xdr.Write(await field.DbValue.GetDate(async).ConfigureAwait(false), async).ConfigureAwait(false); break; case DbDataType.Time: await xdr.Write(await field.DbValue.GetTime(async).ConfigureAwait(false), async).ConfigureAwait(false); break; case DbDataType.TimeStamp: await xdr.Write(await field.DbValue.GetDate(async).ConfigureAwait(false), async).ConfigureAwait(false); await xdr.Write(await field.DbValue.GetTime(async).ConfigureAwait(false), async).ConfigureAwait(false); break; case DbDataType.Boolean: await xdr.Write(await field.DbValue.GetBoolean(async).ConfigureAwait(false), async).ConfigureAwait(false); break; case DbDataType.TimeStampTZ: await xdr.Write(await field.DbValue.GetDate(async).ConfigureAwait(false), async).ConfigureAwait(false); await xdr.Write(await field.DbValue.GetTime(async).ConfigureAwait(false), async).ConfigureAwait(false); await xdr.Write(await field.DbValue.GetTimeZoneId(async).ConfigureAwait(false), async).ConfigureAwait(false); break; case DbDataType.TimeStampTZEx: await xdr.Write(await field.DbValue.GetDate(async).ConfigureAwait(false), async).ConfigureAwait(false); await xdr.Write(await field.DbValue.GetTime(async).ConfigureAwait(false), async).ConfigureAwait(false); await xdr.Write(await field.DbValue.GetTimeZoneId(async).ConfigureAwait(false), async).ConfigureAwait(false); await xdr.Write((short)0, async).ConfigureAwait(false); break; case DbDataType.TimeTZ: await xdr.Write(await field.DbValue.GetTime(async).ConfigureAwait(false), async).ConfigureAwait(false); await xdr.Write(await field.DbValue.GetTimeZoneId(async).ConfigureAwait(false), async).ConfigureAwait(false); break; case DbDataType.TimeTZEx: await xdr.Write(await field.DbValue.GetTime(async).ConfigureAwait(false), async).ConfigureAwait(false); await xdr.Write(await field.DbValue.GetTimeZoneId(async).ConfigureAwait(false), async).ConfigureAwait(false); await xdr.Write((short)0, async).ConfigureAwait(false); break; case DbDataType.Dec16: await xdr.Write(await field.DbValue.GetDec16(async).ConfigureAwait(false), 16, async).ConfigureAwait(false); break; case DbDataType.Dec34: await xdr.Write(await field.DbValue.GetDec34(async).ConfigureAwait(false), 34, async).ConfigureAwait(false); break; case DbDataType.Int128: await xdr.Write(await field.DbValue.GetInt128(async).ConfigureAwait(false), async).ConfigureAwait(false); break; default: throw IscException.ForStrParam($"Unknown SQL data type: {field.DataType}."); } } }
public override DbValue[] Fetch() { if (State == StatementState.Deallocated) { throw new InvalidOperationException("Statement is not correctly created."); } if (StatementType == DbStatementType.StoredProcedure && !_allRowsFetched) { _allRowsFetched = true; return(GetOutputParameters()); } else if (StatementType == DbStatementType.Insert && _allRowsFetched) { return(null); } else if (StatementType != DbStatementType.Select && StatementType != DbStatementType.SelectForUpdate) { return(null); } if (!_allRowsFetched && _rows.Count == 0) { try { _database.Xdr.Write(IscCodes.op_fetch); _database.Xdr.Write(_handle); _database.Xdr.WriteBuffer(_fields.ToBlrArray()); _database.Xdr.Write(0); // p_sqldata_message_number _database.Xdr.Write(_fetchSize); // p_sqldata_messages _database.Xdr.Flush(); var operation = _database.ReadOperation(); if (operation == IscCodes.op_fetch_response) { var hasOperation = true; while (!_allRowsFetched) { #warning Possible refactoring to have smoother code for ReadResponse var response = hasOperation ? _database.ReadResponse(operation) : _database.ReadResponse(); hasOperation = false; if (response is FetchResponse fetchResponse) { if (fetchResponse.Count > 0 && fetchResponse.Status == 0) { _rows.Enqueue(ReadRow()); } else if (fetchResponse.Status == 100) { _allRowsFetched = true; } else { break; } } else { break; } } } else { _database.ReadResponse(operation); } } catch (IOException ex) { throw IscException.ForErrorCode(IscCodes.isc_network_error, ex); } } if (_rows != null && _rows.Count > 0) { return(_rows.Dequeue()); } else { _rows.Clear(); return(null); } }
public override async Task Execute(AsyncWrappingCommonArgs async) { EnsureNotDeallocated(); Clear(); try { RecordsAffected = -1; await SendExecuteToBuffer(async).ConfigureAwait(false); await _database.Xdr.Flush(async).ConfigureAwait(false); var numberOfResponses = (StatementType == DbStatementType.StoredProcedure ? 1 : 0) + 1; try { SqlResponse sqlStoredProcedureResponse = null; if (StatementType == DbStatementType.StoredProcedure) { numberOfResponses--; sqlStoredProcedureResponse = (SqlResponse)await _database.ReadResponse(async).ConfigureAwait(false); await ProcessStoredProcedureExecuteResponse(sqlStoredProcedureResponse, async).ConfigureAwait(false); } numberOfResponses--; var executeResponse = (GenericResponse)await _database.ReadResponse(async).ConfigureAwait(false); await ProcessExecuteResponse(executeResponse, async).ConfigureAwait(false); } finally { numberOfResponses = await SafeFinishFetching(numberOfResponses, async).ConfigureAwait(false); } // we need to split this in two, to allow server handle op_cancel properly if (DoRecordsAffected) { await SendInfoSqlToBuffer(RowsAffectedInfoItems, IscCodes.ROWS_AFFECTED_BUFFER_SIZE, async).ConfigureAwait(false); await _database.Xdr.Flush(async).ConfigureAwait(false); numberOfResponses = 1; try { numberOfResponses--; var rowsAffectedResponse = (GenericResponse)await _database.ReadResponse(async).ConfigureAwait(false); RecordsAffected = ProcessRecordsAffectedBuffer(await ProcessInfoSqlResponse(rowsAffectedResponse, async).ConfigureAwait(false)); } finally { numberOfResponses = await SafeFinishFetching(numberOfResponses, async).ConfigureAwait(false); } } State = StatementState.Executed; } catch (IOException ex) { State = StatementState.Error; throw IscException.ForIOException(ex); } }
public static void CreateDatabase(Hashtable values) { bool overwrite = false; int index = 0; byte dialect = 3; int serverType = 0; if (!values.ContainsKey("User") || !values.ContainsKey("Password") || !values.ContainsKey("Database")) { throw new ArgumentException("CreateDatabase requires a user name, password and database path."); } if (values.ContainsKey("ServerType")) { serverType = Convert.ToInt32(values["ServerType"], CultureInfo.InvariantCulture); } if (!values.ContainsKey("DataSource")) { values.Add("DataSource", "localhost"); } if (!values.ContainsKey("Port")) { values.Add("Port", 3050); } if (values.ContainsKey("Dialect")) { dialect = Convert.ToByte(values["Dialect"], CultureInfo.InvariantCulture); } if (dialect < 1 || dialect > 3) { throw new ArgumentException("Incorrect database dialect it should be 1, 2, or 3."); } if (values.ContainsKey("Overwrite")) { overwrite = (bool)values["Overwrite"]; } try { // Configure Attachment FbConnectionStringBuilder csb = new FbConnectionStringBuilder(); csb.DataSource = values["DataSource"].ToString(); csb.UserID = values["User"].ToString(); csb.Password = values["Password"].ToString(); csb.Database = values["Database"].ToString(); csb.Port = Convert.ToInt32(values["Port"], CultureInfo.InvariantCulture); csb.ServerType = serverType; FbConnectionString options = new FbConnectionString(csb); // DPB configuration DatabaseParameterBuffer dpb = new DatabaseParameterBuffer(); // Dpb version dpb.Append(IscCodes.isc_dpb_version1); // Dummy packet interval dpb.Append(IscCodes.isc_dpb_dummy_packet_interval, new byte[] { 120, 10, 0, 0 }); // User name dpb.Append(IscCodes.isc_dpb_user_name, values["User"].ToString()); // User password dpb.Append(IscCodes.isc_dpb_password, values["Password"].ToString()); // Database dialect dpb.Append(IscCodes.isc_dpb_sql_dialect, new byte[] { dialect, 0, 0, 0 }); // Database overwrite dpb.Append(IscCodes.isc_dpb_overwrite, (short)(overwrite ? 1 : 0)); // Character set if (values.ContainsKey("Charset")) { index = Charset.SupportedCharsets.IndexOf(values["Charset"].ToString()); if (index == -1) { throw new ArgumentException("Character set is not valid."); } else { dpb.Append( IscCodes.isc_dpb_set_db_charset, Charset.SupportedCharsets[index].Name); } } // Page Size if (values.ContainsKey("PageSize")) { dpb.Append(IscCodes.isc_dpb_page_size, Convert.ToInt32(values["PageSize"], CultureInfo.InvariantCulture)); } // Forced writes if (values.ContainsKey("ForcedWrite")) { dpb.Append(IscCodes.isc_dpb_force_write, (short)((bool)values["ForcedWrite"] ? 1 : 0)); } if (!overwrite) { try { // Check if the database exists FbConnectionInternal check = new FbConnectionInternal(options); check.Connect(); check.Disconnect(); IscException ex = new IscException(IscCodes.isc_db_or_file_exists); throw new FbException(ex.Message, ex); } catch (Exception) { throw; } } // Create the new database FbConnectionInternal c = new FbConnectionInternal(options); c.CreateDatabase(dpb); } catch (IscException ex) { throw new FbException(ex.Message, ex); } }
public override async Task Prepare(string commandText, AsyncWrappingCommonArgs async) { ClearAll(); try { var numberOfResponses = 0; if (State == StatementState.Deallocated) { await SendAllocateToBuffer(async).ConfigureAwait(false); numberOfResponses++; } await SendPrepareToBuffer(commandText, async).ConfigureAwait(false); numberOfResponses++; await SendInfoSqlToBuffer(StatementTypeInfoItems, IscCodes.STATEMENT_TYPE_BUFFER_SIZE, async).ConfigureAwait(false); numberOfResponses++; await _database.Xdr.Flush(async).ConfigureAwait(false); try { GenericResponse allocateResponse = null; if (State == StatementState.Deallocated) { numberOfResponses--; allocateResponse = (GenericResponse)await _database.ReadResponse(async).ConfigureAwait(false); } numberOfResponses--; var prepareResponse = (GenericResponse)await _database.ReadResponse(async).ConfigureAwait(false); var deferredExecute = ((prepareResponse.ObjectHandle & IscCodes.STMT_DEFER_EXECUTE) == IscCodes.STMT_DEFER_EXECUTE); numberOfResponses--; var statementTypeResponse = (GenericResponse)await _database.ReadResponse(async).ConfigureAwait(false); if (allocateResponse != null) { await ProcessAllocateResponse(allocateResponse, async).ConfigureAwait(false); } await ProcessPrepareResponse(prepareResponse, async).ConfigureAwait(false); StatementType = ProcessStatementTypeInfoBuffer(await ProcessInfoSqlResponse(statementTypeResponse, async).ConfigureAwait(false)); } finally { numberOfResponses = await SafeFinishFetching(numberOfResponses, async).ConfigureAwait(false); } State = StatementState.Prepared; } catch (IOException ex) { State = State == StatementState.Allocated ? StatementState.Error : State; throw IscException.ForErrorCode(IscCodes.isc_network_error, ex); } }
private async Task <byte[]> ReceiveSliceResponse(ArrayDesc desc, AsyncWrappingCommonArgs async) { try { var operation = await _database.ReadOperation(async).ConfigureAwait(false); if (operation == IscCodes.op_slice) { var isVariying = false; var elements = 0; var length = await _database.Xdr.ReadInt32(async).ConfigureAwait(false); length = await _database.Xdr.ReadInt32(async).ConfigureAwait(false); switch (desc.DataType) { case IscCodes.blr_text: case IscCodes.blr_text2: case IscCodes.blr_cstring: case IscCodes.blr_cstring2: elements = length / desc.Length; length += elements * ((4 - desc.Length) & 3); break; case IscCodes.blr_varying: case IscCodes.blr_varying2: elements = length / desc.Length; isVariying = true; break; case IscCodes.blr_short: length = length * desc.Length; break; } if (isVariying) { using (var ms = new MemoryStream()) { var xdr = new XdrReaderWriter(ms); for (var i = 0; i < elements; i++) { var buffer = await _database.Xdr.ReadOpaque(await _database.Xdr.ReadInt32(async).ConfigureAwait(false), async).ConfigureAwait(false); await xdr.WriteBuffer(buffer, buffer.Length, async).ConfigureAwait(false); } await xdr.Flush(async).ConfigureAwait(false); return(ms.ToArray()); } } else { return(await _database.Xdr.ReadOpaque(length, async).ConfigureAwait(false)); } } else { await _database.ReadResponse(operation, async).ConfigureAwait(false); return(null); } } catch (IOException ex) { throw IscException.ForErrorCode(IscCodes.isc_network_error, ex); } }
public override async ValueTask ExecuteAsync(int timeout, IDescriptorFiller descriptorFiller, CancellationToken cancellationToken = default) { EnsureNotDeallocated(); Clear(); try { RecordsAffected = -1; await SendExecuteToBufferAsync(timeout, descriptorFiller, cancellationToken).ConfigureAwait(false); await _database.Xdr.FlushAsync(cancellationToken).ConfigureAwait(false); var numberOfResponses = (StatementType == DbStatementType.StoredProcedure ? 1 : 0) + 1; try { SqlResponse sqlStoredProcedureResponse = null; if (StatementType == DbStatementType.StoredProcedure) { numberOfResponses--; sqlStoredProcedureResponse = (SqlResponse)await _database.ReadResponseAsync(cancellationToken).ConfigureAwait(false); await ProcessStoredProcedureExecuteResponseAsync(sqlStoredProcedureResponse, cancellationToken).ConfigureAwait(false); } numberOfResponses--; var executeResponse = (GenericResponse)await _database.ReadResponseAsync(cancellationToken).ConfigureAwait(false); await ProcessExecuteResponseAsync(executeResponse, cancellationToken).ConfigureAwait(false); } finally { await(Database as GdsDatabase).SafeFinishFetchingAsync(numberOfResponses, cancellationToken).ConfigureAwait(false); } // we need to split this in two, to allow server handle op_cancel properly if (DoRecordsAffected) { await SendInfoSqlToBufferAsync(RowsAffectedInfoItems, IscCodes.ROWS_AFFECTED_BUFFER_SIZE, cancellationToken).ConfigureAwait(false); await _database.Xdr.FlushAsync(cancellationToken).ConfigureAwait(false); numberOfResponses = 1; try { numberOfResponses--; var rowsAffectedResponse = (GenericResponse)await _database.ReadResponseAsync(cancellationToken).ConfigureAwait(false); RecordsAffected = ProcessRecordsAffectedBuffer(await ProcessInfoSqlResponseAsync(rowsAffectedResponse, cancellationToken).ConfigureAwait(false)); } finally { await(Database as GdsDatabase).SafeFinishFetchingAsync(numberOfResponses, cancellationToken).ConfigureAwait(false); } } State = StatementState.Executed; } catch (IOException ex) { State = StatementState.Error; throw IscException.ForIOException(ex); } }
public override void Execute() { EnsureNotDeallocated(); Clear(); try { RecordsAffected = -1; SendExecuteToBuffer(); var readRowsAffectedResponse = false; if (DoRecordsAffected) { SendInfoSqlToBuffer(RowsAffectedInfoItems, IscCodes.ROWS_AFFECTED_BUFFER_SIZE); readRowsAffectedResponse = true; } _database.Xdr.Flush(); var numberOfResponses = (StatementType == DbStatementType.StoredProcedure ? 1 : 0) + 1 + (readRowsAffectedResponse ? 1 : 0); try { SqlResponse sqlStoredProcedureResponse = null; if (StatementType == DbStatementType.StoredProcedure) { numberOfResponses--; sqlStoredProcedureResponse = (SqlResponse)_database.ReadResponse(); ProcessStoredProcedureExecuteResponse(sqlStoredProcedureResponse); } numberOfResponses--; var executeResponse = (GenericResponse)_database.ReadResponse(); GenericResponse rowsAffectedResponse = null; if (readRowsAffectedResponse) { numberOfResponses--; rowsAffectedResponse = (GenericResponse)_database.ReadResponse(); } ProcessExecuteResponse(executeResponse); if (readRowsAffectedResponse) { RecordsAffected = ProcessRecordsAffectedBuffer(ProcessInfoSqlResponse(rowsAffectedResponse)); } } finally { numberOfResponses = SafeFinishFetching(numberOfResponses); } State = StatementState.Executed; } catch (IOException ex) { State = StatementState.Error; throw IscException.ForIOException(ex); } }
public void FixNull() { if (NullFlag == -1 && _dbValue.IsDBNull()) { switch (DbDataType) { case DbDataType.Char: case DbDataType.VarChar: DbValue.SetValue(string.Empty); break; case DbDataType.Guid: DbValue.SetValue(Guid.Empty); break; case DbDataType.SmallInt: DbValue.SetValue((short)0); break; case DbDataType.Integer: DbValue.SetValue((int)0); break; case DbDataType.BigInt: case DbDataType.Binary: case DbDataType.Array: case DbDataType.Text: DbValue.SetValue((long)0); break; case DbDataType.Numeric: case DbDataType.Decimal: DbValue.SetValue((decimal)0); break; case DbDataType.Float: DbValue.SetValue((float)0); break; case DbDataType.Double: DbValue.SetValue((double)0); break; case DbDataType.Date: case DbDataType.TimeStamp: DbValue.SetValue(DateTime2.UnixEpoch); break; case DbDataType.Time: DbValue.SetValue(TimeSpan.Zero); break; case DbDataType.Boolean: DbValue.SetValue(false); break; case DbDataType.TimeStampTZ: case DbDataType.TimeStampTZEx: DbValue.SetValue(new FbZonedDateTime(DateTime2.UnixEpoch, TimeZoneMapping.DefaultTimeZoneName)); break; case DbDataType.TimeTZ: case DbDataType.TimeTZEx: DbValue.SetValue(new FbZonedTime(TimeSpan.Zero, TimeZoneMapping.DefaultTimeZoneName)); break; case DbDataType.Dec16: case DbDataType.Dec34: DbValue.SetValue(new FbDecFloat(0, 0)); break; case DbDataType.Int128: DbValue.SetValue((BigInteger)0); break; default: throw IscException.ForStrParam($"Unknown sql data type: {DataType}."); } } }
public override async ValueTask ExecuteAsync(CancellationToken cancellationToken = default) { EnsureNotDeallocated(); Clear(); try { RecordsAffected = -1; await SendExecuteToBufferAsync(cancellationToken).ConfigureAwait(false); var readRowsAffectedResponse = false; if (DoRecordsAffected) { await SendInfoSqlToBufferAsync(RowsAffectedInfoItems, IscCodes.ROWS_AFFECTED_BUFFER_SIZE, cancellationToken).ConfigureAwait(false); readRowsAffectedResponse = true; } await _database.Xdr.FlushAsync(cancellationToken).ConfigureAwait(false); var numberOfResponses = (StatementType == DbStatementType.StoredProcedure ? 1 : 0) + 1 + (readRowsAffectedResponse ? 1 : 0); try { SqlResponse sqlStoredProcedureResponse = null; if (StatementType == DbStatementType.StoredProcedure) { numberOfResponses--; sqlStoredProcedureResponse = (SqlResponse)await _database.ReadResponseAsync(cancellationToken).ConfigureAwait(false); await ProcessStoredProcedureExecuteResponseAsync(sqlStoredProcedureResponse, cancellationToken).ConfigureAwait(false); } numberOfResponses--; var executeResponse = (GenericResponse)await _database.ReadResponseAsync(cancellationToken).ConfigureAwait(false); GenericResponse rowsAffectedResponse = null; if (readRowsAffectedResponse) { numberOfResponses--; rowsAffectedResponse = (GenericResponse)await _database.ReadResponseAsync(cancellationToken).ConfigureAwait(false); } await ProcessExecuteResponseAsync(executeResponse, cancellationToken).ConfigureAwait(false); if (readRowsAffectedResponse) { RecordsAffected = ProcessRecordsAffectedBuffer(await ProcessInfoSqlResponseAsync(rowsAffectedResponse, cancellationToken).ConfigureAwait(false)); } } finally { numberOfResponses = await SafeFinishFetchingAsync(numberOfResponses, cancellationToken).ConfigureAwait(false); } State = StatementState.Executed; } catch (IOException ex) { State = StatementState.Error; throw IscException.ForIOException(ex); } }
public override DbValue[] Fetch() { if (_state == StatementState.Deallocated) { throw new InvalidOperationException("Statement is not correctly created."); } if (_statementType == DbStatementType.StoredProcedure && !_allRowsFetched) { _allRowsFetched = true; return(GetOutputParameters()); } else if (_statementType == DbStatementType.Insert && _allRowsFetched) { return(null); } else if (_statementType != DbStatementType.Select && _statementType != DbStatementType.SelectForUpdate) { return(null); } if (!_allRowsFetched && _rows.Count == 0) { try { _database.XdrStream.Write(IscCodes.op_fetch); _database.XdrStream.Write(_handle); _database.XdrStream.WriteBuffer(_fields.ToBlrArray()); _database.XdrStream.Write(0); // p_sqldata_message_number _database.XdrStream.Write(_fetchSize); // p_sqldata_messages _database.XdrStream.Flush(); if (_database.NextOperation() == IscCodes.op_fetch_response) { IResponse response = null; while (!_allRowsFetched) { response = _database.ReadResponse(); if (response is FetchResponse fetchResponse) { if (fetchResponse.Count > 0 && fetchResponse.Status == 0) { _rows.Enqueue(ReadRow()); } else if (fetchResponse.Status == 100) { _allRowsFetched = true; } else { break; } } else { break; } } } else { _database.ReadResponse(); } } catch (IOException ex) { throw IscException.ForErrorCode(IscCodes.isc_net_read_err, ex); } } if (_rows != null && _rows.Count > 0) { return(_rows.Dequeue()); } else { _rows.Clear(); return(null); } }
private async ValueTask <byte[]> ReceiveSliceResponseAsync(ArrayDesc desc, CancellationToken cancellationToken = default) { try { var operation = await _database.ReadOperationAsync(cancellationToken).ConfigureAwait(false); if (operation == IscCodes.op_slice) { var isVariying = false; var elements = 0; var length = await _database.Xdr.ReadInt32Async(cancellationToken).ConfigureAwait(false); length = await _database.Xdr.ReadInt32Async(cancellationToken).ConfigureAwait(false); switch (desc.DataType) { case IscCodes.blr_text: case IscCodes.blr_text2: case IscCodes.blr_cstring: case IscCodes.blr_cstring2: elements = length / desc.Length; length += elements * ((4 - desc.Length) & 3); break; case IscCodes.blr_varying: case IscCodes.blr_varying2: elements = length / desc.Length; isVariying = true; break; case IscCodes.blr_short: length = length * desc.Length; break; } if (isVariying) { using (var ms = new MemoryStream()) { var xdr = new XdrReaderWriter(new DataProviderStreamWrapper(ms)); for (var i = 0; i < elements; i++) { var buffer = await _database.Xdr.ReadOpaqueAsync(await _database.Xdr.ReadInt32Async(cancellationToken).ConfigureAwait(false), cancellationToken).ConfigureAwait(false); await xdr.WriteBufferAsync(buffer, buffer.Length, cancellationToken).ConfigureAwait(false); } await xdr.FlushAsync(cancellationToken).ConfigureAwait(false); return(ms.ToArray()); } } else { return(await _database.Xdr.ReadOpaqueAsync(length, cancellationToken).ConfigureAwait(false)); } } else { await _database.ReadResponseAsync(operation, cancellationToken).ConfigureAwait(false); return(null); } } catch (IOException ex) { throw IscException.ForIOException(ex); } }
protected void WriteRawParameter(XdrStream xdr, DbField field) { if (field.DbDataType != DbDataType.Null) { field.FixNull(); switch (field.DbDataType) { case DbDataType.Char: if (field.Charset.IsOctetsCharset) { xdr.WriteOpaque(field.DbValue.GetBinary(), field.Length); } else { var svalue = field.DbValue.GetString(); if ((field.Length % field.Charset.BytesPerCharacter) == 0 && svalue.Length > field.CharCount) { throw IscException.ForErrorCodes(new[] { IscCodes.isc_arith_except, IscCodes.isc_string_truncation }); } xdr.WriteOpaque(field.Charset.GetBytes(svalue), field.Length); } break; case DbDataType.VarChar: if (field.Charset.IsOctetsCharset) { xdr.WriteBuffer(field.DbValue.GetBinary()); } else { var svalue = field.DbValue.GetString(); if ((field.Length % field.Charset.BytesPerCharacter) == 0 && svalue.Length > field.CharCount) { throw IscException.ForErrorCodes(new[] { IscCodes.isc_arith_except, IscCodes.isc_string_truncation }); } xdr.WriteBuffer(field.Charset.GetBytes(svalue)); } break; case DbDataType.SmallInt: xdr.Write(field.DbValue.GetInt16()); break; case DbDataType.Integer: xdr.Write(field.DbValue.GetInt32()); break; case DbDataType.BigInt: case DbDataType.Array: case DbDataType.Binary: case DbDataType.Text: xdr.Write(field.DbValue.GetInt64()); break; case DbDataType.Decimal: case DbDataType.Numeric: xdr.Write(field.DbValue.GetDecimal(), field.DataType, field.NumericScale); break; case DbDataType.Float: xdr.Write(field.DbValue.GetFloat()); break; case DbDataType.Guid: xdr.Write(field.DbValue.GetGuid()); break; case DbDataType.Double: xdr.Write(field.DbValue.GetDouble()); break; case DbDataType.Date: xdr.Write(field.DbValue.GetDate()); break; case DbDataType.Time: xdr.Write(field.DbValue.GetTime()); break; case DbDataType.TimeStamp: xdr.Write(field.DbValue.GetDate()); xdr.Write(field.DbValue.GetTime()); break; case DbDataType.Boolean: xdr.Write(field.DbValue.GetBoolean()); break; default: throw IscException.ForStrParam($"Unknown SQL data type: {field.DataType}."); } } }
public override async ValueTask PrepareAsync(string commandText, CancellationToken cancellationToken = default) { ClearAll(); try { var numberOfResponses = 0; if (State == StatementState.Deallocated) { await SendAllocateToBufferAsync(cancellationToken).ConfigureAwait(false); numberOfResponses++; } await SendPrepareToBufferAsync(commandText, cancellationToken).ConfigureAwait(false); numberOfResponses++; await SendInfoSqlToBufferAsync(StatementTypeInfoItems, IscCodes.STATEMENT_TYPE_BUFFER_SIZE, cancellationToken).ConfigureAwait(false); numberOfResponses++; await _database.Xdr.FlushAsync(cancellationToken).ConfigureAwait(false); try { GenericResponse allocateResponse = null; if (State == StatementState.Deallocated) { numberOfResponses--; allocateResponse = (GenericResponse)await _database.ReadResponseAsync(cancellationToken).ConfigureAwait(false); } numberOfResponses--; var prepareResponse = (GenericResponse)await _database.ReadResponseAsync(cancellationToken).ConfigureAwait(false); var deferredExecute = ((prepareResponse.ObjectHandle & IscCodes.STMT_DEFER_EXECUTE) == IscCodes.STMT_DEFER_EXECUTE); numberOfResponses--; var statementTypeResponse = (GenericResponse)await _database.ReadResponseAsync(cancellationToken).ConfigureAwait(false); if (allocateResponse != null) { await ProcessAllocateResponseAsync(allocateResponse, cancellationToken).ConfigureAwait(false); } await ProcessPrepareResponseAsync(prepareResponse, cancellationToken).ConfigureAwait(false); StatementType = ProcessStatementTypeInfoBuffer(await ProcessInfoSqlResponseAsync(statementTypeResponse, cancellationToken).ConfigureAwait(false)); } finally { await(Database as GdsDatabase).SafeFinishFetchingAsync(numberOfResponses, cancellationToken).ConfigureAwait(false); } State = StatementState.Prepared; } catch (IOException ex) { State = State == StatementState.Allocated ? StatementState.Error : State; throw IscException.ForIOException(ex); } }
private byte[] ReceiveSliceResponse(ArrayDesc desc) { try { var operation = _database.ReadOperation(); if (operation == IscCodes.op_slice) { var isVariying = false; var elements = 0; var length = _database.Xdr.ReadInt32(); length = _database.Xdr.ReadInt32(); switch (desc.DataType) { case IscCodes.blr_text: case IscCodes.blr_text2: case IscCodes.blr_cstring: case IscCodes.blr_cstring2: elements = length / desc.Length; length += elements * ((4 - desc.Length) & 3); break; case IscCodes.blr_varying: case IscCodes.blr_varying2: elements = length / desc.Length; isVariying = true; break; case IscCodes.blr_short: length = length * desc.Length; break; } if (isVariying) { using (var ms = new MemoryStream()) { var xdr = new XdrReaderWriter(ms); for (var i = 0; i < elements; i++) { var buffer = _database.Xdr.ReadOpaque(_database.Xdr.ReadInt32()); xdr.WriteBuffer(buffer, buffer.Length); } xdr.Flush(); return(ms.ToArray()); } } else { return(_database.Xdr.ReadOpaque(length)); } } else { _database.ReadResponse(operation); return(null); } } catch (IOException ex) { throw IscException.ForErrorCode(IscCodes.isc_network_error, ex); } }
public static IscException ParseStatusVector(int[] statusVector) { IscException exception = null; bool eof = false; for (int i = 0; i < statusVector.Length;) { int arg = statusVector[i++]; switch (arg) { case IscCodes.isc_arg_gds: int er = statusVector[i++]; if (er != 0) { if (exception == null) { exception = new IscException(); } exception.Errors.Add(arg, er); } break; case IscCodes.isc_arg_end: if (exception != null && exception.Errors.Count != 0) { exception.BuildExceptionMessage(); } eof = true; break; case IscCodes.isc_arg_interpreted: case IscCodes.isc_arg_string: { IntPtr ptr = new IntPtr(statusVector[i++]); string arg_value = Marshal.PtrToStringAnsi(ptr); exception.Errors.Add(arg, arg_value); } break; case IscCodes.isc_arg_cstring: { i++; IntPtr ptr = new IntPtr(statusVector[i++]); string arg_value = Marshal.PtrToStringAnsi(ptr); exception.Errors.Add(arg, arg_value); } break; case IscCodes.isc_arg_win32: case IscCodes.isc_arg_number: exception.Errors.Add(arg, statusVector[i++]); break; default: { int e = statusVector[i++]; if (e != 0) { if (exception == null) { exception = new IscException(); } exception.Errors.Add(arg, e); } } break; } if (eof) { break; } } return(exception); }
public override void Execute() { if (_state == StatementState.Deallocated) { throw new InvalidOperationException("Statement is not correctly created."); } Clear(); try { RecordsAffected = -1; SendExecuteToBuffer(); _database.XdrStream.Flush(); var numberOfResponses = (StatementType == DbStatementType.StoredProcedure ? 1 : 0) + 1; try { SqlResponse sqlStoredProcedureResponse = null; if (StatementType == DbStatementType.StoredProcedure) { numberOfResponses--; sqlStoredProcedureResponse = _database.ReadSqlResponse(); ProcessStoredProcedureExecuteResponse(sqlStoredProcedureResponse); } numberOfResponses--; var executeResponse = _database.ReadGenericResponse(); ProcessExecuteResponse(executeResponse); } finally { SafeFinishFetching(ref numberOfResponses); } // we need to split this in two, to alloow server handle op_cancel properly if (ReturnRecordsAffected && (StatementType == DbStatementType.Insert || StatementType == DbStatementType.Delete || StatementType == DbStatementType.Update || StatementType == DbStatementType.StoredProcedure || StatementType == DbStatementType.Select)) { SendInfoSqlToBuffer(RowsAffectedInfoItems, IscCodes.ROWS_AFFECTED_BUFFER_SIZE); _database.XdrStream.Flush(); numberOfResponses = 1; try { numberOfResponses--; var rowsAffectedResponse = _database.ReadGenericResponse(); RecordsAffected = ProcessRecordsAffectedBuffer(ProcessInfoSqlResponse(rowsAffectedResponse)); } finally { SafeFinishFetching(ref numberOfResponses); } } _state = StatementState.Executed; } catch (IOException ex) { _state = StatementState.Error; throw IscException.ForErrorCode(IscCodes.isc_net_read_err, ex); } }
public override async Task Execute(AsyncWrappingCommonArgs async) { EnsureNotDeallocated(); Clear(); try { RecordsAffected = -1; await SendExecuteToBuffer(async).ConfigureAwait(false); var readRowsAffectedResponse = false; if (DoRecordsAffected) { await SendInfoSqlToBuffer(RowsAffectedInfoItems, IscCodes.ROWS_AFFECTED_BUFFER_SIZE, async).ConfigureAwait(false); readRowsAffectedResponse = true; } await _database.Xdr.Flush(async).ConfigureAwait(false); var numberOfResponses = (StatementType == DbStatementType.StoredProcedure ? 1 : 0) + 1 + (readRowsAffectedResponse ? 1 : 0); try { SqlResponse sqlStoredProcedureResponse = null; if (StatementType == DbStatementType.StoredProcedure) { numberOfResponses--; sqlStoredProcedureResponse = (SqlResponse)await _database.ReadResponse(async).ConfigureAwait(false); await ProcessStoredProcedureExecuteResponse(sqlStoredProcedureResponse, async).ConfigureAwait(false); } numberOfResponses--; var executeResponse = (GenericResponse)await _database.ReadResponse(async).ConfigureAwait(false); GenericResponse rowsAffectedResponse = null; if (readRowsAffectedResponse) { numberOfResponses--; rowsAffectedResponse = (GenericResponse)await _database.ReadResponse(async).ConfigureAwait(false); } await ProcessExecuteResponse(executeResponse, async).ConfigureAwait(false); if (readRowsAffectedResponse) { RecordsAffected = ProcessRecordsAffectedBuffer(await ProcessInfoSqlResponse(rowsAffectedResponse, async).ConfigureAwait(false)); } } finally { numberOfResponses = await SafeFinishFetching(numberOfResponses, async).ConfigureAwait(false); } State = StatementState.Executed; } catch (IOException ex) { State = StatementState.Error; throw IscException.ForErrorCode(IscCodes.isc_network_error, ex); } }
public void Identify(string database) { using (var xdrStream = CreateXdrStreamImpl(false)) { try { xdrStream.Write(IscCodes.op_connect); xdrStream.Write(IscCodes.op_attach); xdrStream.Write(IscCodes.CONNECT_VERSION3); xdrStream.Write(IscCodes.GenericAchitectureClient); xdrStream.Write(database); var protocols = ProtocolsSupported.Get(_compression); xdrStream.Write(protocols.Count()); xdrStream.WriteBuffer(UserIdentificationData()); var priority = 0; foreach (var protocol in protocols) { xdrStream.Write(protocol.Version); xdrStream.Write(IscCodes.GenericAchitectureClient); xdrStream.Write(protocol.MinPType); xdrStream.Write(protocol.MaxPType); xdrStream.Write(priority); priority++; } xdrStream.Flush(); var operation = xdrStream.ReadOperation(); if (operation == IscCodes.op_accept || operation == IscCodes.op_cond_accept || operation == IscCodes.op_accept_data) { _protocolVersion = xdrStream.ReadInt32(); _protocolArchitecture = xdrStream.ReadInt32(); _protocolMinimunType = xdrStream.ReadInt32(); if (_protocolVersion < 0) { _protocolVersion = (ushort)(_protocolVersion & IscCodes.FB_PROTOCOL_MASK) | IscCodes.FB_PROTOCOL_FLAG; } if (_compression && !((_protocolMinimunType & IscCodes.pflag_compress) != 0)) { _compression = false; } if (operation == IscCodes.op_cond_accept || operation == IscCodes.op_accept_data) { var data = xdrStream.ReadBuffer(); var acceptPluginName = xdrStream.ReadString(); var isAuthenticated = xdrStream.ReadBoolean(); var keys = xdrStream.ReadString(); if (!isAuthenticated) { switch (acceptPluginName) { case SrpClient.PluginName: _authData = Encoding.ASCII.GetBytes(_srp.ClientProof(NormalizeLogin(_userID), _password, data).ToHexString()); break; case SspiHelper.PluginName: _authData = _sspi.GetClientSecurity(data); break; default: throw new ArgumentOutOfRangeException(nameof(acceptPluginName), $"{nameof(acceptPluginName)}={acceptPluginName}"); } } } } else if (operation == IscCodes.op_response) { var response = (GenericResponse)ProcessOperation(operation, xdrStream); throw response.Exception; } else { try { Disconnect(); } catch { } finally { throw IscException.ForErrorCode(IscCodes.isc_connect_reject); } } } catch (IOException ex) { throw IscException.ForErrorCode(IscCodes.isc_network_error, ex); } finally { // UserIdentificationData might allocate these _srp = null; _sspi?.Dispose(); _sspi = null; } } }
internal IscException ReadStatusVector() { IscException exception = null; bool eof = false; try { while (!eof) { int arg = this.receive.ReadInt32(); switch (arg) { case IscCodes.isc_arg_gds: int er = this.receive.ReadInt32(); if (er != 0) { if (exception == null) { exception = new IscException(); } exception.Errors.Add(arg, er); } break; case IscCodes.isc_arg_end: if (exception != null && exception.Errors.Count != 0) { exception.BuildExceptionMessage(); } eof = true; break; case IscCodes.isc_arg_interpreted: case IscCodes.isc_arg_string: exception.Errors.Add(arg, this.receive.ReadString()); break; case IscCodes.isc_arg_number: exception.Errors.Add(arg, this.receive.ReadInt32()); break; default: { int e = this.receive.ReadInt32(); if (e != 0) { if (exception == null) { exception = new IscException(); } exception.Errors.Add(arg, e); } } break; } } } catch (IOException) { throw new IscException(IscCodes.isc_arg_gds, IscCodes.isc_net_read_err); } if (exception != null && !exception.IsWarning) { throw exception; } return(exception); }