-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDbContext.cs
More file actions
1747 lines (1561 loc) · 73.7 KB
/
DbContext.cs
File metadata and controls
1747 lines (1561 loc) · 73.7 KB
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
using SqlSugar;
using System.Text.RegularExpressions;
using System.IO;
namespace DbCli;
public enum DatabaseType
{
SQLite,
SqlServer,
MySQL,
PostgreSQL,
Oracle,
Dm, // 达梦
MongoDB, // MongoDB
Kdbndp, // 人大金仓 (KingbaseES)
Oscar, // 神通 (Oscar)
HighGo, // 瀚高 (HighGo)
Access, // Access
DB2, // IBM DB2
DuckDb, // DuckDB
Hana, // SAP HANA
OceanBase, // OceanBase
PolarDB, // PolarDB (MySQL-compatible)
TDengine, // TDengine
QuestDb, // QuestDB
ClickHouse, // ClickHouse
Doris, // Doris
MySqlConnector, // MySqlConnector
GaussDB, // GaussDB
GBase, // GBase
MariaDB, // MariaDB
TiDB, // TiDB
Odbc, // ODBC
Custom // Custom
}
public class DbConfig
{
public string ConnectionString { get; set; } = string.Empty;
public DatabaseType DbType { get; set; } = DatabaseType.SQLite;
public bool DisableNvarchar { get; set; }
public bool DisableClearParameters { get; set; }
}
public class DbContext : IDisposable
{
private readonly SqlSugarClient _db;
public SqlSugarClient Db => _db;
public DbContext(DbConfig config)
{
_db = new SqlSugarClient(new ConnectionConfig
{
ConnectionString = config.ConnectionString,
DbType = ConvertDbType(config.DbType),
IsAutoCloseConnection = true,
InitKeyType = InitKeyType.Attribute,
MoreSettings = config.DisableNvarchar ? new ConnMoreSettings { DisableNvarchar = true } : null
});
ApplyClearParametersSetting(config.DisableClearParameters);
}
public DbContext(string connectionString, DatabaseType dbType)
: this(new DbConfig { ConnectionString = connectionString, DbType = dbType })
{
}
private static SqlSugar.DbType ConvertDbType(DatabaseType type) => type switch
{
DatabaseType.SQLite => SqlSugar.DbType.Sqlite,
DatabaseType.SqlServer => SqlSugar.DbType.SqlServer,
DatabaseType.MySQL => SqlSugar.DbType.MySql,
DatabaseType.PostgreSQL => SqlSugar.DbType.PostgreSQL,
DatabaseType.Oracle => SqlSugar.DbType.Oracle,
DatabaseType.Dm => SqlSugar.DbType.Dm,
DatabaseType.MongoDB => SqlSugar.DbType.MongoDb,
DatabaseType.Kdbndp => SqlSugar.DbType.Kdbndp,
DatabaseType.Oscar => SqlSugar.DbType.Oscar,
DatabaseType.HighGo => SqlSugar.DbType.HG,
DatabaseType.Access => SqlSugar.DbType.Access,
DatabaseType.DB2 => SqlSugar.DbType.DB2,
DatabaseType.DuckDb => SqlSugar.DbType.DuckDB,
DatabaseType.Hana => SqlSugar.DbType.HANA,
DatabaseType.OceanBase => SqlSugar.DbType.OceanBase,
DatabaseType.PolarDB => SqlSugar.DbType.PolarDB,
DatabaseType.TDengine => SqlSugar.DbType.TDengine,
DatabaseType.QuestDb => SqlSugar.DbType.QuestDB,
DatabaseType.ClickHouse => SqlSugar.DbType.ClickHouse,
DatabaseType.Doris => SqlSugar.DbType.Doris,
DatabaseType.MySqlConnector => SqlSugar.DbType.MySqlConnector,
DatabaseType.GaussDB => SqlSugar.DbType.GaussDB,
DatabaseType.GBase => SqlSugar.DbType.GBase,
DatabaseType.MariaDB => SqlSugar.DbType.MySql,
DatabaseType.TiDB => SqlSugar.DbType.MySql,
DatabaseType.Odbc => SqlSugar.DbType.Odbc,
DatabaseType.Custom => SqlSugar.DbType.Custom,
_ => SqlSugar.DbType.Sqlite
};
public static DatabaseType ParseDbType(string type)
{
return type.ToLower() switch
{
"sqlite" => DatabaseType.SQLite,
"sqlserver" or "mssql" => DatabaseType.SqlServer,
"mysql" => DatabaseType.MySQL,
// MySQL-compatible variants
"mariadb" => DatabaseType.MariaDB,
"tidb" => DatabaseType.TiDB,
"percona" or "perconaserver" or "percona-server" => DatabaseType.MySQL,
"aurora" or "amazon-aurora" or "amazonaurora" => DatabaseType.MySQL,
"azure-mysql" or "azuremysql" or "azure database for mysql" => DatabaseType.MySQL,
"gcloud-mysql" or "google-cloud-sql" or "google cloud sql" or "google cloud sql for mysql" => DatabaseType.MySQL,
"postgresql" or "postgres" or "pgsql" => DatabaseType.PostgreSQL,
"oracle" => DatabaseType.Oracle,
"dm" or "dameng" => DatabaseType.Dm,
"mongodb" or "mongo" => DatabaseType.MongoDB,
"kdbndp" or "kingbase" or "kingbasees" => DatabaseType.Kdbndp,
"oscar" or "shentong" => DatabaseType.Oscar,
"highgo" or "hg" => DatabaseType.HighGo,
"access" => DatabaseType.Access,
"db2" => DatabaseType.DB2,
"duckdb" or "duck" => DatabaseType.DuckDb,
"hana" => DatabaseType.Hana,
"oceanbase" => DatabaseType.OceanBase,
"polardb" => DatabaseType.PolarDB,
"tdengine" or "td" => DatabaseType.TDengine,
"questdb" or "quest" => DatabaseType.QuestDb,
"clickhouse" => DatabaseType.ClickHouse,
"doris" => DatabaseType.Doris,
"mysqlconnector" => DatabaseType.MySqlConnector,
"gaussdb" or "gauss" => DatabaseType.GaussDB,
"gbase" => DatabaseType.GBase,
"odbc" => DatabaseType.Odbc,
"custom" => DatabaseType.Custom,
_ => throw new ArgumentException($"Unknown database type: {type}")
};
}
public List<Dictionary<string, object>> Query(string sql)
{
var dt = _db.Ado.GetDataTable(sql);
var result = new List<Dictionary<string, object>>();
foreach (System.Data.DataRow row in dt.Rows)
{
var dict = new Dictionary<string, object>();
foreach (System.Data.DataColumn col in dt.Columns)
{
dict[col.ColumnName] = row[col] == DBNull.Value ? null! : row[col];
}
result.Add(dict);
}
return result;
}
public List<Dictionary<string, object>> Query(string sql, object? parameters)
{
var prepared = PrepareSqlParameters(sql, parameters);
var dt = prepared.Parameters == null
? _db.Ado.GetDataTable(sql)
: _db.Ado.GetDataTable(prepared.Sql, prepared.Parameters);
var result = new List<Dictionary<string, object>>();
foreach (System.Data.DataRow row in dt.Rows)
{
var dict = new Dictionary<string, object>();
foreach (System.Data.DataColumn col in dt.Columns)
{
dict[col.ColumnName] = row[col] == DBNull.Value ? null! : row[col];
}
result.Add(dict);
}
return result;
}
public int Execute(string sql)
{
return _db.Ado.ExecuteCommand(sql);
}
public int Execute(string sql, object? parameters)
{
var prepared = PrepareSqlParameters(sql, parameters);
return prepared.Parameters == null
? _db.Ado.ExecuteCommand(sql)
: _db.Ado.ExecuteCommand(prepared.Sql, prepared.Parameters);
}
public int ExecuteWithGo(string sql)
{
if (string.IsNullOrWhiteSpace(sql)) return 0;
var batches = Regex.Split(
sql,
@"^\s*GO\s*;?\s*$",
RegexOptions.Multiline | RegexOptions.IgnoreCase);
var affected = 0;
foreach (var batch in batches)
{
var text = batch.Trim();
if (text.Length == 0) continue;
affected += _db.Ado.ExecuteCommand(text);
}
return affected;
}
private sealed record PreparedSql(string Sql, object? Parameters);
private static PreparedSql PrepareSqlParameters(string sql, object? parameters)
{
if (parameters is not IDictionary<string, object?> dict)
return new PreparedSql(sql, parameters);
if (!ContainsArrayParameter(dict))
return new PreparedSql(sql, parameters);
var lookup = new Dictionary<string, KeyValuePair<string, object?>>(StringComparer.OrdinalIgnoreCase);
foreach (var kvp in dict)
{
lookup[kvp.Key] = kvp;
}
var expandedParams = new Dictionary<string, object?>(StringComparer.OrdinalIgnoreCase);
foreach (var kvp in dict)
{
if (!IsArrayParameter(kvp.Value, out _))
expandedParams[kvp.Key] = kvp.Value;
}
var sb = new System.Text.StringBuilder(sql.Length + 32);
var inString = false;
for (var i = 0; i < sql.Length; i++)
{
var ch = sql[i];
if (ch == '\'')
{
sb.Append(ch);
if (inString && i + 1 < sql.Length && sql[i + 1] == '\'')
{
sb.Append(sql[++i]);
}
else
{
inString = !inString;
}
continue;
}
if (!inString && ch == '@')
{
var start = i + 1;
if (start < sql.Length && IsIdentifierStart(sql[start]))
{
var end = start + 1;
while (end < sql.Length && IsIdentifierPart(sql[end]))
end++;
var name = sql[start..end];
if (lookup.TryGetValue(name, out var kvp) && IsArrayParameter(kvp.Value, out var items))
{
if (items.Count == 0)
{
sb.Append("NULL");
}
else
{
for (var idx = 0; idx < items.Count; idx++)
{
if (idx > 0)
sb.Append(", ");
var paramName = $"{name}_{idx}";
sb.Append('@').Append(paramName);
expandedParams[paramName] = items[idx];
}
}
i = end - 1;
continue;
}
}
}
sb.Append(ch);
}
return new PreparedSql(sb.ToString(), expandedParams);
}
private static bool ContainsArrayParameter(IDictionary<string, object?> parameters)
{
foreach (var kvp in parameters)
{
if (IsArrayParameter(kvp.Value, out _))
return true;
}
return false;
}
private static bool IsArrayParameter(object? value, out List<object?> items)
{
items = new List<object?>();
if (value is null)
return false;
if (value is string or byte[])
return false;
if (value is System.Collections.IDictionary)
return false;
if (value is System.Collections.IEnumerable enumerable)
{
foreach (var item in enumerable)
items.Add(item);
return true;
}
return false;
}
private static bool IsIdentifierStart(char ch)
{
return char.IsLetter(ch) || ch == '_';
}
private static bool IsIdentifierPart(char ch)
{
return char.IsLetterOrDigit(ch) || ch == '_';
}
public List<Dictionary<string, object>> QueryStoredProcedure(string name, object? parameters)
{
var ado = _db.Ado.UseStoredProcedure();
var dt = parameters == null
? ado.GetDataTable(name)
: ado.GetDataTable(name, parameters);
var result = new List<Dictionary<string, object>>();
foreach (System.Data.DataRow row in dt.Rows)
{
var dict = new Dictionary<string, object>();
foreach (System.Data.DataColumn col in dt.Columns)
{
dict[col.ColumnName] = row[col] == DBNull.Value ? null! : row[col];
}
result.Add(dict);
}
return result;
}
public int ExecuteStoredProcedure(string name, object? parameters)
{
var ado = _db.Ado.UseStoredProcedure();
return parameters == null
? ado.ExecuteCommand(name)
: ado.ExecuteCommand(name, parameters);
}
public bool SupportsParameters()
{
var dbType = _db.CurrentConnectionConfig.DbType;
return dbType != SqlSugar.DbType.MongoDb && dbType != SqlSugar.DbType.Custom;
}
public bool SupportsGoBatches()
{
return _db.CurrentConnectionConfig.DbType == SqlSugar.DbType.SqlServer;
}
private void ApplyClearParametersSetting(bool disableClearParameters)
{
if (!disableClearParameters) return;
// Some providers (notably SQLite) may require IsClearParameters=false.
var config = _db.CurrentConnectionConfig;
var prop = config.GetType().GetProperty("IsClearParameters");
if (prop != null && prop.CanWrite)
{
prop.SetValue(config, false);
}
var adoProp = _db.Ado.GetType().GetProperty("IsClearParameters");
if (adoProp != null && adoProp.CanWrite)
{
adoProp.SetValue(_db.Ado, false);
}
}
public void ExecuteDdl(string sql)
{
if (string.IsNullOrWhiteSpace(sql)) return;
// Many SQL Server scripts (including export-schema output) use the batch separator "GO".
// ADO providers don't understand GO, so we split and execute batch-by-batch.
// Split only on standalone lines containing GO (case-insensitive).
var batches = Regex.Split(
sql,
@"^\s*GO\s*;?\s*$",
RegexOptions.Multiline | RegexOptions.IgnoreCase);
foreach (var batch in batches)
{
var text = batch.Trim();
if (text.Length == 0) continue;
_db.Ado.ExecuteCommand(text);
}
}
public List<string> GetTables()
{
var tables = _db.DbMaintenance.GetTableInfoList();
return tables.Select(t => t.Name).ToList();
}
public List<Dictionary<string, object>> GetTableColumns(string tableName)
{
var columns = _db.DbMaintenance.GetColumnInfosByTableName(tableName);
return columns.Select(c => new Dictionary<string, object>
{
["ColumnName"] = c.DbColumnName,
["DataType"] = c.DataType,
["Length"] = c.Length,
["IsNullable"] = c.IsNullable,
["IsPrimaryKey"] = c.IsPrimarykey,
["DefaultValue"] = c.DefaultValue ?? ""
}).ToList();
}
public string ExportTableData(string tableName, string format = "insert")
{
var data = _db.Queryable<dynamic>().AS(tableName).ToList();
if (data.Count == 0) return string.Empty;
var columns = _db.DbMaintenance.GetColumnInfosByTableName(tableName);
var columnNames = columns.Select(c => c.DbColumnName).ToList();
var sb = new System.Text.StringBuilder();
foreach (var row in data)
{
var dict = (IDictionary<string, object>)row;
var values = columnNames.Select(col =>
{
var val = dict.ContainsKey(col) ? dict[col] : null;
if (val == null) return "NULL";
if (val is string s) return $"'{s.Replace("'", "''")}'";
if (val is DateTime dt) return $"'{dt:yyyy-MM-dd HH:mm:ss}'";
if (val is bool b) return b ? "1" : "0";
return val.ToString();
});
sb.AppendLine($"INSERT INTO {tableName} ({string.Join(", ", columnNames)}) VALUES ({string.Join(", ", values)});");
}
return sb.ToString();
}
/// <summary>
/// Backup table using SqlSugar Fastest bulk operations (preferred) or fallback to SQL
/// </summary>
public (bool Success, string Method, int RowCount, string Message) BackupTable(string tableName, string backupTableName)
{
try
{
var currentDbType = _db.CurrentConnectionConfig.DbType;
// Check if table exists
var tables = GetTables();
if (!tables.Any(t => t.Equals(tableName, StringComparison.OrdinalIgnoreCase)))
{
return (false, "None", 0, $"Table '{tableName}' does not exist");
}
// SQL Server: use SELECT INTO (CREATE TABLE AS SELECT is not supported).
// This also avoids identity-insert issues for backup creation.
if (currentDbType == SqlSugar.DbType.SqlServer)
{
try
{
_db.Ado.ExecuteCommand($"DROP TABLE IF EXISTS {backupTableName}");
}
catch
{
// ignore
}
try
{
_db.Ado.ExecuteCommand($"SELECT * INTO {backupTableName} FROM {tableName}");
var count = _db.Ado.GetInt($"SELECT COUNT(*) FROM {backupTableName}");
return (true, "SelectInto", count, "Backup created using SQL Server SELECT INTO");
}
catch (Exception ex)
{
return (false, "SelectInto", 0, $"SQL Server backup failed: {ex.Message}");
}
}
// Method 1: Try CREATE TABLE AS SELECT + INSERT INTO SELECT (fast and compatible)
try
{
// Create backup table with data in one step
var rowCount = _db.Ado.ExecuteCommand($"CREATE TABLE {backupTableName} AS SELECT * FROM {tableName}");
var count = _db.Ado.GetInt($"SELECT COUNT(*) FROM {backupTableName}");
return (true, "CreateTableAsSelect", count, "Backup created using CREATE TABLE AS SELECT (fast & compatible)");
}
catch (Exception createEx)
{
// Method 2: Fallback to DataTable + BulkCopy (for databases not supporting CREATE AS SELECT)
try
{
// Drop backup table if partially created
try { _db.Ado.ExecuteCommand($"DROP TABLE IF EXISTS {backupTableName}"); } catch { }
// Get table structure
var columns = _db.DbMaintenance.GetColumnInfosByTableName(tableName);
// Create empty backup table
_db.Ado.ExecuteCommand($"CREATE TABLE {backupTableName} AS SELECT * FROM {tableName} WHERE 1=0");
// Get data as DataTable
var dt = _db.Ado.GetDataTable($"SELECT * FROM {tableName}");
if (dt.Rows.Count > 0)
{
// Use SqlSugar Fastest().BulkCopy with DataTable
_db.Fastest<System.Data.DataTable>().AS(backupTableName).BulkCopy(dt);
return (true, "Fastest.BulkCopy", dt.Rows.Count, "Backup created using SqlSugar Fastest().BulkCopy with DataTable (fastest for large data)");
}
return (true, "Fastest.BulkCopy", 0, "Backup table created (empty source table)");
}
catch (Exception bulkEx)
{
// Method 3: Manual create + row by row insert (slowest, most compatible)
try
{
// Drop backup table if partially created
try { _db.Ado.ExecuteCommand($"DROP TABLE IF EXISTS {backupTableName}"); } catch { }
var columns = _db.DbMaintenance.GetColumnInfosByTableName(tableName);
// Create table structure manually
var createSql = GenerateCreateTableSql(backupTableName, columns);
_db.Ado.ExecuteCommand(createSql);
// Insert data row by row
var data = _db.Queryable<dynamic>().AS(tableName).ToList();
var rowCount = 0;
foreach (var row in data)
{
var dict = (IDictionary<string, object>)row;
var cols = string.Join(", ", columns.Select(c => c.DbColumnName));
var vals = string.Join(", ", columns.Select(c => FormatValue(dict.ContainsKey(c.DbColumnName) ? dict[c.DbColumnName] : null)));
_db.Ado.ExecuteCommand($"INSERT INTO {backupTableName} ({cols}) VALUES ({vals})");
rowCount++;
}
return (true, "ManualInsert", rowCount, "Backup created using manual insert (compatibility mode)");
}
catch (Exception finalEx)
{
return (false, "Failed", 0, $"All backup methods failed. Create: {createEx.Message}, Bulk: {bulkEx.Message}, Manual: {finalEx.Message}");
}
}
}
}
catch (Exception ex)
{
return (false, "Error", 0, ex.Message);
}
}
/// <summary>
/// Restore table from backup using SqlSugar Fastest bulk operations (preferred) or fallback
/// </summary>
public (bool Success, string Method, int RowCount, string Message) RestoreTable(string tableName, string backupTableName, bool deleteFirst = true)
{
try
{
var currentDbType = _db.CurrentConnectionConfig.DbType;
// Check if backup table exists
var tables = GetTables();
if (!tables.Any(t => t.Equals(backupTableName, StringComparison.OrdinalIgnoreCase)))
{
return (false, "None", 0, $"Backup table '{backupTableName}' does not exist");
}
// Delete existing data if requested
if (deleteFirst)
{
_db.Ado.ExecuteCommand($"DELETE FROM {tableName}");
}
// SQL Server: use explicit column list and handle identity insert when needed.
if (currentDbType == SqlSugar.DbType.SqlServer)
{
try
{
var columns = _db.DbMaintenance.GetColumnInfosByTableName(tableName);
var columnNames = columns.Select(c => c.DbColumnName).ToList();
if (columnNames.Count == 0)
return (false, "SqlServerRestore", 0, $"No columns found for table '{tableName}'");
var columnListSql = string.Join(", ", columnNames.Select(c => $"[{c.Replace("]", "]]")}]"));
var selectListSql = string.Join(", ", columnNames.Select(c => $"[{c.Replace("]", "]]")}]"));
// Identity handling:
// IDENTITY_INSERT is session-scoped, so we must keep the same connection.
// SqlSugar keeps a single connection open during a transaction.
try
{
_db.Ado.BeginTran();
try
{
_db.Ado.ExecuteCommand($"SET IDENTITY_INSERT {tableName} ON");
var rowCount = _db.Ado.ExecuteCommand($"INSERT INTO {tableName} ({columnListSql}) SELECT {selectListSql} FROM {backupTableName}");
_db.Ado.ExecuteCommand($"SET IDENTITY_INSERT {tableName} OFF");
_db.Ado.CommitTran();
return (true, "IdentityInsert", rowCount, "Restored using IDENTITY_INSERT + INSERT ... SELECT (single session)");
}
catch
{
_db.Ado.RollbackTran();
throw;
}
}
catch (Exception ex)
{
// If the table has no identity, fall back to normal insert.
var msg = ex.Message ?? string.Empty;
if (msg.Contains("does not have the identity property", StringComparison.OrdinalIgnoreCase)
|| msg.Contains("Cannot set IDENTITY_INSERT", StringComparison.OrdinalIgnoreCase))
{
var inserted = _db.Ado.ExecuteCommand($"INSERT INTO {tableName} ({columnListSql}) SELECT {selectListSql} FROM {backupTableName}");
return (true, "InsertSelectColumns", inserted, "Restored using INSERT(column list) ... SELECT");
}
throw;
}
}
catch (Exception ex)
{
return (false, "SqlServerRestore", 0, $"SQL Server restore failed: {ex.Message}");
}
}
// Method 1: Try INSERT INTO SELECT (fast and compatible)
try
{
var rowCount = _db.Ado.ExecuteCommand($"INSERT INTO {tableName} SELECT * FROM {backupTableName}");
return (true, "InsertIntoSelect", rowCount, "Restored using INSERT INTO SELECT (fast & compatible)");
}
catch (Exception insertEx)
{
// Method 2: Try Fastest().BulkCopy with DataTable (for large data)
try
{
var dt = _db.Ado.GetDataTable($"SELECT * FROM {backupTableName}");
if (dt.Rows.Count > 0)
{
_db.Fastest<System.Data.DataTable>().AS(tableName).BulkCopy(dt);
return (true, "Fastest.BulkCopy", dt.Rows.Count, "Restored using SqlSugar Fastest().BulkCopy with DataTable (fastest for large data)");
}
return (true, "Fastest.BulkCopy", 0, "Restore completed (empty backup table)");
}
catch (Exception bulkEx)
{
// Method 3: Fallback to row by row insert
try
{
var data = _db.Queryable<dynamic>().AS(backupTableName).ToList();
var columns = _db.DbMaintenance.GetColumnInfosByTableName(tableName);
var rowCount = 0;
foreach (var row in data)
{
var dict = (IDictionary<string, object>)row;
var cols = string.Join(", ", columns.Select(c => c.DbColumnName));
var vals = string.Join(", ", columns.Select(c => FormatValue(dict.ContainsKey(c.DbColumnName) ? dict[c.DbColumnName] : null)));
_db.Ado.ExecuteCommand($"INSERT INTO {tableName} ({cols}) VALUES ({vals})");
rowCount++;
}
return (true, "ManualInsert", rowCount, "Restored using manual insert (compatibility mode)");
}
catch (Exception finalEx)
{
return (false, "Failed", 0, $"All restore methods failed. Insert: {insertEx.Message}, Bulk: {bulkEx.Message}, Manual: {finalEx.Message}");
}
}
}
}
catch (Exception ex)
{
return (false, "Error", 0, ex.Message);
}
}
private string GenerateCreateTableSql(string tableName, List<DbColumnInfo> columns)
{
var columnDefs = columns.Select(c =>
{
var nullable = c.IsNullable ? "" : " NOT NULL";
var primary = c.IsPrimarykey ? " PRIMARY KEY" : "";
var def = !string.IsNullOrEmpty(c.DefaultValue) ? $" DEFAULT {c.DefaultValue}" : "";
return $"{c.DbColumnName} {c.DataType}{nullable}{primary}{def}";
});
return $"CREATE TABLE {tableName} ({string.Join(", ", columnDefs)})";
}
private string FormatValue(object? val)
{
if (val == null || val == DBNull.Value) return "NULL";
if (val is string s) return $"'{s.Replace("'", "''")}'";
if (val is DateTime dt) return $"'{dt:yyyy-MM-dd HH:mm:ss}'";
if (val is bool b) return b ? "1" : "0";
return val.ToString()!;
}
private List<string> GetSqlServerIdentityColumns(string tableName)
{
// Best-effort identity detection for SQL Server. Assumes current connection is SQL Server.
// Supports "dbo.Table" or "Table" (schema omitted). When schema is omitted, we search across schemas.
var raw = tableName.Trim();
static string Unwrap(string s)
{
s = s.Trim();
if (s.StartsWith("[") && s.EndsWith("]") && s.Length >= 2)
return s[1..^1];
return s;
}
string? schema;
string name;
if (raw.Contains('.'))
{
var parts = raw.Split('.', 2);
schema = Unwrap(parts[0]);
name = Unwrap(parts[1]);
}
else
{
schema = null;
name = Unwrap(raw);
}
// Escape single quotes for string literal usage.
schema = schema?.Replace("'", "''");
name = name.Replace("'", "''");
var schemaFilter = schema == null ? "" : $" AND s.name = '{schema}'";
var sql = $@"
SELECT c.name
FROM sys.columns c
JOIN sys.tables t ON c.object_id = t.object_id
JOIN sys.schemas s ON t.schema_id = s.schema_id
WHERE t.name = '{name}'{schemaFilter} AND c.is_identity = 1
ORDER BY c.column_id";
try
{
var dt = _db.Ado.GetDataTable(sql);
var list = new List<string>();
foreach (System.Data.DataRow row in dt.Rows)
{
var v = row[0]?.ToString();
if (!string.IsNullOrWhiteSpace(v)) list.Add(v);
}
return list;
}
catch
{
return new List<string>();
}
}
/// <summary>
/// Export database schema objects (stored procedures, functions, triggers, views, indexes) as SQL scripts
/// </summary>
public string ExportSchemaObjects(string objectType = "all", string? objectName = null)
{
var sb = new System.Text.StringBuilder();
var dbType = _db.CurrentConnectionConfig.DbType;
sb.AppendLine($"-- Schema Export for {dbType}");
sb.AppendLine($"-- Generated: {DateTime.Now:yyyy-MM-dd HH:mm:ss}");
sb.AppendLine($"-- Object Type: {objectType}");
sb.AppendLine();
try
{
// Export Stored Procedures
if (objectType == "all" || objectType == "procedure" || objectType == "proc")
{
sb.AppendLine("-- ========================================");
sb.AppendLine("-- Stored Procedures");
sb.AppendLine("-- ========================================");
sb.AppendLine();
var procedures = GetProcedures(objectName);
foreach (var proc in procedures)
{
sb.AppendLine($"-- Procedure: {proc}");
var procDef = GetProcedureDefinition(proc);
sb.AppendLine(procDef);
sb.AppendLine("GO");
sb.AppendLine();
}
}
// Export Functions
if (objectType == "all" || objectType == "function" || objectType == "func")
{
sb.AppendLine("-- ========================================");
sb.AppendLine("-- User Functions");
sb.AppendLine("-- ========================================");
sb.AppendLine();
var functions = GetFunctions(objectName);
foreach (var func in functions)
{
sb.AppendLine($"-- Function: {func}");
var funcDef = GetFunctionDefinition(func);
sb.AppendLine(funcDef);
sb.AppendLine("GO");
sb.AppendLine();
}
}
// Export Triggers
if (objectType == "all" || objectType == "trigger" || objectType == "trig")
{
sb.AppendLine("-- ========================================");
sb.AppendLine("-- Triggers");
sb.AppendLine("-- ========================================");
sb.AppendLine();
var triggers = GetTriggers(objectName);
foreach (var trigger in triggers)
{
sb.AppendLine($"-- Trigger: {trigger}");
var trigDef = GetTriggerDefinition(trigger);
sb.AppendLine(trigDef);
sb.AppendLine("GO");
sb.AppendLine();
}
}
// Export Views
if (objectType == "all" || objectType == "view")
{
sb.AppendLine("-- ========================================");
sb.AppendLine("-- Views");
sb.AppendLine("-- ========================================");
sb.AppendLine();
var views = GetViews(objectName);
foreach (var view in views)
{
sb.AppendLine($"-- View: {view}");
var viewDef = GetViewDefinition(view);
sb.AppendLine(viewDef);
sb.AppendLine("GO");
sb.AppendLine();
}
}
// Export Indexes
if (objectType == "all" || objectType == "index" || objectType == "idx")
{
sb.AppendLine("-- ========================================");
sb.AppendLine("-- Indexes");
sb.AppendLine("-- ========================================");
sb.AppendLine();
var tables = GetTables();
foreach (var table in tables)
{
var indexes = GetTableIndexes(table);
if (indexes.Count > 0)
{
sb.AppendLine($"-- Indexes for table: {table}");
foreach (var index in indexes)
{
sb.AppendLine(index);
}
sb.AppendLine();
}
}
}
}
catch (Exception ex)
{
sb.AppendLine($"-- Error exporting schema: {ex.Message}");
}
return sb.ToString();
}
public (int FileCount, string OutputDirectory) ExportSchemaObjectsAsFiles(string objectType, string? objectName, string outputDirectory)
{
if (string.IsNullOrWhiteSpace(outputDirectory))
throw new ArgumentException("Output directory is required", nameof(outputDirectory));
Directory.CreateDirectory(outputDirectory);
var written = 0;
static string SafeFileName(string name)
{
if (string.IsNullOrWhiteSpace(name)) return "object";
var invalid = Path.GetInvalidFileNameChars();
var cleaned = new string(name.Select(ch => invalid.Contains(ch) ? '_' : ch).ToArray());
cleaned = cleaned.Replace(' ', '_');
while (cleaned.Contains("__")) cleaned = cleaned.Replace("__", "_");
return cleaned.Trim('_');
}
void WriteOne(string fileName, string contents)
{
var full = Path.Combine(outputDirectory, fileName);
File.WriteAllText(full, contents);
written++;
}
var dbType = _db.CurrentConnectionConfig.DbType;
var header = string.Join(Environment.NewLine, new[]
{
$"-- Schema Export for {dbType}",
$"-- Generated: {DateTime.Now:yyyy-MM-dd HH:mm:ss}",
$"-- Object Type: {objectType}",
""
});
// Stored Procedures
if (objectType == "all" || objectType == "procedure" || objectType == "proc")
{
var procedures = GetProcedures(objectName);
foreach (var proc in procedures)
{
var body = GetProcedureDefinition(proc);
var text = header +
"-- ========================================" + Environment.NewLine +
"-- Stored Procedure" + Environment.NewLine +
"-- ========================================" + Environment.NewLine + Environment.NewLine +
$"-- Procedure: {proc}" + Environment.NewLine +
body + Environment.NewLine +
"GO" + Environment.NewLine;
WriteOne($"procedure__{SafeFileName(proc)}.sql", text);
}
}
// Functions
if (objectType == "all" || objectType == "function" || objectType == "func")
{
var functions = GetFunctions(objectName);
foreach (var func in functions)
{
var body = GetFunctionDefinition(func);
var text = header +
"-- ========================================" + Environment.NewLine +
"-- User Function" + Environment.NewLine +
"-- ========================================" + Environment.NewLine + Environment.NewLine +
$"-- Function: {func}" + Environment.NewLine +
body + Environment.NewLine +
"GO" + Environment.NewLine;
WriteOne($"function__{SafeFileName(func)}.sql", text);
}
}
// Triggers
if (objectType == "all" || objectType == "trigger" || objectType == "trig")
{
var triggers = GetTriggers(objectName);
foreach (var trigger in triggers)
{
var body = GetTriggerDefinition(trigger);
var text = header +
"-- ========================================" + Environment.NewLine +
"-- Trigger" + Environment.NewLine +
"-- ========================================" + Environment.NewLine + Environment.NewLine +
$"-- Trigger: {trigger}" + Environment.NewLine +
body + Environment.NewLine +
"GO" + Environment.NewLine;
WriteOne($"trigger__{SafeFileName(trigger)}.sql", text);
}
}
// Views
if (objectType == "all" || objectType == "view")