gen_writers

Generates the code for the "bulk writers" in the "BulkWriter" C# shared libraries.
git clone https://git.philomathiclife.com/repos/gen_writers
Log | Files | Refs | README

commit d98629b9a9269f23063d71738ffa1d02243b6a7c
Author: Zack Newman <zack@philomathiclife.com>
Date:   Mon, 20 Mar 2023 16:15:17 -0600

initial

Diffstat:
A.gitignore | 2++
ACargo.toml | 15+++++++++++++++
ALICENSE-APACHE | 177+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
ALICENSE-MIT | 20++++++++++++++++++++
AREADME.md | 4++++
Asrc/main.rs | 186+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
6 files changed, 404 insertions(+), 0 deletions(-)

diff --git a/.gitignore b/.gitignore @@ -0,0 +1,2 @@ +Cargo.lock +target/** diff --git a/Cargo.toml b/Cargo.toml @@ -0,0 +1,15 @@ +[package] +authors = ["Zack Newman <zack@philomathiclife.com>"] +categories = ["command-line-utilities"] +description = "Generates the 'bulk writers' in the BulkWriters128 and BulkWriters256 C# shared libraries." +edition = "2021" +keywords = ["cli", "C#"] +license = "MIT OR Apache-2.0" +name = "gen_writers" +readme = "README.md" +repository = "https://git.philomathiclife.com/repos/gen_writers/" +version = "1.0.0" + +[[bin]] +name = "gw" +path = "src/main.rs" diff --git a/LICENSE-APACHE b/LICENSE-APACHE @@ -0,0 +1,177 @@ + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS diff --git a/LICENSE-MIT b/LICENSE-MIT @@ -0,0 +1,20 @@ +Copyright © 2023 Zack Newman + +Permission is hereby granted, free of charge, to any person obtaining a +copy of this software and associated documentation files (the +“Software”), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so, subject to +the following conditions: + +The above copyright notice and this permission notice shall be included +in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS +OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. +IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY +CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, +TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE +SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/README.md b/README.md @@ -0,0 +1,4 @@ +gen_writers +-------- +Generates the code for the "bulk writers" in the `BulkWriters128` +and `BulkWriters256` C# shared libraries. diff --git a/src/main.rs b/src/main.rs @@ -0,0 +1,186 @@ +//! This crate generates the code for the "bulk writers" +//! in the `BulkWriters128` and `BulkWriters256` C# libraries. +#![no_implicit_prelude] +#![deny( + unsafe_code, + unused, + warnings, + clippy::all, + clippy::cargo, + clippy::nursery, + clippy::pedantic +)] +#![allow( + clippy::arithmetic_side_effects, + clippy::implicit_return, + clippy::integer_arithmetic +)] +#[allow(unused_extern_crates)] +extern crate alloc; +#[allow(unused_extern_crates)] +extern crate core; +#[allow(unused_extern_crates)] +extern crate std; +use alloc::string::{String, ToString}; +use core::clone::Clone; +use core::convert::From; +use core::fmt::{self, Debug, Display, Formatter}; +use core::result::Result::{self, Ok}; +use std::env; +use std::fs::File; +use std::io::{Error, Write}; +fn main() -> Result<(), GenErr> { + #[allow(deprecated)] + let mut path0 = env::home_dir().ok_or(GenErr::HomeVarNotSet)?; + path0.push(".c#"); + let mut path1 = path0.clone(); + path0.push("BulkWriters128/BulkWriters.cs"); + let mut f = File::options().write(true).create_new(true).open(path0)?; + path1.push("BulkWriters256/BulkWriters.cs"); + let mut f2 = File::options().write(true).create_new(true).open(path1)?; + let mut s = String::with_capacity(32561); + write(&mut f, 0, &mut s)?; + write(&mut f2, 128, &mut s)?; + Ok(()) +} +/// Writes the file. +/// `s` is used as a buffer to write an entire `BulkWriter` into +/// before being used by `f` to write to the underlying file descriptor. +/// `v` is the starting arity of tuples: 0 or 128. +fn write(f: &mut File, v: u8, s: &mut String) -> Result<(), Error> { + s.push_str("// This code was generated via a CLI app that used the source code in BulkWriterBaseCase.cs as a template. +// To improve compilation performance, the code uses very little 'whitespace' beyond what is necessary and contains no documentation, warning suppressions, or comments. +using Microsoft.Data.SqlClient; +using Serde.Bin.Ser; +using Std; +using Std.Iter; +using Std.Maybe; +using Std.Num; +using Std.Result; +using System; +using System.Data; +using System.Diagnostics; +using static SQLServer.Helpers; +using System.Runtime.InteropServices; +#pragma warning disable CA1005, CA1045, CA1051, CA1062, CA1066, CA1815, CA2100, CA2231, IDE0032 +namespace SQLServer {\n"); + // + for i in (if v == 0 { 1 } else { v })..=(v + 127) { + s.push_str("[StructLayout(LayoutKind.Sequential,CharSet=CharSet.Unicode,Pack= 0)]public struct BulkWriter<"); + for j in 0..=i { + Kind::T.write(s, j); + } + s.pop(); + s.push_str(">:IBulkWriter "); + for j in 0..=i { + Kind::Bound.write(s, j); + } + s.pop(); + s.push_str(r#"{public BulkWriter()=>throw new InvalidOperationException("Parameterless constructor is not allowed to be called!");BulkWriter(UserTable table,Maybe<ErrorTable>errTable,Prod<ulong,double>maxErrorsAllowed,string processName,string userName,bool encrypted,bool encryptedMod)=>(Destination,ErrTable,MaxErrorsAllowed,_currentErrorCount,_currentProcessedCount,_processName,_userName,_containsEncryptedColumn,_mustBeAllowEncryptedValueModifications)=(table,errTable,maxErrorsAllowed,ulong.MinValue,ulong.MinValue,processName,userName,encrypted,encryptedMod);public readonly Maybe<ErrorTable>ErrTable;public readonly UserTable Destination;public readonly Prod<ulong,double>MaxErrorsAllowed;ulong _currentErrorCount;ulong _currentProcessedCount;readonly string _processName;readonly string _userName;readonly bool _containsEncryptedColumn;readonly bool _mustBeAllowEncryptedValueModifications;readonly Maybe<ErrorTable>IBulkWriter.ErrTable=>ErrTable;readonly UserTable IBulkWriter.Destination=>Destination;readonly Prod<ulong,double>IBulkWriter.MaxErrorsAllowed=>MaxErrorsAllowed;public readonly ulong CurrentSuccessfullyProcessedCount=>_currentProcessedCount-_currentErrorCount;public readonly ulong CurrentErrorCount=>_currentErrorCount;public readonly ulong CurrentProcessedCount=>_currentProcessedCount;public readonly double CurrentErrorRatio=>(double)_currentErrorCount/_currentProcessedCount;public readonly bool IsInError=>_currentErrorCount>MaxErrorsAllowed.Item0&&CurrentErrorRatio>MaxErrorsAllowed.Item1;public static Result<BulkWriter<"#); + for j in 0..=i { + Kind::T.write(s, j); + } + s.pop(); + s.push_str(">,BulkWriterCreateError>New(in UserTable table,Prod<ulong,double>maxErrorsAllowed,in Maybe<ErrorTable>errTable,string processName,string userName){if(table.Schema.Database.IsReadOnly){return new(new BulkWriterCreateError(BulkWriterCreateError.Tag.DatabaseIsReadOnly,new StackTrace(1,true)));}else if(double.IsNaN(maxErrorsAllowed.Item1)||double.IsNegative(maxErrorsAllowed.Item1)||maxErrorsAllowed.Item1>1.0d){return new(new BulkWriterCreateError(BulkWriterCreateError.Tag.InvalidErrorRatio,new StackTrace(1,true)));}else if(processName.Length>128){return new(new BulkWriterCreateError(BulkWriterCreateError.Tag.ProcessNameLengthExceeds128,new StackTrace(1,true)));}else if(userName.Length>128){return new(new BulkWriterCreateError(BulkWriterCreateError.Tag.UserNameLengthExceeds128,new StackTrace(1,true)));}else{var counter=ushort.MinValue;var match=TypeMatch(Std.Iter.Functions.FromFn(()=>counter++switch{"); + for j in 0..=i { + Kind::GetType.write(s, j); + } + s.push_str("_=>Maybe<Type>.None()}),in table);return match.IsSome?match.Unwrap()?new(new BulkWriter<"); + for j in 0..=i { + Kind::T.write(s, j); + } + s.pop(); + s.push_str(">(table,errTable,maxErrorsAllowed,processName,userName,table.ContainsEncryptedColumn(),false)):new(new BulkWriterCreateError(BulkWriterCreateError.Tag.TypeMismatch,new StackTrace(1,true))):new(new BulkWriter<"); + for j in 0..=i { + Kind::T.write(s, j); + } + s.pop(); + s.push_str(">(table,errTable,maxErrorsAllowed,processName,userName,true,true));}}public override readonly bool Equals(object?_)=>false;public override readonly int GetHashCode()=>0;readonly void IBulkWriter.Sealed(){}public override readonly string ToString()=>string.Empty;public Result<Unit,WriteError>Write<TRowIter,TRow,TProd,TErr>(ref TRowIter iter,WriteOptions writeOptions,Maybe<NonZeroUshort>batchSize,Maybe<NonZeroUshort>timeout,bool enableStreaming,bool isSortedAccordingToClusteredIndex,SessionOptions options)where TErr:notnull,IBulkRowError where TProd:notnull,IBinSerializable,IProduct<"); + for j in 0..=i { + Kind::T.write(s, j); + } + s.pop(); + s.push_str(r#">where TRow:notnull,ISum<TProd,TErr>where TRowIter:notnull,IFusedIterator<TRow>{var allowEncryptMod=false;if((writeOptions&WriteOptions.AllowEncryptedValueModifications)==WriteOptions.AllowEncryptedValueModifications){if(_containsEncryptedColumn){allowEncryptMod=true;}else{return new(new WriteError(WriteError.Tag.TableExpectedToContainEncryptedDataButDoesNot,new StackTrace(1,true)));}}else if(_mustBeAllowEncryptedValueModifications){return new(new WriteError(WriteError.Tag.TableColumnMismatchOrWriteOptionsMustContainAllowEncryptedValueModifications,new StackTrace(1,true)));}using var con=Functions.CreateOpenedConnection(in Destination.Schema.Database,options,!allowEncryptMod&&_containsEncryptedColumn,Maybe<Uri>.None());if((writeOptions&WriteOptions.KeepIdentity)==WriteOptions.KeepIdentity&&Destination.ContainsIDENTITYColumn()){using var txn=con.BeginTransaction(IsolationLevel.Serializable);using (SqlCommand qry=new($"SET IDENTITY_INSERT [{Destination.Schema.Name.Value}].[{Destination.Name}] ON;",con,txn,SqlCommandColumnEncryptionSetting.Disabled){CommandTimeout=60,CommandType=CommandType.Text,EnableOptimizedParameterBinding=true}){_=qry.ExecuteNonQuery();}txn.Commit();}return WriteInternal<TRowIter,TRow,TProd,TErr>(ref iter,writeOptions,batchSize,timeout,enableStreaming,isSortedAccordingToClusteredIndex,con,null,(options&SessionOptions.NUMERIC_ROUNDABORT_OFF)!=SessionOptions.NUMERIC_ROUNDABORT_OFF,new StackTrace(1,true).ToString()).MapErr(_writeTxnErrToWriteErr);}public Result<Unit,WriteErrorOrTransactionError>Write<TRowIter,TRow,TProd,TErr>(ref TRowIter iter,WriteOptions writeOptions,Maybe<NonZeroUshort>batchSize,Maybe<NonZeroUshort>timeout,bool enableStreaming,bool isSortedAccordingToClusteredIndex,SqlTransaction txn)where TErr:notnull,IBulkRowError where TProd:notnull,IBinSerializable,IProduct<"#); + for j in 0..=i { + Kind::T.write(s, j); + } + s.pop(); + s.push_str(r#">where TRow:notnull,ISum<TProd,TErr>where TRowIter:notnull,IFusedIterator<TRow>{if(txn.Connection.State!=ConnectionState.Open){return new(new WriteErrorOrTransactionError(WriteErrorOrTransactionError.Tag.SqlConnectionIsNotOpen,new StackTrace(1,true)));}else if(!string.Equals(txn.Connection.DataSource,$"tcp:{Destination.Schema.Database.Server.IntoString()}",StringComparison.Ordinal)){return new(new WriteErrorOrTransactionError(WriteErrorOrTransactionError.Tag.SqlConnectionServerMismatch,new StackTrace(1,true)));}else{if((writeOptions&WriteOptions.AllowEncryptedValueModifications)==WriteOptions.AllowEncryptedValueModifications){if(_containsEncryptedColumn){if(!txn.Connection.ConnectionString.Contains("Column Encryption Setting=enabled",StringComparison.Ordinal)){return new(new WriteErrorOrTransactionError(WriteErrorOrTransactionError.Tag.SqlConnectionViolatesAllowEncryptedValueModifications,new StackTrace(1,true)));}}else{return new(new WriteErrorOrTransactionError(WriteErrorOrTransactionError.Tag.TableExpectedToContainEncryptedDataButDoesNot,new StackTrace(1,true)));}}else if(_mustBeAllowEncryptedValueModifications){return new(new WriteErrorOrTransactionError(WriteErrorOrTransactionError.Tag.TableColumnMismatchOrWriteOptionsMustContainAllowEncryptedValueModifications,new StackTrace(1,true)));}else if(_containsEncryptedColumn&&!txn.Connection.ConnectionString.Contains("Column Encryption Setting=enabled",StringComparison.Ordinal)){return new(new WriteErrorOrTransactionError(WriteErrorOrTransactionError.Tag.ContainsEncryptedColumnsButConnectionDoesNotHandleEncryptedColumns,new StackTrace(1,true)));}if((writeOptions&WriteOptions.KeepIdentity)==WriteOptions.KeepIdentity&&Destination.ContainsIDENTITYColumn()){bool numericRoundAbort;using (SqlCommand qry=new($@"SET IDENTITY_INSERT [{Destination.Schema.Database.Name.Value}].[{Destination.Schema.Name.Value}].[{Destination.Name}] ON;SELECT CASE (@@OPTIONS & 8192) WHEN 8192 THEN CONVERT(bit,1) ELSE CONVERT(bit,0) END AS fblnNumericRoundabort;",txn.Connection,txn,SqlCommandColumnEncryptionSetting.Disabled){CommandTimeout=timeout.MapOr(0,_nzUshortToInt),CommandType=CommandType.Text,EnableOptimizedParameterBinding=true}){numericRoundAbort=(bool)qry.ExecuteScalar();}var tableCopy=Destination;return WriteInternal<TRowIter,TRow,TProd,TErr>(ref iter,writeOptions,batchSize,timeout,enableStreaming,isSortedAccordingToClusteredIndex,txn.Connection,txn,numericRoundAbort,new StackTrace(1,true).ToString()).MapOrElse((err)=>{using SqlCommand qry=new($"SET IDENTITY_INSERT [{tableCopy.Schema.Database.Name.Value}].[{tableCopy.Schema.Name.Value}].[{tableCopy.Name}] OFF;",txn.Connection,txn,SqlCommandColumnEncryptionSetting.Disabled){CommandTimeout=timeout.MapOr(0,_nzUshortToInt),CommandType=CommandType.Text,EnableOptimizedParameterBinding=true};_=qry.ExecuteNonQuery();return new Result<Unit,WriteErrorOrTransactionError>(err);},(x)=>{using SqlCommand qry=new($"SET IDENTITY_INSERT [{tableCopy.Schema.Database.Name.Value}].[{tableCopy.Schema.Name.Value}].[{tableCopy.Name}] OFF;",txn.Connection,txn,SqlCommandColumnEncryptionSetting.Disabled){CommandTimeout=timeout.MapOr(0,_nzUshortToInt),CommandType=CommandType.Text,EnableOptimizedParameterBinding=true};var unused=qry.ExecuteNonQuery();return new(x);});}else{bool numericRoundAbort;using (SqlCommand qry=new($@"SELECT CASE (@@OPTIONS & 8192) WHEN 8192 THEN CONVERT(bit,1) ELSE CONVERT(bit,0) END AS fblnNumericRoundabort;",txn.Connection,txn,SqlCommandColumnEncryptionSetting.Disabled){CommandTimeout=timeout.MapOr(0,_nzUshortToInt),CommandType=CommandType.Text,EnableOptimizedParameterBinding=true}){numericRoundAbort=(bool)qry.ExecuteScalar();}return WriteInternal<TRowIter,TRow,TProd,TErr>(ref iter,writeOptions,batchSize,timeout,enableStreaming,isSortedAccordingToClusteredIndex,txn.Connection,txn,numericRoundAbort,new StackTrace(1,true).ToString());}}}Result<Unit,WriteErrorOrTransactionError>WriteInternal<TRowIter,TRow,TProd,TErr>(ref TRowIter iter,WriteOptions writeOptions,Maybe<NonZeroUshort>batchSize,Maybe<NonZeroUshort>timeout,bool enableStreaming,bool isSortedAccordingToClusteredIndex,SqlConnection con,SqlTransaction?txn,bool numericRoundAbort,string stackTrace)where TErr:notnull,IBulkRowError where TProd:notnull,IBinSerializable,IProduct<"#); + for j in 0..=i { + Kind::T.write(s, j); + } + s.pop(); + s.push_str(">where TRow:notnull,ISum<TProd,TErr>where TRowIter:notnull,IFusedIterator<TRow>{if(_currentErrorCount>MaxErrorsAllowed.Item0&&CurrentErrorRatio>MaxErrorsAllowed.Item1){return new(new WriteErrorOrTransactionError(WriteErrorOrTransactionError.Tag.MaxErrorsExceeded,new StackTrace(1,true)));}using var blk=CreateBulkCopy(in Destination,writeOptions,batchSize,timeout,enableStreaming,isSortedAccordingToClusteredIndex,con,txn);using IterDataReader<TRowIter,TRow,TProd,TErr,"); + for j in 0..=i { + Kind::T.write(s, j); + } + s.pop(); + s.push_str(">rdr=new(ErrTable,Destination,MaxErrorsAllowed,_currentProcessedCount,_currentErrorCount,iter,_processName,_userName,numericRoundAbort,stackTrace);blk.WriteToServer(rdr);_currentProcessedCount=rdr.CurrentProcessedCount;return (_currentErrorCount=rdr.CurrentErrorCount)>MaxErrorsAllowed.Item0&&CurrentErrorRatio>MaxErrorsAllowed.Item1?new(new WriteErrorOrTransactionError(WriteErrorOrTransactionError.Tag.MaxErrorsExceeded,new StackTrace(1,true))):new(new Unit());}}\n"); + f.write_all(s.as_bytes())?; + s.clear(); + } + f.write_all(&[b'}'])?; + f.flush() +} +/// The source code for a `BulkWriter` has multiple areas dependent +/// on the n-arity tuple that is written to the table. The code of which +/// is different, so we model those differences here. +enum Kind { + /// Represents the sequence of type parameters T0...Tn. + T, + /// Represents the type bounds for T0...Tn. + Bound, + /// Represents the portion of the source code based on T0...Tn + /// in the `New` function. + GetType, +} +impl Kind { + /// Writes the source code related to a single type parameter. + fn write(self, buffer: &mut String, i: u8) { + let s = &i.to_string(); + match self { + Self::T => { + buffer.push('T'); + buffer.push_str(s); + buffer.push(','); + } + Self::Bound => { + buffer.push_str("where "); + buffer.push('T'); + buffer.push_str(s); + buffer.push_str(":struct,IDataType "); + } + Self::GetType => { + buffer.push_str(s); + buffer.push_str("=>new(typeof(T"); + buffer.push_str(s); + buffer.push_str(")),"); + } + } + } +} +/// The errors possible. +enum GenErr { + /// Error when `$HOME` is not set. + HomeVarNotSet, + /// Error containing a general IO error. + Error(Error), +} +impl Display for GenErr { + fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result { + match *self { + Self::HomeVarNotSet => f.write_str("$HOME is not set."), + Self::Error(ref e) => <Error as Display>::fmt(e, f), + } + } +} +impl Debug for GenErr { + fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result { + <Self as Display>::fmt(self, f) + } +} +impl From<Error> for GenErr { + fn from(value: Error) -> Self { + Self::Error(value) + } +}