forked from cyq1162/cyqdata
-
Notifications
You must be signed in to change notification settings - Fork 0
/
MAction.cs
1538 lines (1466 loc) · 58.2 KB
/
MAction.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
using System;
using System.Collections.Generic;
using System.Text;
using System.Data;
using System.Data.Common;
using System.Data.SqlClient;
using System.ComponentModel;
using CYQ.Data.SQL;
using CYQ.Data.Cache;
using CYQ.Data.Table;
using CYQ.Data.Aop;
using CYQ.Data.Tool;
using CYQ.Data.UI;
namespace CYQ.Data
{
/// <summary>
/// Manipulate:table / view / custom statement
///<para>操作:表/视图/自定义语句</para>
/// </summary>
public partial class MAction : IDisposable
{
#region 全局变量
internal DbBase dalHelper;//数据操作
private SqlCreate _sqlCreate;
private InsertOp _option = InsertOp.ID;
private NoSqlAction _noSqlAction = null;
private MDataRow _Data;//表示一行
/// <summary>
/// Archive the rows of the data structure
/// <para>存档数据结构的行</para>
/// </summary>
public MDataRow Data
{
get
{
return _Data;
}
}
/// <summary>
/// 原始传进来的表名/视图名,未经过[多数据库转换处理]格式化。
/// </summary>
private string _sourceTableName;
private string _TableName; //表名
/// <summary>
/// Table name (if the view statement is the operation, the final view of the name)
///<para>当前操作的表名(若操作的是视图语句,则为最后的视图名字</para> )
/// </summary>
public string TableName
{
get
{
return _TableName;
}
set
{
_TableName = value;
}
}
/// <summary>
/// The database connection string
///<para>数据库链接字符串</para>
/// </summary>
public string ConnectionString
{
get
{
if (dalHelper != null)
{
return dalHelper.conn;
}
return string.Empty;
}
}
private string _debugInfo = string.Empty;
/// <summary>
/// Get or set debugging information [need to set App Config.Debug.Open DebugInfo to ture]
///<para>获取或设置调试信息[需要设置AppConfig.Debug.OpenDebugInfo为ture]</para>
/// </summary>
public string DebugInfo
{
get
{
if (dalHelper != null)
{
return dalHelper.debugInfo.ToString();
}
return _debugInfo;
}
set
{
if (dalHelper != null)
{
dalHelper.debugInfo.Length = 0;
dalHelper.debugInfo.Append(value);
}
}
}
/// <summary>
/// The database type
/// <para>数据库类型</para>
/// </summary>
public DalType DalType
{
get
{
return dalHelper.dalType;
}
}
/// <summary>
/// The database name
/// <para>数据库名称</para>
/// </summary>
public string DataBase
{
get
{
return dalHelper.DataBase;
}
}
/// <summary>
/// The database version
/// 数据库的版本号
/// </summary>
public string DalVersion
{
get
{
return dalHelper.Version;
}
}
/// <summary>
/// The number of rows affected when executing a SQL command (-2 is an exception)
/// <para>执行SQL命令时受影响的行数(-2则为异常)。</para>
/// </summary>
public int RecordsAffected
{
get
{
return dalHelper.recordsAffected;
}
}
/// <summary>
/// Command Timeout[seconds]
///<para>命令超时设置[单位秒]</para>
/// </summary>
public int TimeOut
{
get
{
if (dalHelper.Com != null)
{
return dalHelper.Com.CommandTimeout;
}
return -1;
}
set
{
if (dalHelper.Com != null)
{
dalHelper.Com.CommandTimeout = value;
}
}
}
private bool _AllowInsertID = false;
/// <summary>
/// Whether to allow manual insertion of IDs for self-incrementing primary key identification
///<para>自增主键标识的,是否允许手动插入ID</para>
/// </summary>
public bool AllowInsertID
{
get
{
return _AllowInsertID;
}
set
{
_AllowInsertID = value;
}
}
private bool _isInsertCommand; //是否执行插入命令(区分于Update命令)
private bool _setIdentityResult = true;
/// <summary>
/// MSSQL插入标识ID时开启此选项[事务开启时有效]
/// </summary>
internal void SetIdentityInsertOn()
{
_setIdentityResult = true;
if (dalHelper != null && dalHelper.isOpenTrans)
{
switch (dalHelper.dalType)
{
case DalType.MsSql:
case DalType.Sybase:
if (_Data.Columns.FirstPrimary.IsAutoIncrement)//数字型
{
try
{
string lastTable = Convert.ToString(CacheManage.LocalInstance.Get("MAction_IdentityInsertForSql"));
if (!string.IsNullOrEmpty(lastTable))
{
lastTable = "set identity_insert " + SqlFormat.Keyword(lastTable, dalHelper.dalType) + " off";
dalHelper.ExeNonQuery(lastTable, false);
}
_setIdentityResult = dalHelper.ExeNonQuery("set identity_insert " + SqlFormat.Keyword(_TableName, dalHelper.dalType) + " on", false) > -2;
if (_setIdentityResult)
{
CacheManage.LocalInstance.Set("MAction_IdentityInsertForSql", _TableName, 30);
}
}
catch
{
}
}
break;
}
}
_AllowInsertID = true;
}
/// <summary>
/// MSSQL插入标识ID后关闭此选项[事务开启时有效]
/// </summary>;
internal void SetIdentityInsertOff()
{
if (_setIdentityResult && dalHelper != null && dalHelper.isOpenTrans)
{
switch (dalHelper.dalType)
{
case DalType.MsSql:
case DalType.Sybase:
if (_Data.Columns.FirstPrimary.IsAutoIncrement)//数字型
{
try
{
if (dalHelper.ExeNonQuery("set identity_insert " + SqlFormat.Keyword(_TableName, DalType.MsSql) + " off", false) > -2)
{
_setIdentityResult = false;
CacheManage.LocalInstance.Remove("MAction_IdentityInsertForSql");
}
}
catch
{
}
}
break;
}
}
_AllowInsertID = false;
}
/// <summary>
/// 当DeleteField被设置后(删除转更新操作),如果仍想删除操作(可将此属性置为true)
/// </summary>
internal bool IsIgnoreDeleteField = false;
#endregion
#region 构造函数
/// <summary>
/// Instantiation
/// <para>实例化</para>
/// </summary>
/// <param name="tableNamesEnum">Parameters: table name, view, custom statement, DataRow
/// <para>参数:表名、视图、自定义语句、MDataRow</para></param>
public MAction(object tableNamesEnum)
{
Init(tableNamesEnum, AppConfig.DB.DefaultConn);
}
/// <param name="conn">Database connection statement or configuration key
/// <para>数据库链接语句或配置Key</para></param>
public MAction(object tableNamesEnum, string conn)
{
Init(tableNamesEnum, conn);
}
#endregion
#region 初始化
private void Init(object tableObj, string conn)
{
tableObj = SqlCreate.SqlToViewSql(tableObj);
string dbName = StaticTool.GetDbName(ref tableObj);
if (conn == AppConfig.DB.DefaultConn && !string.IsNullOrEmpty(dbName))
{
conn = dbName + "Conn";
}
MDataRow newRow;
InitConn(tableObj, conn, out newRow);//尝试从MDataRow提取新的Conn链接
InitSqlHelper(newRow, dbName);
InitRowSchema(newRow, true);
InitGlobalObject(true);
//Aop.IAop myAop = Aop.InterAop.Instance.GetFromConfig();//试图从配置文件加载自定义Aop
//if (myAop != null)
//{
// SetAop(myAop);
//}
}
private void InitConn(object tableObj, string conn, out MDataRow newRow)
{
if (tableObj is MDataRow)
{
newRow = tableObj as MDataRow;
}
else
{
newRow = new MDataRow();
newRow.TableName = SqlFormat.NotKeyword(tableObj.ToString());
}
if (!string.IsNullOrEmpty(conn))
{
newRow.Conn = conn;
}
_sourceTableName = newRow.TableName;
}
private void InitSqlHelper(MDataRow newRow, string newDbName)
{
if (dalHelper == null)// || newCreate
{
dalHelper = DalCreate.CreateDal(newRow.Conn);
//创建错误事件。
if (dalHelper.IsOnExceptionEventNull)
{
dalHelper.OnExceptionEvent += new DbBase.OnException(_DataSqlHelper_OnExceptionEvent);
}
}
else
{
dalHelper.ClearParameters();//oracle 11g(某用户的电脑上会出问题,切换表操作,参数未清)
}
if (!string.IsNullOrEmpty(newDbName))//需要切换数据库。
{
if (string.Compare(dalHelper.DataBase, newDbName, StringComparison.OrdinalIgnoreCase) != 0)//数据库名称不相同。
{
if (newRow.TableName.Contains(" "))//视图语句,则直接切换数据库链接。
{
dalHelper.ChangeDatabase(newDbName);
}
else
{
bool isWithDbName = newRow.TableName.Contains(".");//是否DBName.TableName
string fullTableName = isWithDbName ? newRow.TableName : newDbName + "." + newRow.TableName;
string sourceDbName = dalHelper.DataBase;
DbResetResult result = dalHelper.ChangeDatabaseWithCheck(fullTableName);
switch (result)
{
case DbResetResult.Yes://数据库切换了 (不需要前缀)
case DbResetResult.No_SaveDbName:
case DbResetResult.No_DBNoExists:
if (isWithDbName) //带有前缀的,取消前缀
{
_sourceTableName = newRow.TableName = SqlFormat.NotKeyword(fullTableName);
}
break;
case DbResetResult.No_Transationing:
if (!isWithDbName)//如果不同的数据库,需要带有数据库前缀
{
_sourceTableName = newRow.TableName = fullTableName;
}
break;
}
}
}
}
}
void _DataSqlHelper_OnExceptionEvent(string msg)
{
_aop.OnError(msg);
}
private static DateTime lastGCTime = DateTime.Now;
private void InitRowSchema(MDataRow row, bool resetState)
{
_Data = row;
_TableName = SqlCompatible.Format(_sourceTableName, dalHelper.dalType);
_TableName = DBTool.GetMapTableName(dalHelper.useConnBean.ConfigName, _TableName);//处理数据库映射兼容。
if (_Data.Count == 0)
{
if (!TableSchema.FillTableSchema(ref _Data, ref dalHelper, _TableName, _sourceTableName))
{
if (!dalHelper.TestConn(AllowConnLevel.MaterBackupSlave))
{
Error.Throw(dalHelper.dalType + "." + dalHelper.DataBase + ":open database failed! check the connectionstring is be ok!" + AppConst.NewLine + "error:" + dalHelper.debugInfo.ToString());
}
Error.Throw(dalHelper.dalType + "." + dalHelper.DataBase + ":check the tablename \"" + _TableName + "\" is exist?" + AppConst.NewLine + "error:" + dalHelper.debugInfo.ToString());
}
}
else if (resetState)
{
_Data.SetState(0);
}
_Data.Conn = row.Conn;//FillTableSchema会改变_Row的对象。
}
/// <summary>
/// Toggle Table Action: To switch between other tables, use this method
/// <para>切换表操作:如需操作其它表,通过此方法切换</para>
/// </summary>
/// <param name="tableObj">Parameters: table name, view, custom statement, DataRow
/// <para>参数:表名、视图、自定义语句、MDataRow</para></param>
public void ResetTable(object tableObj)
{
ResetTable(tableObj, true, null);
}
/// <param name="resetState">Reset Row State (defaultValue:true)
/// <para>是否重置原有的数据状态(默认true)</para></param>
public void ResetTable(object tableObj, bool resetState)
{
ResetTable(tableObj, resetState, null);
}
/// <param name="newDbName">Other DataBaseName
/// <para>其它数据库名称</para></param>
public void ResetTable(object tableObj, bool resetState, string newDbName)
{
tableObj = SqlCreate.SqlToViewSql(tableObj);
newDbName = newDbName ?? StaticTool.GetDbName(ref tableObj);
MDataRow newRow;
InitConn(tableObj, string.Empty, out newRow);
//newRow.Conn = newDbName;//除非指定链接,否则不切换数据库
InitSqlHelper(newRow, newDbName);
InitRowSchema(newRow, resetState);
InitGlobalObject(false);
}
private void InitGlobalObject(bool allowCreate)
{
if (_Data != null)
{
if (_sqlCreate == null)
{
_sqlCreate = new SqlCreate(this);
}
if (_UI != null)
{
_UI._Data = _Data;
}
else if (allowCreate)
{
_UI = new MActionUI(ref _Data, dalHelper, _sqlCreate);
}
if (_noSqlAction != null)
{
_noSqlAction.Reset(ref _Data, _TableName, dalHelper.Con.DataSource, dalHelper.dalType);
}
else if (allowCreate)
{
switch (dalHelper.dalType)
{
case DalType.Txt:
case DalType.Xml:
_noSqlAction = new NoSqlAction(ref _Data, _TableName, dalHelper.Con.DataSource, dalHelper.dalType);
break;
}
}
}
}
#endregion
#region 数据库操作方法
private bool InsertOrUpdate(string sqlCommandText)
{
bool returnResult = false;
if (_sqlCreate.isCanDo)
{
#region 执行Insert或Update命令
if (_isInsertCommand) //插入
{
_isInsertCommand = false;
object ID;
switch (dalHelper.dalType)
{
case DalType.MsSql:
case DalType.Sybase:
ID = dalHelper.ExeScalar(sqlCommandText, false);
if (ID == null && AllowInsertID && dalHelper.recordsAffected > -2)
{
ID = _Data.PrimaryCell.Value;
}
break;
default:
#region MyRegion
bool isTrans = dalHelper.isOpenTrans;
int groupID = DataType.GetGroup(_Data.PrimaryCell.Struct.SqlType);
bool isNum = groupID == 1 && _Data.PrimaryCell.Struct.Scale <= 0;
if (!isTrans && (isNum || _Data.PrimaryCell.Struct.IsAutoIncrement) && (!AllowInsertID || _Data.PrimaryCell.IsNullOrEmpty)) // 数字自增加
{
dalHelper.isOpenTrans = true;//开启事务。
dalHelper.TranLevel = IsolationLevel.ReadCommitted;//默认事务级别已是这个,还是设置一下,避免外部调整对此的影响。
}
ID = dalHelper.ExeNonQuery(sqlCommandText, false);//返回的是受影响的行数
if (_option != InsertOp.None && ID != null && Convert.ToInt32(ID) > 0)
{
if (AllowInsertID && !_Data.PrimaryCell.IsNullOrEmpty)//手工插ID
{
ID = _Data.PrimaryCell.Value;
}
else if (isNum)
{
ClearParameters();
ID = dalHelper.ExeScalar(_sqlCreate.GetMaxID(), false);
}
else
{
ID = null;
returnResult = true;
}
}
if (!isTrans)
{
dalHelper.EndTransaction();
}
#endregion
break;
}
if ((ID != null && Convert.ToString(ID) != "-2") || (dalHelper.recordsAffected > -2 && _option == InsertOp.None))
{
if (_option != InsertOp.None)
{
_Data.PrimaryCell.Value = ID;
}
returnResult = (_option == InsertOp.Fill) ? Fill(ID) : true;
}
}
else //更新
{
returnResult = dalHelper.ExeNonQuery(sqlCommandText, false) > 0;
}
#endregion
}
else if (!_isInsertCommand && _Data.GetState() == 1 && dalHelper.recordsAffected != -2) // 更新操作。
{
//输出警告信息
return true;
}
else if (dalHelper.isOpenTrans && dalHelper.recordsAffected == -2) // 若事务中,则回滚
{
dalHelper.WriteError(_isInsertCommand ? "Insert" : "Update" + "():");
}
return returnResult;
}
#region 插入
/// <summary>
/// Insert To DataBase
/// <para>插入数据</para>
/// </summary>
public bool Insert()
{
return Insert(false, _option);
}
/// <param name="option">InsertOp
/// <para>插入选项</para></param>
public bool Insert(InsertOp option)
{
return Insert(false, option);
}
/// <param name="autoSetValue">Automatic get values from context
/// <para>自动取值(从上下文环境中)</para></param>
public bool Insert(bool autoSetValue)
{
return Insert(autoSetValue, _option);
}
/// <param name="option">InsertOp
/// <para>插入选项</para></param>
public bool Insert(bool autoSetValue, InsertOp option)
{
if (CheckDisposed()) { return false; }
if (autoSetValue)
{
_UI.GetAll(!AllowInsertID);//允许插入ID时,也需要获取主键。
}
AopResult aopResult = AopResult.Default;
if (_aop.IsLoadAop)
{
_aop.Para.MAction = this;
_aop.Para.TableName = _sourceTableName;
_aop.Para.Row = _Data;
_aop.Para.AutoSetValue = autoSetValue;
_aop.Para.InsertOp = option;
_aop.Para.IsTransaction = dalHelper.isOpenTrans;
aopResult = _aop.Begin(Aop.AopEnum.Insert);
}
if (aopResult == AopResult.Default || aopResult == AopResult.Continue)
{
switch (dalHelper.dalType)
{
case DalType.Txt:
case DalType.Xml:
_aop.Para.IsSuccess = _noSqlAction.Insert(dalHelper.isOpenTrans);
break;
default:
ClearParameters();
string sql = _sqlCreate.GetInsertSql();
_isInsertCommand = true;
_option = option;
_aop.Para.IsSuccess = InsertOrUpdate(sql);
break;
}
}
else if (option != InsertOp.None)
{
_Data = _aop.Para.Row;
InitGlobalObject(false);
}
if (_aop.IsLoadAop && (aopResult == AopResult.Break || aopResult == AopResult.Continue))
{
_aop.End(Aop.AopEnum.Insert);
}
if (dalHelper.recordsAffected == -2)
{
OnError();
}
return _aop.Para.IsSuccess;
}
#endregion
#region 更新
/// <summary>
/// Update to database [Will automatically try to fetch from the UI when conditions are not passed]
/// <para>更新数据[不传where条件时将自动尝试从UI获取]</para>
/// </summary>
public bool Update()
{
return Update(null, true);
}
/// <param name="where">Sql statement where the conditions: 88, "id = 88"
/// <para>sql语句的where条件:88、"id=88"</para></param>
public bool Update(object where)
{
return Update(where, false);
}
/// <param name="autoSetValue">Automatic get values from context
/// <para>自动取值(从上下文环境中)</para></param>
public bool Update(bool autoSetValue)
{
return Update(null, autoSetValue);
}
/// <param name="autoSetValue">Automatic get values from context
/// <para>自动取值(从上下文环境中)</para></param>
public bool Update(object where, bool autoSetValue)
{
if (CheckDisposed()) { return false; }
if (autoSetValue)
{
_UI.GetAll(false);
}
if (where == null || Convert.ToString(where) == "")
{
where = _sqlCreate.GetPrimaryWhere();
}
AopResult aopResult = AopResult.Default;
if (_aop.IsLoadAop)
{
_aop.Para.MAction = this;
_aop.Para.TableName = _sourceTableName;
_aop.Para.Row = _Data;
_aop.Para.Where = where;
//_aop.Para.AopPara = aopPara;
_aop.Para.AutoSetValue = autoSetValue;
_aop.Para.UpdateExpression = _sqlCreate.updateExpression;
_aop.Para.IsTransaction = dalHelper.isOpenTrans;
aopResult = _aop.Begin(Aop.AopEnum.Update);
}
if (aopResult == AopResult.Default || aopResult == AopResult.Continue)
{
switch (dalHelper.dalType)
{
case DalType.Txt:
case DalType.Xml:
_aop.Para.IsSuccess = _noSqlAction.Update(_sqlCreate.FormatWhere(where));
break;
default:
ClearParameters();
string sql = _sqlCreate.GetUpdateSql(where);
_aop.Para.IsSuccess = InsertOrUpdate(sql);
break;
}
}
if (_aop.IsLoadAop && (aopResult == AopResult.Break || aopResult == AopResult.Continue))
{
_aop.End(Aop.AopEnum.Update);
}
if (dalHelper.recordsAffected == -2)
{
OnError();
}
return _aop.Para.IsSuccess;
}
#endregion
/// <summary>
/// Delete from database [Will automatically try to fetch from the UI when conditions are not passed]
/// <para>删除数据[不传where条件时将自动尝试从UI获取]</para>
/// </summary>
public bool Delete()
{
return Delete(null);
}
/// <param name="where">Sql statement where the conditions: 88, "id = 88"
/// <para>sql语句的where条件:88、"id=88"</para></param>
public bool Delete(object where)
{
if (CheckDisposed()) { return false; }
if (where == null || Convert.ToString(where) == "")
{
_UI.PrimayAutoGetValue();
where = _sqlCreate.GetPrimaryWhere();
}
AopResult aopResult = AopResult.Default;
if (_aop.IsLoadAop)
{
_aop.Para.MAction = this;
_aop.Para.TableName = _sourceTableName;
_aop.Para.Row = _Data;
_aop.Para.Where = where;
//_aop.Para.AopPara = aopPara;
_aop.Para.IsTransaction = dalHelper.isOpenTrans;
aopResult = _aop.Begin(Aop.AopEnum.Delete);
}
if (aopResult == AopResult.Default || aopResult == AopResult.Continue)
{
string deleteField = AppConfig.DB.DeleteField;
bool isToUpdate = !IsIgnoreDeleteField && !string.IsNullOrEmpty(deleteField) && _Data.Columns.Contains(deleteField);
switch (dalHelper.dalType)
{
case DalType.Txt:
case DalType.Xml:
string sqlWhere = _sqlCreate.FormatWhere(where);
if (isToUpdate)
{
_Data.Set(deleteField, true);
_aop.Para.IsSuccess = _noSqlAction.Update(sqlWhere);
}
else
{
_aop.Para.IsSuccess = _noSqlAction.Delete(sqlWhere);
}
break;
default:
ClearParameters();
string sql = isToUpdate ? _sqlCreate.GetDeleteToUpdateSql(where) : _sqlCreate.GetDeleteSql(where);
_aop.Para.IsSuccess = dalHelper.ExeNonQuery(sql, false) > 0;
break;
}
}
if (_aop.IsLoadAop && (aopResult == AopResult.Break || aopResult == AopResult.Continue))
{
_aop.End(Aop.AopEnum.Delete);
}
if (dalHelper.recordsAffected == -2)
{
OnError();
}
return _aop.Para.IsSuccess;
}
/// <summary>
/// select all data
///<para>选择所有数据</para>
/// </summary>
public MDataTable Select()
{
int count;
return Select(0, 0, null, out count);
}
/// <param name="where">Sql statement where the conditions: 88, "id = 88"
/// <para>sql语句的where条件:88、"id=88"</para></param>
public MDataTable Select(object where)
{
int count;
return Select(0, 0, where, out count);
}
public MDataTable Select(int topN, object where)
{
int count;
return Select(0, topN, where, out count);
}
/// <param name="pageIndex">pageIndex<para>第几页</para></param>
/// <param name="pageSize">pageSize<para>每页数量[为0时默认选择所有]</para></param>
public MDataTable Select(int pageIndex, int pageSize)
{
int count;
return Select(pageIndex, pageSize, null, out count);
}
public MDataTable Select(int pageIndex, int pageSize, object where)
{
int count;
return Select(pageIndex, pageSize, where, out count);
}
/// <param name="rowCount">The total number of records returned
/// <para>返回的记录总数</para></param>
public MDataTable Select(int pageIndex, int pageSize, object where, out int rowCount)
{
if (CheckDisposed()) { rowCount = -1; return new MDataTable(_TableName); }
rowCount = 0;
AopResult aopResult = AopResult.Default;
if (_aop.IsLoadAop)
{
_aop.Para.MAction = this;
_aop.Para.PageIndex = pageIndex;
_aop.Para.PageSize = pageSize;
_aop.Para.TableName = _sourceTableName;
_aop.Para.Row = _Data;
_aop.Para.Where = where;
_aop.Para.SelectColumns = _sqlCreate.selectColumns;
//_aop.Para.AopPara = aopPara;
_aop.Para.IsTransaction = dalHelper.isOpenTrans;
aopResult = _aop.Begin(Aop.AopEnum.Select);
}
if (aopResult == AopResult.Default || aopResult == AopResult.Continue)
{
string primaryKey = SqlFormat.Keyword(_Data.Columns.FirstPrimary.ColumnName, dalHelper.dalType);//主键列名。
switch (dalHelper.dalType)
{
case DalType.Txt:
case DalType.Xml:
_aop.Para.Table = _noSqlAction.Select(pageIndex, pageSize, _sqlCreate.FormatWhere(where), out rowCount, _sqlCreate.selectColumns);
break;
default:
_aop.Para.Table = new MDataTable(_TableName.Contains("(") ? "SysDefaultCustomTable" : _TableName);
_aop.Para.Table.LoadRow(_Data);
ClearParameters();//------------------------参数清除
DbDataReader sdReader = null;
string whereSql = string.Empty;//已格式化过的原生whereSql语句
if (_sqlCreate != null)
{
whereSql = _sqlCreate.FormatWhere(where);
}
else
{
whereSql = SqlFormat.Compatible(where, dalHelper.dalType, dalHelper.Com.Parameters.Count == 0);
}
bool byPager = pageIndex > 0 && pageSize > 0;//分页查询(第一页也要分页查询,因为要计算总数)
if (byPager && AppConfig.DB.PagerBySelectBase && dalHelper.dalType == DalType.MsSql && !dalHelper.Version.StartsWith("08"))// || dalHelper.dalType == DalType.Oracle
{
#region 存储过程执行
if (dalHelper.Com.Parameters.Count > 0)
{
dalHelper.debugInfo.Append(AppConst.HR + "error : select method deny call SetPara() method to add custom parameters!");
}
dalHelper.AddParameters("@PageIndex", pageIndex, DbType.Int32, -1, ParameterDirection.Input);
dalHelper.AddParameters("@PageSize", pageSize, DbType.Int32, -1, ParameterDirection.Input);
dalHelper.AddParameters("@TableName", _sqlCreate.GetSelectTableName(ref whereSql), DbType.String, -1, ParameterDirection.Input);
whereSql = _sqlCreate.AddOrderByWithCheck(whereSql, primaryKey);
dalHelper.AddParameters("@Where", whereSql, DbType.String, -1, ParameterDirection.Input);
sdReader = dalHelper.ExeDataReader("SelectBase", true);
#endregion
}
else
{
#region SQL语句分页执行
if (byPager)
{
rowCount = GetCount(whereSql);//利用自动缓存,避免每次分页都要计算总数。
_aop.Para.Where = where;//恢复影响的条件,避免影响缓存key
_aop.isHasCache = false;//不能影响Select的后续操作。
//rowCount = Convert.ToInt32(dalHelper.ExeScalar(_sqlCreate.GetCountSql(whereSql), false));//分页查询先记算总数
}
if (!byPager || (rowCount > 0 && (pageIndex - 1) * pageSize < rowCount))
{
string sql = SqlCreateForPager.GetSql(dalHelper.dalType, dalHelper.Version, pageIndex, pageSize, whereSql, SqlFormat.Keyword(_TableName, dalHelper.dalType), rowCount, _sqlCreate.GetColumnsSql(), primaryKey, _Data.PrimaryCell.Struct.IsAutoIncrement);
sdReader = dalHelper.ExeDataReader(sql, false);
}
else if (_sqlCreate.selectColumns != null)
{
_aop.Para.Table = _aop.Para.Table.Select(0, 0, null, _sqlCreate.selectColumns);
}
#endregion
}
if (sdReader != null)
{
// _aop.Para.Table.ReadFromDbDataReader(sdReader);//内部有关闭。
_aop.Para.Table = sdReader;
if (!byPager)
{
rowCount = _aop.Para.Table.Rows.Count;
}
else if (dalHelper.dalType == DalType.MsSql && AppConfig.DB.PagerBySelectBase)
{
rowCount = dalHelper.ReturnValue;
}
_aop.Para.Table.RecordsAffected = rowCount;
}
else
{
_aop.Para.Table.Rows.Clear();//预防之前的插入操作产生了一个数据行。
}
_aop.Para.IsSuccess = _aop.Para.Table.Rows.Count > 0;
ClearParameters();//------------------------参数清除
break;
}
}
else if (_aop.Para.Table.RecordsAffected > 0)
{
rowCount = _aop.Para.Table.RecordsAffected;//返回记录总数
}
if (_aop.IsLoadAop && (aopResult == AopResult.Break || aopResult == AopResult.Continue))
{
_aop.End(Aop.AopEnum.Select);
}
_aop.Para.Table.TableName = TableName;//Aop从Json缓存加载时会丢失表名。
_aop.Para.Table.Conn = _Data.Conn;
//修正DataType和Size、Scale
for (int i = 0; i < _aop.Para.Table.Columns.Count; i++)
{
MCellStruct msTable = _aop.Para.Table.Columns[i];
MCellStruct ms = _Data.Columns[msTable.ColumnName];
if (ms != null)
{
msTable.Load(ms);
}
}
if (_sqlCreate != null)
{
_sqlCreate.selectColumns = null;
}
return _aop.Para.Table;
}
/// <summary>
/// Select top one row to fill this.Data
/// <para>选择一行数据,并填充到Data属性[不传where条件时将自动尝试从UI获取]</para>
/// </summary>
public bool Fill()
{
return Fill(null);
}
/// <param name="where">Sql statement where the conditions: 88, "id = 88"
/// <para>sql语句的where条件:88、"id=88"</para></param>
public bool Fill(object where)
{
if (CheckDisposed()) { return false; }
if (where == null || Convert.ToString(where) == "")
{
_UI.PrimayAutoGetValue();
where = _sqlCreate.GetPrimaryWhere();
}
AopResult aopResult = AopResult.Default;
if (_aop.IsLoadAop)
{
_aop.Para.MAction = this;
_aop.Para.TableName = _sourceTableName;
_aop.Para.Row = _Data;
_aop.Para.Where = where;
_aop.Para.SelectColumns = _sqlCreate.selectColumns;
//_aop.Para.AopPara = aopPara;
_aop.Para.IsTransaction = dalHelper.isOpenTrans;
aopResult = _aop.Begin(Aop.AopEnum.Fill);
}
if (aopResult == AopResult.Default || aopResult == AopResult.Continue)
{
switch (dalHelper.dalType)
{
case DalType.Txt:
case DalType.Xml:
_aop.Para.IsSuccess = _noSqlAction.Fill(_sqlCreate.FormatWhere(where));
break;
default:
ClearParameters();
MDataTable mTable = dalHelper.ExeDataReader(_sqlCreate.GetTopOneSql(where), false);
// dalHelper.ResetConn();//重置Slave
if (mTable != null && mTable.Rows.Count > 0)
{
_Data.Clear();//清掉旧值。
_Data.LoadFrom(mTable.Rows[0], RowOp.None, true);//setselectcolumn("aa as bb")时
_aop.Para.IsSuccess = true;
}
else
{
_aop.Para.IsSuccess = false;
}
break;
}
}