public T ExecuteInterfaceMethod <T>(MethodInformation method, Action <T> action) { DataOptType dataOptType = ((IDataInterface)this).dataOptType; method.dataProviderNamespace = dataProviderNamespace; method.dataProviderClassName = dataProviderClassName; method.fields = fields; method.fieldsType = fieldsType; method.ResultExecMethod = ResultExecMethod; method.sqlExecType = sqlExecType; string sqlVarName = "sql"; DynamicCodeAutoCall dynamicCodeAutoCall = new DynamicCodeAutoCall(); sql = dynamicCodeAutoCall.ExecReplaceForSqlByFieldName(sql, sqlVarName, method); DynamicCodeChange dynamicCodeChange = new DynamicCodeChange(); try { dynamicCodeChange.AnalyzeSql(method, dataOptType, sqlVarName, ref sql); } catch (Exception ex) { e(ex.ToString(), ErrorLevels.severe); throw ex; } DynamicEntity dynamicEntity = new DynamicEntity(); T result = dynamicEntity.Exec <T>(method, dataOptType, action, sql); return(result); }
string ISqlExpressionProvider.provideSql(DbList <DbParameter> dbParameters, DataOptType dataOptType, PList <Para> paraList, object[] methodParameters) { string ComNameEn = paraList["ComNameEn", true].ToString(); string sql = "select a.* from EmployeeInfo a, WorkInfo b where a.id=b.EmployeeInfoID and b.CompanyNameEn=@CompanyNameEn"; dbParameters.Add("CompanyNameEn", ComNameEn); return(sql); throw new NotImplementedException(); }
string ISqlExpressionProvider.provideSql(DbList <DbParameter> dbParameters, DataOptType dataOptType, PList <Para> paraList, object[] methodParameters) { DataEntity <DataElement> dataElements = paraList["dataElements", true].TryObject <DataEntity <DataElement> >(); string sql = "select a.* from EmployeeInfo a, WorkInfo b where a.id=b.EmployeeInfoID and b.CompanyNameEn=@CompanyNameEn"; dbParameters.Add("CompanyNameEn", dataElements["CompanyNameEn"].value); return(sql); throw new NotImplementedException(); }
public AbsDataInterface() : base() { string fn = ""; // this.GetType().Name; Type[] types = new Type[] { typeof(AutoCount), typeof(AutoSelect), typeof(AutoInsert), typeof(AutoUpdate), typeof(AutoDelete), typeof(AutoProcedure) }; int n = 0; Type typeObj = typeof(object); object obj = this; Type baseType = obj.GetType(); Dictionary <Type, Type> dic = new Dictionary <Type, Type>(); dic.Add(baseType, baseType); while (5 > n) { baseType = baseType.BaseType; if (baseType.Equals(typeObj)) { break; } dic.Add(baseType, baseType); n++; } foreach (Type item in types) { typeObj = null; dic.TryGetValue(item, out typeObj); if (null != typeObj) { fn = item.Name; break; } } Regex rg = new Regex("^Auto(?<TagName>[a-z]+)", RegexOptions.IgnoreCase); if (rg.IsMatch(fn)) { string TagName = rg.Match(fn).Groups["TagName"].Value.ToLower(); DataOptType dataOptType = DataOptType.none; Enum.TryParse <DataOptType>(TagName, out dataOptType); ((IDataInterface)this).dataOptType = dataOptType; } }
static void bufferDatas(IDbHelper dbHelper, AutoCall autoCall, DataOptType dataOptType, string sql, List <DbParameter> parameters, Action <object> action, Func <DbCommand, object> func) { lock (_bufferData) { if (DataOptType.insert == dataOptType) { if (null == insertBatch) { insertBatch = new InsertBatch(); setAsbBatchProperty(insertBatch, dbHelper); } insertBatch.analysis(dbHelper, autoCall, sql, parameters, (sql_1, tableName_1, para_1) => { addDataToCollection(dbHelper, autoCall, action, func, sql_1, tableName_1, para_1); }); } else if (DataOptType.update == dataOptType) { if (null == updateBatch) { updateBatch = new UpdateBatch(); setAsbBatchProperty(updateBatch, dbHelper); } updateBatch.analysis(dbHelper, autoCall, sql, parameters, (sql_1, tableName_1, para_1) => { addDataToCollection(dbHelper, autoCall, action, func, sql_1, tableName_1, para_1); }); } else if (DataOptType.delete == dataOptType) { if (null == deleteBatch) { deleteBatch = new DeleteBatch(); setAsbBatchProperty(deleteBatch, dbHelper); } deleteBatch.analysis(dbHelper, autoCall, sql, parameters, (sql_1, tableName_1, para_1) => { addDataToCollection(dbHelper, autoCall, action, func, sql_1, tableName_1, para_1); }); } } }
void ReturnResult(MethodInformation method, LeftSpaceLevel leftSpaceLevel, DataOptType dataOptType, string funcResultVarName, string resultVarName, ref string code) { Type resultType = method.methodInfo.ReturnType; if (DataOptType.insert == dataOptType || DataOptType.update == dataOptType || DataOptType.delete == dataOptType) { if (typeof(bool) == resultType || typeof(Boolean) == resultType) { method.append(ref code, leftSpaceLevel, "{0} = 0 < {1};", funcResultVarName, resultVarName); } else { method.append(ref code, leftSpaceLevel, "{0} = {1};", funcResultVarName, resultVarName); } } else { method.append(ref code, leftSpaceLevel, "{0} = {1};", funcResultVarName, resultVarName); } }
/// <summary> /// 执行 delete 操作 /// </summary> /// <param name="deleteExpression">delete 语句表达式</param> /// <param name="sqlExecType">sql 表达式执行类型</param> public AutoDelete(string deleteExpression, DataOptType sqlExecType) : base() { sql = deleteExpression; this.sqlExecType = sqlExecType; }
/// <summary> /// 执行 insert 操作 /// </summary> /// <param name="insertExpression">执行 insert 操作的sql语句</param> /// <param name="fields">执行 insert 操作时必须排除\包含的字段名称</param> /// <param name="fieldsType">指示字段名称集合类型是 Exclude(排除) 或 Contain(包含), 默认为 Exclude</param> /// <param name="sqlExecType">sql 表达式执行类型</param> public AutoInsert(string insertExpression, string[] fields, FieldsType fieldsType, DataOptType sqlExecType) : base() { sql = insertExpression; this.fields = fields; this.fieldsType = fieldsType; this.sqlExecType = sqlExecType; }
public AutoInsert(string insertExpression, DataOptType sqlExecType, bool EnabledBuffer) : base() { sql = insertExpression; this.sqlExecType = sqlExecType; this.EnabledBuffer = EnabledBuffer; }
public T Exec <T>(MethodInformation method, DataOptType dataOptType, Action <T> action, string sql) { T result = default(T); AutoCall autoCall = (AutoCall)method.AutoCall; dynamicWhere(method, ref sql); IList <DataEntity <DataElement> > dataElements = null; DataEntity <DataElement> dataElements1 = null; DbList <DbParameter> dbParameters = null; if (0 < method.paraList.Count) { foreach (Para item in method.paraList) { if (null != item.ParaValue) { if (null != item.ParaValue as IList <DataEntity <DataElement> > ) { dataElements = item.ParaValue as IList <DataEntity <DataElement> >; break; } else if (null != item.ParaValue as DataEntity <DataElement> ) { dataElements = new List <DataEntity <DataElement> >(); dataElements1 = item.ParaValue as DataEntity <DataElement>; dataElements.Add(dataElements1); break; } } } } if (null == dataElements) { dataElements = new List <DataEntity <DataElement> >(); } string err = ""; bool EnabledBuffer = method.methodComponent.EnabledBuffer; EnabledBuffer = method.methodComponent.IsAsync ? true : EnabledBuffer; if (DataOptType.select == dataOptType || DataOptType.count == dataOptType || DataOptType.procedure == dataOptType) { if (0 < dataElements.Count) { dataElements1 = dataElements[0]; } dbParameters = GetDbParameters(method, dataElements1, sql); GetSqlByProvider(method, dbParameters, ref sql); dbHelper.query(autoCall, sql, dbParameters, EnabledBuffer, (dt) => { DynamicCodeAutoCall dynamicCodeAutoCall = new DynamicCodeAutoCall(); string execClassPath = ""; string execMethodName = ""; bool paraExsit = false; Type returnType = dynamicCodeAutoCall.GetParaTypeOfResultExecMethod(method, ref execClassPath, ref execMethodName, ref paraExsit); if (paraExsit) { Type resultExecMethodType = execClassPath.GetClassTypeByPath(); if (null == resultExecMethodType) { err = "The ClassPath '" + execClassPath + "' is not exist."; autoCall.e(err, ErrorLevels.dangerous); throw new Exception(err); } object clsObj = null; MethodInfo methodInfo = resultExecMethodType.GetMethod(execMethodName); if (null != methodInfo) { if (methodInfo.ReturnType != typeof(T)) { err = ""; string msg = "The return value type of the method '{0}' of the class '{1}' and the method '{2}' of the interface '{3}' are not the same."; method.append(ref err, 0, msg, execMethodName, execClassPath, method.methodInfo.Name, method.methodInfo.DeclaringType.FullName); autoCall.e(err, ErrorLevels.dangerous); throw new Exception(err); } object vData = dataTableTo(method, dt, returnType); try { clsObj = Activator.CreateInstance(resultExecMethodType); result = (T)methodInfo.Invoke(clsObj, new object[] { vData }); } catch (Exception ex) { autoCall.e(ex.ToString(), ErrorLevels.dangerous); //throw; } } } else { result = dataTableTo <T>(method, dt); } if (null != action) { action(result); } }, ref err); } else { int n = 0; Func <int, T> funcResult = n1 => { object v = n1; if (typeof(bool) == typeof(T)) { v = 0 < n1; } return((T)v); }; foreach (DataEntity <DataElement> item in dataElements) { dbParameters = GetDbParameters(method, item, sql); switch (dataOptType) { case DataOptType.insert: dbHelper.insert(autoCall, sql, dbParameters, EnabledBuffer, (num) => { n += num; result = funcResult(n); if (null != action) { action(result); } }, ref err); break; case DataOptType.update: dbHelper.update(autoCall, sql, dbParameters, EnabledBuffer, (num) => { n += num; result = funcResult(n); if (null != action) { action(result); } }, ref err); break; case DataOptType.delete: dbHelper.delete(autoCall, sql, dbParameters, EnabledBuffer, (num) => { n += num; result = funcResult(n); if (null != action) { action(result); } }, ref err); break; } } result = funcResult(n); } return(result); }
public AnalyzeSqlOnClass(DataOptType dataOptType, Type methodParameterType) { this.dataOptType = dataOptType; this.methodParameterType = methodParameterType; }
public string GetParametersBySqlParameter(string sql, string sqlVarName, MethodInformation method, DataOptType dataOptType, ref string dbParaListVarName) { string code = ""; string sql1 = sql; string executeDbHelper = "{ExecuteDbHelper#}"; string leftSpace = ""; Regex rg = rgParaField; if (string.IsNullOrEmpty(dbParaListVarName) || dbParaListVarName.ToLower().Equals("null")) { dbParaListVarName = "dbParaList"; method.append(ref code, LeftSpaceLevel.one, "DbList<System.Data.Common.DbParameter> {0} = new DbList<System.Data.Common.DbParameter>();", dbParaListVarName); } string dbHelperVarName = "dbHelper"; string resultVarName = "successVal"; string funcResultVarName = method.methodComponent.ResultVariantName; if (baseTypeWithResult(method)) { method.append(ref code, LeftSpaceLevel.one, "int {0} = 0;", resultVarName); } else { method.append(ref code, LeftSpaceLevel.one, "{0} {1} = default({0});", method.methodComponent.ResultType.FullName, resultVarName); } method.append(ref code, LeftSpaceLevel.one, "string err = \"\";"); method.append(ref code, LeftSpaceLevel.one, "IDbHelper {0} = ImplementAdapter.DbHelper;", dbHelperVarName); if (rg.IsMatch(sql) && 0 < method.paraList.Count) { string LeftSign = ""; string EndSign = ""; string DbTag = ""; string FieldName = ""; string autoCallName = method.AutoCallVarName; Match match = null; EList <CKeyValue> sqlParaList1 = new EList <CKeyValue>(); string sqlParasVarName = "sqlParaList"; method.append(ref code, LeftSpaceLevel.one, "EList<CKeyValue> {0} = new EList<CKeyValue>();", sqlParasVarName); int n = 0; while (rg.IsMatch(sql1) && 200 > n) { match = rg.Match(sql1); LeftSign = match.Groups["LeftSign"].Value; EndSign = match.Groups["EndSign"].Value; if (isEnabledField(LeftSign)) { if (string.IsNullOrEmpty(DbTag)) { DbTag = match.Groups["DbTag"].Value; } FieldName = match.Groups["FieldName"].Value; method.append(ref code, LeftSpaceLevel.one, "{0}.Add(new CKeyValue(){ Key = \"{1}\", Value = \"{2}\", other = \"{3}\" });", sqlParasVarName, FieldName.ToLower(), FieldName, DbTag); sqlParaList1.Add(new CKeyValue() { Key = FieldName.ToLower(), Value = FieldName, other = DbTag }); } sql1 = sql1.Replace(match.Groups[0].Value, ""); sql1 = EndSign + sql1; n++; } Regex rg1 = new Regex(@"\`[0-9]+\["); CKeyValue kv = null; PList <Para> paraList = method.paraList; string paraClassName = ""; //DJTools.GetParamertClassNameByDbTag(DbTag); foreach (Para para in paraList) { if (para.ParaType.BaseType == typeof(System.MulticastDelegate) && rg1.IsMatch(para.ParaType.ToString())) { continue; } if (DJTools.IsBaseType(para.ParaType)) { //方法参数为基本类型 string, int, bool 等 kv = sqlParaList1[para.ParaName.ToLower()]; if (null == kv) { continue; } method.append(ref code, LeftSpaceLevel.one, "{0}.Add(\"{2}\", {3});", dbParaListVarName, paraClassName, kv.Value.ToString(), para.ParaName); } else { LeftSpaceLevel leftSpaceLevel = LeftSpaceLevel.one; if (null != para.ParaType.GetInterface("IEnumerable")) { //集合复杂类型 //ICollection collection = (ICollection)para.ParaValue; method.append(ref code, LeftSpaceLevel.one, ""); method.append(ref code, LeftSpaceLevel.one, "System.Collections.ICollection collection = (System.Collections.ICollection){0};", para.ParaName); method.append(ref code, LeftSpaceLevel.one, ""); if (null != para.ParaType.GetInterface("IDictionary")) { method.append(ref code, leftSpaceLevel, "//键值对情况"); method.append(ref code, leftSpaceLevel, "object vObj = null;"); method.append(ref code, leftSpaceLevel, "string key = \"\";"); method.append(ref code, leftSpaceLevel, "foreach (var item in collection)"); method.append(ref code, leftSpaceLevel, "{"); method.append(ref code, leftSpaceLevel + 1, "key = item.GetType().GetProperty(\"Key\").GetValue(item, null).ToString();"); method.append(ref code, leftSpaceLevel + 1, "vObj = item.GetType().GetProperty(\"Value\").GetValue(item, null);"); method.append(ref code, leftSpaceLevel + 1, "if (DJTools.IsBaseType(vObj.GetType())) break;"); method.append(ref code, leftSpaceLevel + 1, "if (null != vObj.GetType().GetInterface(\"IEnumerable\")) break;"); method.append(ref code, leftSpaceLevel + 1, "//值必须是简单类型:int, string, bool, float, double等"); method.append(ref code, leftSpaceLevel + 1, ""); //Type dataType, string dbTag, object data, string fieldName, List<DbParameter> dbParas method.append(ref code, leftSpaceLevel + 1, "{0}.GetDbParaByBaseType(typeof(string),\"{1}\",vObj,key,{2});", autoCallName, DbTag, dbParaListVarName); method.append(ref code, leftSpaceLevel + 1, ""); method.append(ref code, leftSpaceLevel, "}"); //foreach (var item in collection) } else if (null != para.ParaType.GetInterface("IList") || para.ParaType.IsArray) { leftSpace = method.StartSpace + method.getSpace((int)leftSpaceLevel); method.append(ref code, leftSpaceLevel, "//List集合情况 或 数组情况"); method.append(ref code, leftSpaceLevel, "foreach (var item in collection)"); method.append(ref code, leftSpaceLevel, "{"); method.append(ref code, leftSpaceLevel + 1, "if (DJTools.IsBaseType(item.GetType())) break;"); method.append(ref code, leftSpaceLevel + 1, "if (null != item.GetType().GetInterface(\"IEnumerable\")) break;"); method.append(ref code, leftSpaceLevel + 1, "//集合元素必须是单体复杂对象(数据实体)"); //object entity, List<DbParameter> dbParas, EList<CKeyValue> paraNameList method.append(ref code, leftSpaceLevel + 1, "{0}.GetDbParaListByEntity(item,{1},{2});", autoCallName, dbParaListVarName, sqlParasVarName); code += "\r\n" + executeDbHelper; method.append(ref code, leftSpaceLevel + 1, ""); method.append(ref code, leftSpaceLevel, "}"); //foreach (var item in collection) } } else if (typeof(DataTable) == para.ParaType) { leftSpace = method.StartSpace + method.getSpace((int)leftSpaceLevel); method.append(ref code, LeftSpaceLevel.one, ""); method.append(ref code, LeftSpaceLevel.one, "{0} = null == {0} ? new System.Data.DataTable() : {0};", para.ParaName); method.append(ref code, LeftSpaceLevel.one, "System.Data.DataTable dtable = (System.Data.DataTable){0};", para.ParaName); method.append(ref code, LeftSpaceLevel.one, "EList<CKeyValue> tableColumns = new EList<CKeyValue>();"); method.append(ref code, LeftSpaceLevel.one, ""); method.append(ref code, leftSpaceLevel, "foreach(System.Data.DataColumn c in dtable.Columns)"); method.append(ref code, leftSpaceLevel, "{"); method.append(ref code, leftSpaceLevel + 1, "tableColumns.Add(new CKeyValue(){ Key = c.ColumnName.ToLower(), Value = c.ColumnName, other = c.DataType });"); method.append(ref code, leftSpaceLevel, "}"); method.append(ref code, leftSpaceLevel, ""); method.append(ref code, leftSpaceLevel, "foreach(System.Data.DataRow dr in dtable.Rows)"); method.append(ref code, leftSpaceLevel, "{"); //GetDbParaByDataRow(DataRow row, List<DbParameter> dbParas, EList<CKeyValue> sqlParaNameList, EList<CKeyValue> tableColumns) method.append(ref code, leftSpaceLevel + 1, "{0}.GetDbParaByDataRow(dr,{1},{2},tableColumns);", autoCallName, dbParaListVarName, sqlParasVarName); code += "\r\n" + executeDbHelper; method.append(ref code, leftSpaceLevel + 1, ""); method.append(ref code, leftSpaceLevel, "}");//foreach(var dr in dtable.Rows) } else { //单体复杂类型(数据实体) //object entity, List<DbParameter> dbParas, EList<CKeyValue> paraNameList method.append(ref code, LeftSpaceLevel.one, ""); method.append(ref code, LeftSpaceLevel.one, "//单体复杂类型(数据实体) "); method.append(ref code, LeftSpaceLevel.one, "{0}.GetDbParaListByEntity({1},{2},{3});", autoCallName, para.ParaName, dbParaListVarName, sqlParasVarName); method.append(ref code, LeftSpaceLevel.one, ""); } } } } if (string.IsNullOrEmpty(leftSpace)) { method.append(ref code, LeftSpaceLevel.one, ""); ExecuteSqlCode(method, LeftSpaceLevel.one, dataOptType, sqlVarName, dbParaListVarName, dbHelperVarName, resultVarName, ref code); } else { string code1 = ""; ExecuteSqlCode(method, LeftSpaceLevel.two, dataOptType, sqlVarName, dbParaListVarName, dbHelperVarName, resultVarName, ref code1); code = code.Replace(executeDbHelper, code1); } if (!string.IsNullOrEmpty(funcResultVarName)) { method.append(ref code, LeftSpaceLevel.one, ""); if (null == method.methodComponent.ActionType) { ReturnResult(method, LeftSpaceLevel.one, dataOptType, funcResultVarName, resultVarName, ref code); } else { method.append(ref code, LeftSpaceLevel.one, "{0} = {1};", funcResultVarName, resultVarName); } } return(code); }
void ExecuteSqlCode(MethodInformation method, LeftSpaceLevel leftSpaceLevel, DataOptType dataOptType, string sqlVarName, string paraListVarName, string dbHelperVarName, string returnVarName, ref string code) { if (DataOptType.select == dataOptType) { return; } //method.append(ref code, leftSpaceLevel, ""); string methodName = ""; if (DataOptType.none == method.sqlExecType) { switch (dataOptType) { case DataOptType.insert: methodName = "insert"; break; case DataOptType.update: methodName = "update"; break; case DataOptType.delete: methodName = "delete"; break; } } else { methodName = Enum.GetName(typeof(DataOptType), method.sqlExecType); } string autCall = method.AutoCallVarName; string enabledBuffer = method.methodComponent.EnabledBuffer.ToString().ToLower(); enabledBuffer = method.methodComponent.IsAsync ? "true" : enabledBuffer; method.append(ref code, leftSpaceLevel, "if(null != {0})", dbHelperVarName); method.append(ref code, leftSpaceLevel, "{"); if (DataOptType.select == method.sqlExecType || (DataOptType.procedure == dataOptType && DJTools.IsBaseType(method.methodComponent.ResultType))) { string dbTag = DJTools.GetParaTagByDbDialect(DataAdapter.dbDialect); method.append(ref code, leftSpaceLevel + 1, "{0} = {0}.Replace(\"{1}\", \"{2}\");", sqlVarName, procParaSign, dbTag); method.append(ref code, leftSpaceLevel + 1, "dbHelper.query({0}, {1}, {2}, {3}, dataTable =>", autCall, sqlVarName, paraListVarName, enabledBuffer); method.append(ref code, leftSpaceLevel + 1, "{"); #region ***** action method.append(ref code, leftSpaceLevel + 2, "dataTable = null == dataTable ? new System.Data.DataTable() : dataTable;"); method.append(ref code, leftSpaceLevel + 2, "if(0 < dataTable.Rows.Count)"); method.append(ref code, leftSpaceLevel + 2, "{"); method.append(ref code, leftSpaceLevel + 3, "string valStr = System.DBNull.Value == dataTable.Rows[0][0] ? \"\" : dataTable.Rows[0][0].ToString();"); if (baseTypeWithResult(method)) { method.append(ref code, leftSpaceLevel + 3, "int tempVal = 0;"); method.append(ref code, leftSpaceLevel + 3, "int.TryParse(valStr, out tempVal);"); method.append(ref code, leftSpaceLevel + 3, "{0} = tempVal;", returnVarName); } else if (typeof(string) == method.methodComponent.ResultType) { method.append(ref code, leftSpaceLevel + 3, "{0} = valStr;", returnVarName); } else { method.append(ref code, leftSpaceLevel + 3, "{0}.TryParse(valStr, out {1});", method.methodComponent.ResultType.FullName, returnVarName); } method.append(ref code, leftSpaceLevel + 2, "}"); method.append(ref code, leftSpaceLevel + 2, "else"); method.append(ref code, leftSpaceLevel + 2, "{"); method.append(ref code, leftSpaceLevel + 3, "{0} = 0;", returnVarName); method.append(ref code, leftSpaceLevel + 2, "}"); if (null != method.methodComponent.ActionType) { method.append(ref code, leftSpaceLevel + 2, "{0}({1});", method.methodComponent.ActionParaName, returnVarName); } #endregion method.append(ref code, leftSpaceLevel + 1, "}, ref err);"); } else { method.append(ref code, leftSpaceLevel + 1, "{0} += dbHelper.{1}({2}, {3}, {4},{5}, resultNum =>", returnVarName, methodName, autCall, sqlVarName, paraListVarName, enabledBuffer); method.append(ref code, leftSpaceLevel + 1, "{"); #region ***** action method.append(ref code, leftSpaceLevel + 2, "{0} += resultNum;", returnVarName); if (null != method.methodComponent.ActionType) { method.append(ref code, leftSpaceLevel + 2, "{0}(resultNum);", method.methodComponent.ActionParaName, returnVarName); } #endregion method.append(ref code, leftSpaceLevel + 1, "}, ref err);"); } method.append(ref code, leftSpaceLevel + 1, ""); method.append(ref code, leftSpaceLevel + 1, "if(!string.IsNullOrEmpty(err))"); method.append(ref code, leftSpaceLevel + 1, "{"); method.append(ref code, leftSpaceLevel + 2, "throw new Exception(err);"); method.append(ref code, leftSpaceLevel + 1, "}"); method.append(ref code, leftSpaceLevel, "}"); }
/// <summary> /// 执行 insert 操作 /// </summary> /// <param name="insertExpression">执行 insert 操作的sql语句</param> /// <param name="sqlExecType">sql 表达式执行类型</param> public AutoInsert(string insertExpression, DataOptType sqlExecType) : base() { sql = insertExpression; this.sqlExecType = sqlExecType; }
void UseSegmentToReplaceTagInSql(Para para, DataOptType dataOptType, string insertFields, string insertParas, string updateSets, string procParas, ref string sql) { if (!string.IsNullOrEmpty(insertFields)) { string FieldTag = ""; string fnStr = ""; string fn = ""; string Values = ""; Match mc = null; Regex rg = null; if (dataOptType == DataOptType.insert) { //insert into TableName ({ParameterNameOfMethod}) values //或 insert into TableName {ParameterNameOfMethod} values //或 insert into TableName ({ParameterNameOfMethod}) //或 insert into TableName {ParameterNameOfMethod} rg = new Regex(@"insert\s+(into\s+)?[a-z0-9_\-]+\s*(?<FieldTag>((\(\{" + para.ParaName + @"\}\))|(\{" + para.ParaName + @"\})))(\s+(?<Values>values[^a-z0-9_]))?", RegexOptions.IgnoreCase); if (rg.IsMatch(sql)) { mc = rg.Match(sql); fn = mc.Groups[0].Value; FieldTag = mc.Groups["FieldTag"].Value; Values = mc.Groups["Values"].Value; fnStr = fn.Replace(FieldTag, "(" + insertFields + ")"); if (string.IsNullOrEmpty(Values)) { fnStr += " values "; } } if (string.IsNullOrEmpty(fnStr)) { //insert into TableName values ({ParameterNameOfMethod}) //insert into TableName values {ParameterNameOfMethod} rg = new Regex(@"insert\s+(into\s+)?(?<FieldTag>[a-z0-9_\-]+)(?<Values>\s+values)((\s*\(\s*\{" + para.ParaName + @"\}\s*\))|(\s*\{" + para.ParaName + @"\}))", RegexOptions.IgnoreCase); if (rg.IsMatch(sql)) { mc = rg.Match(sql); fn = mc.Groups[0].Value; FieldTag = mc.Groups["FieldTag"].Value; Values = mc.Groups["Values"].Value; fnStr = fn.Replace(" " + FieldTag + Values, " " + FieldTag + "(" + insertFields + ") values"); } } if (string.IsNullOrEmpty(fnStr)) { return; } sql = sql.Replace(fn, fnStr); fn = ""; fnStr = ""; // values ({ParameterNameOfMethod}) rg = new Regex(@"\s+values\s*(?<FieldTag>((\(\{" + para.ParaName + @"\}\))|(\{" + para.ParaName + @"\})))?(?<TagSign>\s*[^\s])?", RegexOptions.IgnoreCase); if (rg.IsMatch(sql)) { mc = rg.Match(sql); fn = mc.Groups[0].Value; FieldTag = mc.Groups["FieldTag"].Value; string TagSign = mc.Groups["TagSign"].Value; if (!string.IsNullOrEmpty(TagSign)) { fn = fn.Substring(0, fn.Length - TagSign.Length); } if (!string.IsNullOrEmpty(FieldTag)) { fnStr = fn.Replace(FieldTag, "(" + insertParas + ")"); } else { string end = string.IsNullOrEmpty(TagSign) ? "" : " "; fnStr = fn + "(" + insertParas + ")" + end; } } if (string.IsNullOrEmpty(fnStr)) { return; } sql = sql.Replace(fn, fnStr); } else if (dataOptType == DataOptType.update) { //update rg = new Regex(@"update\s+[a-z0-9_\-]+\s+set\s*(?<FieldTag>\{" + para.ParaName + @"\})", RegexOptions.IgnoreCase); if (rg.IsMatch(sql)) { mc = rg.Match(sql); FieldTag = mc.Groups["FieldTag"].Value; } if (string.IsNullOrEmpty(FieldTag)) { return; } sql = sql.Replace(FieldTag, updateSets); } else if (dataOptType == DataOptType.procedure) { //procedure rg = new Regex(@"(?<FieldTag>\{" + para.ParaName + @"\})", RegexOptions.IgnoreCase); if (rg.IsMatch(sql)) { mc = rg.Match(sql); FieldTag = mc.Groups["FieldTag"].Value; } if (string.IsNullOrEmpty(FieldTag)) { return; } sql = sql.Replace(FieldTag, procParas); } } }
public AutoDelete(string deleteExpression, DataOptType sqlExecType, bool EnabledBuffer) : base() { sql = deleteExpression; this.sqlExecType = sqlExecType; this.EnabledBuffer = EnabledBuffer; }
/// <summary> /// 当执行接口方法时,根据数据提供者获取sql语句表达式(动态创建sql语句) /// </summary> /// <param name="dataProvider">sql语句数据提供者</param> /// <param name="paraList">接口方法参数集合</param> /// <param name="dbParameters">sql语句参数集合</param> /// <param name="autoCall">AutoCall对象</param> /// <param name="dataOptType">数据操作类型select|insert|update|delete</param> /// <param name="sql">返回sql语句提供者动态生成的sql语句</param> public void GetSqlByDataProvider(ISqlExpressionProvider dataProvider, PList <Para> paraList, DbList <DbParameter> dbParameters, AutoCall autoCall, DataOptType dataOptType, ref string sql) { if (null != dataProvider) { int ncount = paraList.Count; object[] paras = new object[ncount]; int n = 0; foreach (Para p in paraList) { paras[n] = p.ParaValue; n++; } MethodInfo m = typeof(ISqlExpressionProvider).GetMethod("provideSql"); try { object v = m.Invoke(dataProvider, new object[] { dbParameters, dataOptType, paraList, paras }); if (null != v) { sql = v.ToString(); } } catch (Exception ex) { autoCall.ExecuteExcption(typeof(ISqlExpressionProvider), null, "provideSql", paraList, ex); } } }
/// <summary> /// 执行select、insert、update、delete数据操作时被调用 /// </summary> /// <param name="method">接口方法信息对象</param> /// <param name="dataOptType">数据操作类型select|insert|update|delete</param> /// <param name="sql">sql语句表达式</param> /// <param name="code">接口方法代码相关代码字符串</param> protected void ExecInterfaceMethodOfCodeStr_DataOpt(MethodInformation method, DataOptType dataOptType, string sql, ref string code) { StackTrace stackTrace = new StackTrace(); Type type = stackTrace.GetFrame(1).GetMethod().DeclaringType; if (null == type.GetInterface("IDataInterface")) { e("调用该方法的类必须实例接口类 IDataInterface", ErrorLevels.severe); throw new Exception("调用该方法的类必须实例接口类 IDataInterface"); } string sqlVarName = "sql"; DynamicCodeChange dynamicCodeChange = new DynamicCodeChange(); try { dynamicCodeChange.AnalyzeSql(method, dataOptType, sqlVarName, ref sql); } catch (Exception ex) { e(ex.ToString(), ErrorLevels.severe); throw ex; } code = dynamicCodeAutoCall.ExecReplaceForSqlByFieldName(sql, sqlVarName, method); string paraListVarName = "null"; dynamicCodeAutoCall.DataProviderCode(sqlVarName, method, dataOptType, ref code, ref paraListVarName); if (string.IsNullOrEmpty(code) && string.IsNullOrEmpty(sql)) { e("没有提供任何执行语句", ErrorLevels.severe); throw new Exception("没有提供任何执行语句"); } string code1 = ""; if (dataOptType == DataOptType.select || dataOptType == DataOptType.count || DataOptType.procedure == dataOptType) { code1 = dynamicCodeAutoCall.GetParametersBySqlParameter(sql, method, ref paraListVarName); appendCode(method, code1, ref code); dynamicCodeAutoCall.MadeExecuteSql(sqlVarName, paraListVarName, method, dataOptType, ref code); } else { code1 = dynamicCodeChange.GetParametersBySqlParameter(sql, sqlVarName, method, dataOptType, ref paraListVarName); appendCode(method, code1, ref code); } }
/// <summary> /// 执行 update 操作 /// </summary> /// <param name="updateExpression">执行 update 操作的sql语句</param> /// <param name="fields">执行 update 操作时必须排除的字段名称</param> /// <param name="fieldsType">指示字段名称集合类型是 Exclude(排除) 或 Contain(包含), 默认为 Exclude</param> /// <param name="sqlExecType">sql 表达式执行类型</param> public AutoUpdate(string updateExpression, string[] fields, FieldsType fieldsType, DataOptType sqlExecType) : base() { sql = updateExpression; this.fields = fields; this.fieldsType = fieldsType; this.sqlExecType = sqlExecType; }
/// <summary> /// 执行 update 操作 /// </summary> /// <param name="updateExpression">执行 update 操作的sql语句</param> /// <param name="sqlExecType">sql 表达式执行类型</param> public AutoUpdate(string updateExpression, DataOptType sqlExecType) : base() { sql = updateExpression; this.sqlExecType = sqlExecType; }
/// <summary> /// 指定一个生成sql语句的提供者类, 需要指定该所在的命名空间及类名 /// </summary> /// <param name="dataProviderNamespace">提供sql语句类所在的命名空间</param> /// <param name="dataProviderClassName">提供sql语句类的类名</param> /// <param name="sqlExecType">sql 表达式执行类型</param> public AutoDelete(string dataProviderNamespace, string dataProviderClassName, DataOptType sqlExecType) : base() { this.dataProviderNamespace = dataProviderNamespace; this.dataProviderClassName = dataProviderClassName; this.sqlExecType = sqlExecType; }
/// <summary> /// 解析 insert / update 与接口方法参数名称对应的sql语句, 注:该参数必须是一个数据实体List或是单个数据实体, /// 例: insert into UserInfo values({UserInfos}), update UserInfo set {UserInfos} where id=@id /// {UserInfos} -- UserInfos 对应方法参数名称,例: int insert(List<UserInfo> UserInfos) /// </summary> /// <param name="method"></param> /// <param name="dataOptType"></param> /// <param name="sqlVarName"></param> /// <param name="sql"></param> public void AnalyzeSql(MethodInformation method, DataOptType dataOptType, string sqlVarName, ref string sql) { if (string.IsNullOrEmpty(sql)) { return; } if (dataOptType == DataOptType.select || dataOptType == DataOptType.delete) { return; } AuthenticateSql(ref sql); string sql1 = sql.ToLower(); string fn = ""; PList <Para> paras = method.paraList; Para para = null; foreach (Para item in paras) { if (DJTools.IsBaseType(item.ParaType)) { continue; } fn = "{" + item.ParaName.ToLower() + "}"; if (-1 != sql1.IndexOf(fn)) { fn = "{" + item.ParaName + "}"; para = item; break; } } if (null == para) { return; } string dbTag = DJTools.GetParaTagByDbDialect(DataAdapter.dbDialect); string insertFields = ""; string insertParas = ""; string updateSets = ""; string procParas = ""; if (dataOptType == DataOptType.insert) { Regex regex = new Regex(@"[0-9a-z_]+\s*\((?<insertFields>[0-9a-z_\[\]\,\s]+)\)", RegexOptions.IgnoreCase); if (regex.IsMatch(sql1)) { insertFields = regex.Match(sql1).Groups["insertFields"].Value; string[] arr = null; string fn1 = ""; if (-1 != insertFields.IndexOf(",")) { arr = insertFields.Split(','); } else { arr = new string[] { insertFields }; } foreach (var item in arr) { fn1 = item.Trim(); fn1 = fn1.Replace("[", ""); fn1 = fn1.Replace("]", ""); insertParas += "," + dbTag + fn1; } if (!string.IsNullOrEmpty(insertParas)) { insertParas = insertParas.Substring(1); sql = sql.Replace(fn, insertParas); return; } } } Type dataType = GetDataTypeByPara(para, fn); if (null != dataType) { if (DJTools.IsBaseType(dataType)) { return; } GetSegmentFromSql(method, dataType, ref insertFields, ref insertParas, ref updateSets, ref procParas); UseSegmentToReplaceTagInSql(para, dataOptType, insertFields, insertParas, updateSets, procParas, ref sql); } }