/
DBCommandBuilder.cs
1642 lines (1463 loc) · 59.1 KB
/
DBCommandBuilder.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System.ComponentModel;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Text;
using System.Text.RegularExpressions;
namespace System.Data.Common
{
public abstract class DbCommandBuilder : Component
{
private sealed class ParameterNames
{
private const string DefaultOriginalPrefix = "Original_";
private const string DefaultIsNullPrefix = "IsNull_";
// we use alternative prefix if the default prefix fails parametername validation
private const string AlternativeOriginalPrefix = "original";
private const string AlternativeIsNullPrefix = "isnull";
private const string AlternativeOriginalPrefix2 = "ORIGINAL";
private const string AlternativeIsNullPrefix2 = "ISNULL";
private string? _originalPrefix;
private string? _isNullPrefix;
private readonly Regex _parameterNameParser;
private readonly DbCommandBuilder _dbCommandBuilder;
private readonly string?[] _baseParameterNames;
private readonly string?[] _originalParameterNames;
private readonly string?[] _nullParameterNames;
private readonly bool[] _isMutatedName;
private readonly int _count;
private int _genericParameterCount;
private readonly int _adjustedParameterNameMaxLength;
internal ParameterNames(DbCommandBuilder dbCommandBuilder, DbSchemaRow?[] schemaRows)
{
_dbCommandBuilder = dbCommandBuilder;
_baseParameterNames = new string[schemaRows.Length];
_originalParameterNames = new string[schemaRows.Length];
_nullParameterNames = new string[schemaRows.Length];
_isMutatedName = new bool[schemaRows.Length];
_count = schemaRows.Length;
_parameterNameParser = new Regex(_dbCommandBuilder.ParameterNamePattern!, RegexOptions.ExplicitCapture | RegexOptions.Singleline);
SetAndValidateNamePrefixes();
_adjustedParameterNameMaxLength = GetAdjustedParameterNameMaxLength();
// Generate the baseparameter names and remove conflicting names
// No names will be generated for any name that is rejected due to invalid prefix, regex violation or
// name conflict after mutation.
// All null values will be replaced with generic parameter names
//
for (int i = 0; i < schemaRows.Length; i++)
{
var schemaRow = schemaRows[i];
if (null == schemaRow)
{
continue;
}
bool isMutatedName = false;
string columnName = schemaRow.ColumnName;
// all names that start with original- or isNullPrefix are invalid
if (null != _originalPrefix)
{
if (columnName.StartsWith(_originalPrefix, StringComparison.OrdinalIgnoreCase))
{
continue;
}
}
if (null != _isNullPrefix)
{
if (columnName.StartsWith(_isNullPrefix, StringComparison.OrdinalIgnoreCase))
{
continue;
}
}
// Mutate name if it contains space(s)
if (columnName.Contains(' '))
{
columnName = columnName.Replace(' ', '_');
isMutatedName = true;
}
// Validate name against regular expression
if (!_parameterNameParser.IsMatch(columnName))
{
continue;
}
// Validate name against adjusted max parametername length
if (columnName.Length > _adjustedParameterNameMaxLength)
{
continue;
}
_baseParameterNames[i] = columnName;
_isMutatedName[i] = isMutatedName;
}
EliminateConflictingNames();
// Generate names for original- and isNullparameters
// no names will be generated if the prefix failed parametername validation
for (int i = 0; i < schemaRows.Length; i++)
{
if (null != _baseParameterNames[i])
{
if (null != _originalPrefix)
{
_originalParameterNames[i] = _originalPrefix + _baseParameterNames[i];
}
if (null != _isNullPrefix)
{
// don't bother generating an 'IsNull' name if it's not used
if (schemaRows[i]!.AllowDBNull)
{
_nullParameterNames[i] = _isNullPrefix + _baseParameterNames[i];
}
}
}
}
ApplyProviderSpecificFormat();
GenerateMissingNames(schemaRows);
}
private void SetAndValidateNamePrefixes()
{
if (_parameterNameParser.IsMatch(DefaultIsNullPrefix))
{
_isNullPrefix = DefaultIsNullPrefix;
}
else if (_parameterNameParser.IsMatch(AlternativeIsNullPrefix))
{
_isNullPrefix = AlternativeIsNullPrefix;
}
else if (_parameterNameParser.IsMatch(AlternativeIsNullPrefix2))
{
_isNullPrefix = AlternativeIsNullPrefix2;
}
else
{
_isNullPrefix = null;
}
if (_parameterNameParser.IsMatch(DefaultOriginalPrefix))
{
_originalPrefix = DefaultOriginalPrefix;
}
else if (_parameterNameParser.IsMatch(AlternativeOriginalPrefix))
{
_originalPrefix = AlternativeOriginalPrefix;
}
else if (_parameterNameParser.IsMatch(AlternativeOriginalPrefix2))
{
_originalPrefix = AlternativeOriginalPrefix2;
}
else
{
_originalPrefix = null;
}
}
private void ApplyProviderSpecificFormat()
{
for (int i = 0; i < _baseParameterNames.Length; i++)
{
if (_baseParameterNames[i] is string baseParameterName)
{
_baseParameterNames[i] = _dbCommandBuilder.GetParameterName(baseParameterName);
}
if (_originalParameterNames[i] is string originalParameterName)
{
_originalParameterNames[i] = _dbCommandBuilder.GetParameterName(originalParameterName);
}
if (_nullParameterNames[i] is string nullParameterName)
{
_nullParameterNames[i] = _dbCommandBuilder.GetParameterName(nullParameterName);
}
}
}
private void EliminateConflictingNames()
{
for (int i = 0; i < _count - 1; i++)
{
string? name = _baseParameterNames[i];
if (null != name)
{
for (int j = i + 1; j < _count; j++)
{
if (ADP.CompareInsensitiveInvariant(name, _baseParameterNames[j]))
{
// found duplicate name
// the name unchanged name wins
int iMutatedName = _isMutatedName[j] ? j : i;
Debug.Assert(_isMutatedName[iMutatedName], $"{_baseParameterNames[iMutatedName]} expected to be a mutated name");
_baseParameterNames[iMutatedName] = null; // null out the culprit
}
}
}
}
}
// Generates parameternames that couldn't be generated from columnname
internal void GenerateMissingNames(DbSchemaRow?[] schemaRows)
{
// foreach name in base names
// if base name is null
// for base, original and nullnames (null names only if nullable)
// do
// generate name based on current index
// increment index
// search name in base names
// loop while name occurs in base names
// end for
// end foreach
string? name;
for (int i = 0; i < _baseParameterNames.Length; i++)
{
name = _baseParameterNames[i];
if (null == name)
{
_baseParameterNames[i] = GetNextGenericParameterName();
_originalParameterNames[i] = GetNextGenericParameterName();
// don't bother generating an 'IsNull' name if it's not used
if (schemaRows[i] is DbSchemaRow schemaRow && schemaRow.AllowDBNull)
{
_nullParameterNames[i] = GetNextGenericParameterName();
}
}
}
}
private int GetAdjustedParameterNameMaxLength()
{
int maxPrefixLength = Math.Max(
(null != _isNullPrefix ? _isNullPrefix.Length : 0),
(null != _originalPrefix ? _originalPrefix.Length : 0)
) + _dbCommandBuilder.GetParameterName("").Length;
return _dbCommandBuilder.ParameterNameMaxLength - maxPrefixLength;
}
private string GetNextGenericParameterName()
{
string name;
bool nameExist;
do
{
nameExist = false;
_genericParameterCount++;
name = _dbCommandBuilder.GetParameterName(_genericParameterCount);
for (int i = 0; i < _baseParameterNames.Length; i++)
{
if (ADP.CompareInsensitiveInvariant(_baseParameterNames[i], name))
{
nameExist = true;
break;
}
}
} while (nameExist);
return name;
}
internal string? GetBaseParameterName(int index)
{
return (_baseParameterNames[index]);
}
internal string? GetOriginalParameterName(int index)
{
return (_originalParameterNames[index]);
}
internal string? GetNullParameterName(int index)
{
return (_nullParameterNames[index]);
}
}
private const string DeleteFrom = "DELETE FROM ";
private const string InsertInto = "INSERT INTO ";
private const string DefaultValues = " DEFAULT VALUES";
private const string Values = " VALUES ";
private const string Update = "UPDATE ";
private const string Set = " SET ";
private const string Where = " WHERE ";
private const string SpaceLeftParenthesis = " (";
private const string Comma = ", ";
private const string Equal = " = ";
private const char LeftParenthesis = '(';
private const char RightParenthesis = ')';
private const string NameSeparator = ".";
private const string IsNull = " IS NULL";
private const string EqualOne = " = 1";
private const string And = " AND ";
private const string Or = " OR ";
private DbDataAdapter? _dataAdapter;
private DbCommand? _insertCommand;
private DbCommand? _updateCommand;
private DbCommand? _deleteCommand;
private MissingMappingAction _missingMappingAction;
private ConflictOption _conflictDetection = ConflictOption.CompareAllSearchableValues;
private bool _setAllValues;
private bool _hasPartialPrimaryKey;
private DataTable? _dbSchemaTable;
private DbSchemaRow?[]? _dbSchemaRows;
private string[]? _sourceColumnNames;
private ParameterNames? _parameterNames;
private string? _quotedBaseTableName;
// quote strings to use around SQL object names
private CatalogLocation _catalogLocation = CatalogLocation.Start;
private string? _catalogSeparator = NameSeparator;
private string? _schemaSeparator = NameSeparator;
private string? _quotePrefix = string.Empty;
private string? _quoteSuffix = string.Empty;
private string? _parameterNamePattern;
private string? _parameterMarkerFormat;
private int _parameterNameMaxLength;
protected DbCommandBuilder() : base()
{
}
[DefaultValueAttribute(ConflictOption.CompareAllSearchableValues)]
public virtual ConflictOption ConflictOption
{
get
{
return _conflictDetection;
}
set
{
switch (value)
{
case ConflictOption.CompareAllSearchableValues:
case ConflictOption.CompareRowVersion:
case ConflictOption.OverwriteChanges:
_conflictDetection = value;
break;
default:
throw ADP.InvalidConflictOptions(value);
}
}
}
[DefaultValueAttribute(CatalogLocation.Start)]
public virtual CatalogLocation CatalogLocation
{
get
{
return _catalogLocation;
}
set
{
if (null != _dbSchemaTable)
{
throw ADP.NoQuoteChange();
}
switch (value)
{
case CatalogLocation.Start:
case CatalogLocation.End:
_catalogLocation = value;
break;
default:
throw ADP.InvalidCatalogLocation(value);
}
}
}
[DefaultValueAttribute(DbCommandBuilder.NameSeparator)]
[AllowNull]
public virtual string CatalogSeparator
{
get
{
string? catalogSeparator = _catalogSeparator;
return (((null != catalogSeparator) && (0 < catalogSeparator.Length)) ? catalogSeparator : NameSeparator);
}
set
{
if (null != _dbSchemaTable)
{
throw ADP.NoQuoteChange();
}
_catalogSeparator = value;
}
}
[Browsable(false)]
[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
public DbDataAdapter? DataAdapter
{
get
{
return _dataAdapter;
}
set
{
if (_dataAdapter != value)
{
RefreshSchema();
if (null != _dataAdapter)
{
// derived should remove event handler from old adapter
SetRowUpdatingHandler(_dataAdapter);
_dataAdapter = null;
}
if (null != value)
{
// derived should add event handler to new adapter
SetRowUpdatingHandler(value);
_dataAdapter = value;
}
}
}
}
internal int ParameterNameMaxLength
{
get
{
return _parameterNameMaxLength;
}
}
internal string? ParameterNamePattern
{
get
{
return _parameterNamePattern;
}
}
private string? QuotedBaseTableName
{
get
{
return _quotedBaseTableName;
}
}
[DefaultValueAttribute("")]
[AllowNull]
public virtual string QuotePrefix
{
get { return _quotePrefix ?? string.Empty; }
set
{
if (null != _dbSchemaTable)
{
throw ADP.NoQuoteChange();
}
_quotePrefix = value;
}
}
[DefaultValueAttribute("")]
[AllowNull]
public virtual string QuoteSuffix
{
get
{
return (_quoteSuffix ?? string.Empty);
}
set
{
if (null != _dbSchemaTable)
{
throw ADP.NoQuoteChange();
}
_quoteSuffix = value;
}
}
[DefaultValueAttribute(DbCommandBuilder.NameSeparator)]
[AllowNull]
public virtual string SchemaSeparator
{
get
{
string? schemaSeparator = _schemaSeparator;
return (((null != schemaSeparator) && (0 < schemaSeparator.Length)) ? schemaSeparator : NameSeparator);
}
set
{
if (null != _dbSchemaTable)
{
throw ADP.NoQuoteChange();
}
_schemaSeparator = value;
}
}
[DefaultValueAttribute(false)]
public bool SetAllValues
{
get
{
return _setAllValues;
}
set
{
_setAllValues = value;
}
}
private DbCommand? InsertCommand
{
get
{
return _insertCommand;
}
set
{
_insertCommand = value;
}
}
private DbCommand? UpdateCommand
{
get
{
return _updateCommand;
}
set
{
_updateCommand = value;
}
}
private DbCommand? DeleteCommand
{
get
{
return _deleteCommand;
}
set
{
_deleteCommand = value;
}
}
private void BuildCache(bool closeConnection, DataRow? dataRow, bool useColumnsForParameterNames)
{
// Don't bother building the cache if it's done already; wait for
// the user to call RefreshSchema first.
if ((null != _dbSchemaTable) && (!useColumnsForParameterNames || (null != _parameterNames)))
{
return;
}
DataTable? schemaTable = null;
DbCommand srcCommand = GetSelectCommand();
DbConnection? connection = srcCommand.Connection;
if (null == connection)
{
throw ADP.MissingSourceCommandConnection();
}
try
{
if (0 == (ConnectionState.Open & connection.State))
{
connection.Open();
}
else
{
closeConnection = false;
}
if (useColumnsForParameterNames)
{
DataTable dataTable = connection.GetSchema(DbMetaDataCollectionNames.DataSourceInformation);
if (dataTable.Rows.Count == 1)
{
_parameterNamePattern = dataTable.Rows[0][DbMetaDataColumnNames.ParameterNamePattern] as string;
_parameterMarkerFormat = dataTable.Rows[0][DbMetaDataColumnNames.ParameterMarkerFormat] as string;
object oParameterNameMaxLength = dataTable.Rows[0][DbMetaDataColumnNames.ParameterNameMaxLength];
_parameterNameMaxLength = (oParameterNameMaxLength is int) ? (int)oParameterNameMaxLength : 0;
// note that we protect against errors in the xml file!
if (0 == _parameterNameMaxLength || null == _parameterNamePattern || null == _parameterMarkerFormat)
{
useColumnsForParameterNames = false;
}
}
else
{
Debug.Fail("Rowcount expected to be 1");
useColumnsForParameterNames = false;
}
}
schemaTable = GetSchemaTable(srcCommand);
}
finally
{
if (closeConnection)
{
connection.Close();
}
}
if (null == schemaTable)
{
throw ADP.DynamicSQLNoTableInfo();
}
BuildInformation(schemaTable);
_dbSchemaTable = schemaTable;
DbSchemaRow?[] schemaRows = _dbSchemaRows!;
string[] srcColumnNames = new string[schemaRows.Length];
for (int i = 0; i < schemaRows.Length; ++i)
{
if (schemaRows[i] is DbSchemaRow schemaRow)
{
srcColumnNames[i] = schemaRow.ColumnName;
}
}
_sourceColumnNames = srcColumnNames;
if (useColumnsForParameterNames)
{
_parameterNames = new ParameterNames(this, schemaRows);
}
ADP.BuildSchemaTableInfoTableNames(srcColumnNames);
}
protected virtual DataTable? GetSchemaTable(DbCommand sourceCommand)
{
using (IDataReader dataReader = sourceCommand.ExecuteReader(CommandBehavior.SchemaOnly | CommandBehavior.KeyInfo))
{
return dataReader.GetSchemaTable();
}
}
private void BuildInformation(DataTable schemaTable)
{
DbSchemaRow?[]? rows = DbSchemaRow.GetSortedSchemaRows(schemaTable, false);
if ((null == rows) || (0 == rows.Length))
{
throw ADP.DynamicSQLNoTableInfo();
}
string? baseServerName = string.Empty;
string? baseCatalogName = string.Empty;
string? baseSchemaName = string.Empty;
string? baseTableName = null;
for (int i = 0; i < rows.Length; ++i)
{
DbSchemaRow row = rows[i]!;
string tableName = row.BaseTableName;
if ((null == tableName) || (0 == tableName.Length))
{
rows[i] = null;
continue;
}
string serverName = row.BaseServerName;
string catalogName = row.BaseCatalogName;
string schemaName = row.BaseSchemaName;
if (null == serverName)
{
serverName = string.Empty;
}
if (null == catalogName)
{
catalogName = string.Empty;
}
if (null == schemaName)
{
schemaName = string.Empty;
}
if (null == baseTableName)
{
baseServerName = serverName;
baseCatalogName = catalogName;
baseSchemaName = schemaName;
baseTableName = tableName;
}
else if ((0 != ADP.SrcCompare(baseTableName, tableName))
|| (0 != ADP.SrcCompare(baseSchemaName, schemaName))
|| (0 != ADP.SrcCompare(baseCatalogName, catalogName))
|| (0 != ADP.SrcCompare(baseServerName, serverName)))
{
throw ADP.DynamicSQLJoinUnsupported();
}
}
if (0 == baseServerName.Length)
{
baseServerName = null;
}
if (0 == baseCatalogName.Length)
{
baseServerName = null;
baseCatalogName = null;
}
if (0 == baseSchemaName.Length)
{
baseServerName = null;
baseCatalogName = null;
baseSchemaName = null;
}
if ((null == baseTableName) || (0 == baseTableName.Length))
{
throw ADP.DynamicSQLNoTableInfo();
}
CatalogLocation location = CatalogLocation;
string catalogSeparator = CatalogSeparator;
string schemaSeparator = SchemaSeparator;
string quotePrefix = QuotePrefix;
string quoteSuffix = QuoteSuffix;
if (!string.IsNullOrEmpty(quotePrefix) && (-1 != baseTableName.IndexOf(quotePrefix, StringComparison.Ordinal)))
{
throw ADP.DynamicSQLNestedQuote(baseTableName, quotePrefix);
}
if (!string.IsNullOrEmpty(quoteSuffix) && (-1 != baseTableName.IndexOf(quoteSuffix, StringComparison.Ordinal)))
{
throw ADP.DynamicSQLNestedQuote(baseTableName, quoteSuffix);
}
System.Text.StringBuilder builder = new System.Text.StringBuilder();
if (CatalogLocation.Start == location)
{
if (null != baseServerName)
{
builder.Append(ADP.BuildQuotedString(quotePrefix, quoteSuffix, baseServerName));
builder.Append(catalogSeparator);
}
if (null != baseCatalogName)
{
builder.Append(ADP.BuildQuotedString(quotePrefix, quoteSuffix, baseCatalogName));
builder.Append(catalogSeparator);
}
}
if (null != baseSchemaName)
{
builder.Append(ADP.BuildQuotedString(quotePrefix, quoteSuffix, baseSchemaName));
builder.Append(schemaSeparator);
}
builder.Append(ADP.BuildQuotedString(quotePrefix, quoteSuffix, baseTableName));
if (CatalogLocation.End == location)
{
if (null != baseServerName)
{
builder.Append(catalogSeparator);
builder.Append(ADP.BuildQuotedString(quotePrefix, quoteSuffix, baseServerName));
}
if (null != baseCatalogName)
{
builder.Append(catalogSeparator);
builder.Append(ADP.BuildQuotedString(quotePrefix, quoteSuffix, baseCatalogName));
}
}
_quotedBaseTableName = builder.ToString();
_hasPartialPrimaryKey = false;
foreach (DbSchemaRow? row in rows)
{
if ((null != row) && (row.IsKey || row.IsUnique) && !row.IsLong && !row.IsRowVersion && row.IsHidden)
{
_hasPartialPrimaryKey = true;
break;
}
}
_dbSchemaRows = rows;
}
private DbCommand BuildDeleteCommand(DataTableMapping? mappings, DataRow? dataRow)
{
DbCommand command = InitializeCommand(DeleteCommand);
StringBuilder builder = new StringBuilder();
int parameterCount = 0;
Debug.Assert(!string.IsNullOrEmpty(_quotedBaseTableName), "no table name");
builder.Append(DeleteFrom);
builder.Append(QuotedBaseTableName);
parameterCount = BuildWhereClause(mappings, dataRow, builder, command, parameterCount, false);
command.CommandText = builder.ToString();
RemoveExtraParameters(command, parameterCount);
DeleteCommand = command;
return command;
}
private DbCommand BuildInsertCommand(DataTableMapping? mappings, DataRow? dataRow)
{
DbCommand command = InitializeCommand(InsertCommand);
StringBuilder builder = new StringBuilder();
int parameterCount = 0;
string nextSeparator = SpaceLeftParenthesis;
Debug.Assert(!string.IsNullOrEmpty(_quotedBaseTableName), "no table name");
builder.Append(InsertInto);
builder.Append(QuotedBaseTableName);
// search for the columns in that base table, to be the column clause
DbSchemaRow[] schemaRows = _dbSchemaRows!;
string[] parameterName = new string[schemaRows.Length];
for (int i = 0; i < schemaRows.Length; ++i)
{
DbSchemaRow row = schemaRows[i];
if ((null == row) || (0 == row.BaseColumnName.Length) || !IncludeInInsertValues(row))
continue;
object? currentValue = null;
string sourceColumn = _sourceColumnNames![i];
// If we're building a statement for a specific row, then check the
// values to see whether the column should be included in the insert
// statement or not
if ((null != mappings) && (null != dataRow))
{
DataColumn? dataColumn = GetDataColumn(sourceColumn, mappings, dataRow);
if (null == dataColumn)
continue;
// Don't bother inserting if the column is readonly in both the data
// set and the back end.
if (row.IsReadOnly && dataColumn.ReadOnly)
continue;
currentValue = GetColumnValue(dataRow, dataColumn, DataRowVersion.Current);
// If the value is null, and the column doesn't support nulls, then
// the user is requesting the server-specified default value, so don't
// include it in the set-list.
if (!row.AllowDBNull && (null == currentValue || Convert.IsDBNull(currentValue)))
continue;
}
builder.Append(nextSeparator);
nextSeparator = Comma;
builder.Append(QuotedColumn(row.BaseColumnName));
parameterName[parameterCount] = CreateParameterForValue(
command,
GetBaseParameterName(i),
sourceColumn,
DataRowVersion.Current,
parameterCount,
currentValue,
row, StatementType.Insert, false
);
parameterCount++;
}
if (0 == parameterCount)
builder.Append(DefaultValues);
else
{
builder.Append(RightParenthesis);
builder.Append(Values);
builder.Append(LeftParenthesis);
builder.Append(parameterName[0]);
for (int i = 1; i < parameterCount; ++i)
{
builder.Append(Comma);
builder.Append(parameterName[i]);
}
builder.Append(RightParenthesis);
}
command.CommandText = builder.ToString();
RemoveExtraParameters(command, parameterCount);
InsertCommand = command;
return command;
}
private DbCommand? BuildUpdateCommand(DataTableMapping? mappings, DataRow? dataRow)
{
DbCommand command = InitializeCommand(UpdateCommand);
StringBuilder builder = new StringBuilder();
string nextSeparator = Set;
int parameterCount = 0;
Debug.Assert(!string.IsNullOrEmpty(_quotedBaseTableName), "no table name");
builder.Append(Update);
builder.Append(QuotedBaseTableName);
// search for the columns in that base table, to build the set clause
DbSchemaRow[] schemaRows = _dbSchemaRows!;
for (int i = 0; i < schemaRows.Length; ++i)
{
DbSchemaRow row = schemaRows[i];
if ((null == row) || (0 == row.BaseColumnName.Length) || !IncludeInUpdateSet(row))
continue;
object? currentValue = null;
string sourceColumn = _sourceColumnNames![i];
// If we're building a statement for a specific row, then check the
// values to see whether the column should be included in the update
// statement or not
if ((null != mappings) && (null != dataRow))
{
DataColumn? dataColumn = GetDataColumn(sourceColumn, mappings, dataRow);
if (null == dataColumn)
continue;
// Don't bother updating if the column is readonly in both the data
// set and the back end.
if (row.IsReadOnly && dataColumn.ReadOnly)
continue;
// Unless specifically directed to do so, we will not automatically update
// a column with it's original value, which means that we must determine
// whether the value has changed locally, before we send it up.
currentValue = GetColumnValue(dataRow, dataColumn, DataRowVersion.Current);
if (!SetAllValues)
{
object originalValue = GetColumnValue(dataRow, dataColumn, DataRowVersion.Original);
if ((originalValue == currentValue)
|| ((null != originalValue) && originalValue.Equals(currentValue)))
{
continue;
}
}
}
builder.Append(nextSeparator);
nextSeparator = Comma;
builder.Append(QuotedColumn(row.BaseColumnName));
builder.Append(Equal);
builder.Append(
CreateParameterForValue(
command,
GetBaseParameterName(i),
sourceColumn,
DataRowVersion.Current,
parameterCount,
currentValue,
row, StatementType.Update, false
)
);
parameterCount++;
}
// It is an error to attempt an update when there's nothing to update;
bool skipRow = (0 == parameterCount);
parameterCount = BuildWhereClause(mappings, dataRow, builder, command, parameterCount, true);
command.CommandText = builder.ToString();
RemoveExtraParameters(command, parameterCount);
UpdateCommand = command;
return (skipRow) ? null : command;
}
private int BuildWhereClause(
DataTableMapping? mappings,
DataRow? dataRow,
StringBuilder builder,
DbCommand command,
int parameterCount,
bool isUpdate
)
{
string beginNewCondition = string.Empty;