private APGenTable[] GetAllTables(APGenBusinessModelSection businessModel) { APGenTable[] tables = new APGenTable[businessModel.Tables.Count]; businessModel.Tables.CopyTo(tables, 0); return tables; }
private void CreateTable(APDatabase db, APGenTable table) { _createTable(db, table); _createPrimaryKey(db, table); foreach (APGenIndex index in table.Indexes) { _createIndex(db, table, index); } foreach (APGenIndex unique in table.Uniques) { _createUnique(db, table, unique); } }
//static string currentIdNewIdProc = "ap_Query_NewId"; private APGenTable[] GetAllTables(APGenBusinessModelSection businessModel) { // CurrentId table also include in. APGenTable tableCurrentId = new APGenTable() { Name = currentIdTable, TableName = currentIdTable }; tableCurrentId.Columns.Add(new APGenColumn() { Name = currentIdName, ColumnName = currentIdName, PrimaryKey = true, IsNullable = false, DBType = DbType.String, DataLength = 512 }); tableCurrentId.Columns.Add(new APGenColumn() { Name = currentIdValue, ColumnName = currentIdValue, IsNullable = false, DBType = DbType.Int64 }); APGenTable[] tables = new APGenTable[businessModel.Tables.Count + 1]; tables[0] = tableCurrentId; businessModel.Tables.CopyTo(tables, 1); return tables; }
private void _createUnique(APDatabase db, APGenTable table, APGenIndex index) { StringBuilder sb = new StringBuilder(); sb.AppendFormat("alter table {0} add constraint {1} unique (", table.TableName, index.Name/* UQ_name(table, index)*/); foreach (APGenOrder order in index.Orders) { sb.AppendFormat("\r\n\t{0} {1},", table.Columns[order.Name].ColumnName, order.According.ToString()); } sb.Length--; sb.Append("\r\n)"); // alter table table_name add constraint uq_name ( // column_name DESC, // ... // ) DbCommand dbCmd = db.CreateSqlCommand(sb.ToString()); dbCmd.ExecuteNonQuery(); }
private void _dropConstraint(APDatabase db, APGenTable table, string name) { DbCommand dbCmd = db.CreateSqlCommand("alter table {0} drop constraint {1}", table.TableName, name); dbCmd.ExecuteNonQuery(); }
//private string IX_name(APGenTable table, APGenIndex index) //{ // string ix = "IX"; // foreach (APGenOrder order in index.Orders) // { // ix += "_" + table.Columns[order.Name].ColumnName; // } // return ix; //} //private string UQ_name(APGenTable table, APGenIndex index) //{ // string ix = "UQ"; // foreach (APGenOrder order in index.Orders) // { // ix += "_" + table.Columns[order.Name].ColumnName; // } // return ix; //} private string PK_name(APGenTable table) { return "PK_" + table.TableName; }
private void CreateTableDef(CodeTypeDeclaration ctd, APGenTable table, bool isView) { // add tableDef CodeTypeDeclaration tableDel = NewClass(table.TableDefName, TypeAttributes.Public, null); tableDel.IsPartial = true; tableDel.BaseTypes.Add(TypeRef("APTableDef")); tableDel.CustomAttributes.Add(AttrDecl(TypeRef("Serializable"))); ctd.Members.Add(tableDel); CodeConstructor ctor = NewCtor(MemberAttributes.Public, null, Param(TypeRef(typeof(string)), "tableName")); ctor.BaseConstructorArgs.Add(ParamRef("tableName")); tableDel.Members.Add(ctor); ctor = NewCtor(MemberAttributes.Family, null, Param(TypeRef(typeof(string)), "tableName"), Param(TypeRef(typeof(string)), "alias")); ctor.BaseConstructorArgs.Add(ParamRef("tableName")); ctor.BaseConstructorArgs.Add(ParamRef("alias")); tableDel.Members.Add(ctor); // all APColumnDef // foreach (APGenColumn column in table.Columns) { CodeTypeReference tr = ColumnDefType; Type type = column.ParsedType; bool needLength = false; bool needPrecision = false; if (type != null) { if (type.IsGenericType && type.IsValueType) type = Nullable.GetUnderlyingType(type); if (type.IsPrimitive) { tr = TypeRef(type.Name + "APColumnDef"); if (type == typeof(string) || type == typeof(byte[])) needLength = true; else if (type == typeof(decimal)) needPrecision = true; } else if (type.IsEnum) { tr = TypeTRef("EnumAPColumnDef", column.TypeRef); } else if (type == typeof(Guid)) { tr = TypeRef("GuidAPColumnDef"); } else if (type == typeof(String)) { tr = TypeRef("StringAPColumnDef"); needLength = true; } else if (type == typeof(DateTime)) { tr = TypeRef("DateTimeAPColumnDef"); } else if (type == typeof(Decimal)) { tr = TypeRef("DecimalAPColumnDef"); needPrecision = true; } else if (type == typeof(byte[])) { tr = TypeRef("BytesAPColumnDef"); needLength = true; } } else if (column.IsEnum) { tr = TypeTRef("EnumAPColumnDef", column.TypeRef); } column.DefRef = tr; CodeMemberField fieldColumnDef = NewMemberField(column.FieldName, tr, MemberAttributes.Private, null); tableDel.Members.Add(fieldColumnDef); CodeMemberProperty columnProp = NewMemberProperty(column.PropertyName, tr, MemberAttributes.Public, column.Name + " ColumnDef"); CodeConditionStatement condColumn = If(MethodInvoke("Object", "ReferenceEquals", FieldRef(column.FieldName), Null())); CodeExpression initColumn = New(tr, This(), column.ColumnExp, Const(column.IsNullable)); if (needLength) { (initColumn as CodeObjectCreateExpression).Parameters.Add(Const(column.DataLength)); } else if (needPrecision) { (initColumn as CodeObjectCreateExpression).Parameters.Add(Const(column.Precision)); (initColumn as CodeObjectCreateExpression).Parameters.Add(Const(column.Scale)); } condColumn.TrueStatements.Add(Let(FieldRef(column.FieldName), initColumn)); condColumn.TrueStatements.Add(Let(PropRef(FieldRef(column.FieldName), "Display"), Const(column.Display == String.Empty ? column.ColumnName : column.Display))); if (column.Required) condColumn.TrueStatements.Add(Let(PropRef(FieldRef(column.FieldName), "Required"), Const(true))); columnProp.GetStatements.Add(condColumn); columnProp.GetStatements.Add(Return(FieldRef(column.FieldName))); tableDel.Members.Add(columnProp); } CodeExpression init = null; foreach (APGenIndex index in table.Indexes) { CodeExpression[] array = new CodeExpression[index.Orders.Count]; for (int i = 0; i < index.Orders.Count; i++) { APGenOrder order = index.Orders[i]; array[i] = PropRef(PropRef(order.Name), order.According == APSqlOrderAccording.Asc ? "Asc" : "Desc"); } CodeMemberProperty propOrder = NewMemberProperty(index.Name, OrderPhraseType, MemberAttributes.Public, index.Name + " OrderByDef"); propOrder.GetStatements.Add(Return( PropRef(New(OrderByClauseType, array), "Next") )); tableDel.Members.Add(propOrder); if (index.IsDefault && init == null) { init = PropRef(index.Name); } } CodeMemberProperty defaultOrder = NewMemberProperty("DefaultOrder", OrderPhraseType, MemberAttributes.Public, "Default Index"); if (init == null) defaultOrder.GetStatements.Add(Return(Null())); else defaultOrder.GetStatements.Add(Return(init)); tableDel.Members.Add(defaultOrder); CodeMemberMethod as_ = NewMemberMethod("As", MemberAttributes.Public, "Create a alias table", Param(typeof(string), "name")); tableDel.Members.Add(as_); as_.ReturnType = TypeRef(table.TableDefName); as_.Statements.Add(Return(New(TypeRef(table.TableDefName), Const(table.TableName), ParamRef("name")))); foreach (APGenAlias alias in table.Aliases) { CodeMemberField aliasField = NewMemberField(alias.FieldName, TypeRef(table.TableDefName), MemberAttributes.Private | MemberAttributes.Static, null); tableDel.Members.Add(aliasField); CodeMemberProperty aliasProp = NewMemberProperty(alias.Name, TypeRef(table.TableDefName), MemberAttributes.Public, "Alias table " + alias.Name); aliasProp.GetStatements.Add(If(Equals(FieldRef(alias.FieldName), Null()), Let(FieldRef(alias.FieldName), MethodInvoke("As", Const(alias.Name))))); aliasProp.GetStatements.Add(Return(FieldRef(alias.FieldName))); tableDel.Members.Add(aliasProp); } CodeMemberField fieldTableDef = NewMemberField(table.FieldName, TypeRef(table.TableDefName), MemberAttributes.Private | MemberAttributes.Static, null); ctd.Members.Add(fieldTableDef); CodeMemberProperty propTableDef = NewMemberProperty(table.ClassName, TypeRef(table.TableDefName), MemberAttributes.Public | MemberAttributes.Static, table.Comment + " TableDef"); propTableDef.GetStatements.Add(If(Equals(FieldRef(table.FieldName), Null()), Let(FieldRef(table.FieldName), New(TypeRef(table.TableDefName), table.TableExp)))); propTableDef.GetStatements.Add(Return(FieldRef(table.FieldName))); ctd.Members.Add(propTableDef); #region [ Map ] CodeParameterDeclarationExpression dataDef = Param(table.DataType, "data"); CodeArgumentReferenceExpression dataRef = ParamRef("data"); CodeTypeReference boolDef = TypeRef(typeof(bool)); CodeParameterDeclarationExpression throwDef = Param(boolDef, "throwIfValidColumnName"); CodeArgumentReferenceExpression throwRef = ParamRef("throwIfValidColumnName"); CodeTypeReference listType = TypeTRef("List", table.DataType); // Fullup CodeMemberMethod mapFull = NewMemberMethod(fullupMethodName, MemberAttributes.Public, APResource.APBusiness_MapComment, Param(DataReaderType, "reader"), dataDef, throwDef); tableDel.Members.Add(mapFull); CodePropertyReferenceExpression tableRef = PropRef(DBDef, table.ClassName); foreach (APGenColumn column in table.Columns) { if (column.DefaultValue != "") { mapFull.Statements.Add(Let(FieldRef(dataRef, column.PropertyName), MethodInvoke( MethodRef(PropRef(column.PropertyName), "GetValue", column.TypeRef), ParamRef("reader"), throwRef, Special(column.DefaultValue)))); } else { mapFull.Statements.Add(Let(FieldRef(dataRef, column.PropertyName), MethodInvoke( MethodRef(PropRef(column.PropertyName), "GetValue", column.TypeRef), ParamRef("reader"), throwRef))); } } // Map CodeMemberMethod map = NewMemberMethod(mapMethodName, MemberAttributes.Public, APResource.APBusiness_MapComment, Param(DataReaderType, "reader")); tableDel.Members.Add(map); map.ReturnType = table.DataType; map.Statements.Add(VarDecl(table.DataType, "data", New(table.DataType))); map.Statements.Add(MethodInvoke(fullupMethodName, ParamRef("reader"), dataRef, Const(true))); map.Statements.Add(Return(dataRef)); // TolerantMap CodeMemberMethod tolerantMap = NewMemberMethod(tolerantMapMethodName, MemberAttributes.Public, APResource.APBusiness_MapComment, Param(DataReaderType, "reader")); tableDel.Members.Add(tolerantMap); tolerantMap.ReturnType = table.DataType; tolerantMap.Statements.Add(VarDecl(table.DataType, "data", New(table.DataType))); tolerantMap.Statements.Add(MethodInvoke(fullupMethodName, ParamRef("reader"), dataRef, Const(false))); tolerantMap.Statements.Add(Return(dataRef)); // MapList { CodeMemberMethod mapList = NewMemberMethod(mapListMethodName, MemberAttributes.Public, APResource.APBusiness_MapComment, Param(DataReaderType, "reader")); tableDel.Members.Add(mapList); mapList.ReturnType = listType; mapList.Statements.Add(VarDecl(listType, "list", New(listType))); // try ... finally ... CodeVariableReferenceExpression reader = Local("reader"); CodeTryCatchFinallyStatement _try; mapList.Statements.Add(_try = Try()); CodeIterationStatement s = new CodeIterationStatement(); _try.TryStatements.Add( For(Eval(Special("")), MethodInvoke(reader, "Read"), Eval(Special("")), Eval(MethodInvoke(Local("list"), "Add", MethodInvoke(mapMethodName, reader))))); _try.FinallyStatements.Add(MethodInvoke(reader, "Close")); mapList.Statements.Add(Return(Local("list"))); } // TolerantMapList { CodeMemberMethod tolerantMapList = NewMemberMethod(tolerantMapListMethodName, MemberAttributes.Public, APResource.APBusiness_MapComment, Param(DataReaderType, "reader")); tableDel.Members.Add(tolerantMapList); tolerantMapList.ReturnType = listType; tolerantMapList.Statements.Add(VarDecl(listType, "list", New(listType))); // try ... finally ... CodeVariableReferenceExpression reader = Local("reader"); CodeTryCatchFinallyStatement _try; tolerantMapList.Statements.Add(_try = Try()); CodeIterationStatement s = new CodeIterationStatement(); _try.TryStatements.Add( For(Eval(Special("")), MethodInvoke(reader, "Read"), Eval(Special("")), Eval(MethodInvoke(Local("list"), "Add", MethodInvoke(tolerantMapMethodName, reader))))); _try.FinallyStatements.Add(MethodInvoke(reader, "Close")); tolerantMapList.Statements.Add(Return(Local("list"))); } #endregion }
private Dictionary<string, indexinfo> _getIndexes(APDatabase db, APGenTable table) { DbCommand dbCmd = db.CreateSqlCommand( @"select idx.name, col.name as col, idxCol.is_descending_key, idx.is_unique, idx.is_primary_key, idx.is_unique_constraint from sys.indexes as idx inner join sys.index_columns as idxCol on (idx.object_id = idxCol.object_id AND idx.index_id = idxCol.index_id) inner join sys.columns as col on (idx.object_id = col.object_id AND idxCol.column_id = col.column_id) where idx.object_id = object_id('{0}') order by idx.name", table.TableName); Dictionary<string, indexinfo> dbIndexes = new Dictionary<string, indexinfo>(); using (IDataReader reader = dbCmd.ExecuteReader()) { while (reader.Read()) { string name = Convert.ToString(reader.GetValue(0)); string col = Convert.ToString(reader.GetValue(1)); bool is_descending_key = Convert.ToBoolean(reader.GetValue(2)); bool is_unique = Convert.ToBoolean(reader.GetValue(3)); bool is_primary_key = Convert.ToBoolean(reader.GetValue(4)); bool is_unique_constraint = Convert.ToBoolean(reader.GetValue(5)); indexinfo data; if (dbIndexes.ContainsKey(name)) { data = dbIndexes[name]; } else { data = new indexinfo() { indname = name }; if (is_primary_key) data.indtype = indexType.Primary; else if (is_unique_constraint) data.indtype = indexType.Unique; else data.indtype = indexType.Index; dbIndexes.Add(name, data); } data.columns.Add(col, is_descending_key); } } foreach (var item in dbIndexes.Values) { item.pickKeys(); } return dbIndexes; }
private string DF_constraint(APGenTable table, APGenColumn column) { if (column.DBDefaultValue != "") return String.Format("constraint {0} default {1}", DF_name(table, column), column.DBDefaultValue); return ""; }
private void _alterColumn(APDatabase db, APGenTable table, APGenColumn column, columninfo info) { if (info.dfname != "") _dropConstraint(db, table, info.dfname); DbCommand dbCmd; // no safe mode to change identity, so ingone this, throw sql exception. if (info.isnullable && !column.IsNullable) { dbCmd = db.CreateSqlCommand("select count(*) from {0} where {1} is null", table.TableName, column.ColumnName); if ((int)dbCmd.ExecuteScalar() > 0) { // when column nullable change to not nullable and has data, // set default value. dbCmd = db.CreateSqlCommand("update {0} set {1} = {2} where {1} is null", table.TableName, column.ColumnName, info.GetDefaultValue()); dbCmd.ExecuteNonQuery(); } } dbCmd = db.CreateSqlCommand("alter table {0} alter column {1} {2} {3}", table.TableName, column.ColumnName, DBTypeName(column), IsNullableString(column)); dbCmd.ExecuteNonQuery(); if (column.DBDefaultValue != "") { dbCmd = db.CreateSqlCommand("alter table {0} add {1} for {2}", table.TableName, DF_constraint(table, column), column.ColumnName); dbCmd.ExecuteNonQuery(); } // alter table table_nae alter column column_name type_name [not] null // go // alter table add constraint DF_tablename_columnname default dfvalue for column_name // go }
private void CreateDal(CodeTypeDeclaration cns, APGenTable table, bool isView) { CodeTypeDeclaration ctd; ctd = NewClass(table.DalInheritFromBase ? table.DalBaseName : table.DalName, TypeAttributes.Public, table.Comment + (table.DalInheritFromBase ? " DalBase" : " Dal")); ctd.IsPartial = true; ctd.BaseTypes.Add(DalType); cns.Members.Add(ctd); // constructors // CodeConstructor ctor1 = NewCtor(MemberAttributes.Public, null); ctd.Members.Add(ctor1); CodeConstructor ctor2 = NewCtor(MemberAttributes.Public, null, Param(DatabaseType, "db")); ctor2.BaseConstructorArgs.Add(ParamRef("db")); ctd.Members.Add(ctor2); // if FromBase // if (table.DalInheritFromBase) { CodeTypeDeclaration ctd_ex; ctd_ex = NewClass(table.DalName, TypeAttributes.Public, table.Comment + " Dal"); ctd_ex.IsPartial = true; ctd_ex.BaseTypes.Add(TypeRef(table.DalBaseName)); cns.Members.Add(ctd_ex); // constructors // CodeConstructor ctor_ex1 = NewCtor(MemberAttributes.Public, null); ctd_ex.Members.Add(ctor_ex1); CodeConstructor ctor_ex2 = NewCtor(MemberAttributes.Public, null, Param(DatabaseType, "db")); ctor_ex2.BaseConstructorArgs.Add(ParamRef("db")); ctd_ex.Members.Add(ctor_ex2); } if (!isView) { // insert method // CreateDalInsert(ctd, table, isView); // update method // CreateDalUpdate(ctd, table, isView); // update partial method // CreateDalUpdatePartial(ctd, table, isView); // primary delete method // CreateDalPrimaryDelete(ctd, table, isView); // condition delete method // CreateDalConditionDelete(ctd, table, isView); } // condition query count // CreateDalConditionQueryCount(ctd, table, isView); // primary get method // CreateDalPrimaryGet(ctd, table, isView); // condition query // CreateDalConditionQuery(ctd, table, isView); // misc methods // CreateDalMisc(ctd, table, isView); }
private void CreateDalProperty(CodeTypeDeclaration ctd, APGenTable table, bool isView) { CodeTypeReference dalType = TypeRef(DalDefName + "." + table.DalName); string fieldName = table.FieldName + "Dal"; CodeMemberField field = NewMemberField(fieldName, dalType, MemberAttributes.Private, null); ctd.Members.Add(field); CodeMemberProperty prop = NewMemberProperty(table.ClassName + "Dal", dalType, MemberAttributes.Public, table.Comment + " Dal"); prop.GetStatements.Add(If(Equals(FieldRef(fieldName), Null()), Let(FieldRef(fieldName), New(dalType, This())))); prop.GetStatements.Add(Return(FieldRef(fieldName))); ctd.Members.Add(prop); }
private Dictionary<string, indexinfo> _getIndexes(APDatabase db, APGenTable table) { OracleCommand dbCmd = db.CreateSqlCommand( @"select col.index_name, col.column_name, expr.column_expression, col.descend, nvl(cst.constraint_type,'C') from user_ind_columns col left join user_ind_expressions expr on col.index_name=expr.index_name and col.table_name=expr.table_name and col.column_position=expr.column_position left join user_constraints cst on col.table_name=cst.table_name and col.index_name=cst.constraint_name where col.table_name = '{0}' order by col.index_name, col.column_position", table.TableName.ToUpper()) as OracleCommand; dbCmd.InitialLONGFetchSize = -1; Dictionary<string, indexinfo> dbIndexes = new Dictionary<string, indexinfo>(StringComparer.InvariantCultureIgnoreCase); using (OracleDataReader reader = dbCmd.ExecuteReader()) { while (reader.Read()) { string name = Convert.ToString(reader.GetValue(0)); string col = Convert.ToString(reader.GetValue(1)); if (!reader.IsDBNull(2)) { col = reader.GetString(2); col = col.Substring(1, col.Length - 2); } bool is_descending_key = Convert.ToString(reader.GetValue(3)) == "DESC"; string type = Convert.ToString(reader.GetValue(4)); indexinfo data; if (dbIndexes.ContainsKey(name)) { data = dbIndexes[name]; } else { data = new indexinfo() { indname = name }; if (type == "P") data.indtype = indexType.Primary; else if (type == "U") data.indtype = indexType.Unique; else data.indtype = indexType.Index; dbIndexes.Add(name, data); } data.columns.Add(col, is_descending_key); } } foreach (var item in dbIndexes.Values) { item.pickKeys(); } return dbIndexes; }
private Dictionary<string, columninfo> _getColumns(APDatabase db, APGenTable table) { OracleCommand dbCmd = db.CreateSqlCommand( @"select column_id, column_name, data_type, data_length, nvl(data_precision, 0), nvl(data_scale, 0), nullable, nvl(default_length, 0), data_default from user_tab_columns where table_name = '{0}' order by column_id", table.TableName.ToUpper()) as OracleCommand; dbCmd.InitialLONGFetchSize = -1; Dictionary<string, columninfo> dbColumns = new Dictionary<string, columninfo>(StringComparer.InvariantCultureIgnoreCase); using (OracleDataReader reader = dbCmd.ExecuteReader()) { while (reader.Read()) { int idx = 0; columninfo data = new columninfo(){ colid = Convert.ToInt32(reader.GetValue(idx++)), colname = Convert.ToString(reader.GetValue(idx++)), typename = Convert.ToString(reader.GetValue(idx++)).ToLower(), length = Convert.ToInt32(reader.GetValue(idx++)), xprec = Convert.ToInt32(reader.GetValue(idx++)), xscale = Convert.ToInt32(reader.GetValue(idx++)), isnullable = Convert.ToString(reader.GetValue(idx++)) == "Y", dflength = Convert.ToInt32(reader.GetValue(idx++)), dfvalue = "", }; if (data.dflength > 0) data.dfvalue = reader.GetString(idx++).Trim(); data.Resolve(); dbColumns.Add(data.colname, data); } } return dbColumns; }
private void _createColumn(APDatabase db, APGenTable table, APGenColumn column, bool isTableEmpty) { string sql = ""; if (column.IdentityType == APColumnIdentityType.Database) ThrowDBUnsupport("identityType=\"Database\""); else sql = string.Format("alter table {0} add {1} {2} {3} {4}", table.TableName, column.ColumnName, DBTypeName(column), DF_constraint(table, column), IsNullableString(column)); DbCommand dbCmd = db.CreateSqlCommand(sql); dbCmd.ExecuteNonQuery(); }
private void _alterColumn(APDatabase db, APGenTable table, APGenColumn column, columninfo info) { DbCommand dbCmd; int totalCount, nullCount = 0; dbCmd = db.CreateSqlCommand("select count(*) from {0}", table.TableName, column.ColumnName); totalCount = Convert.ToInt32(dbCmd.ExecuteScalar()); if (totalCount > 0) { dbCmd = db.CreateSqlCommand("select count(*) from {0} where {1} is null", table.TableName, column.ColumnName); nullCount = Convert.ToInt32(dbCmd.ExecuteScalar()); } if (totalCount > 0) { if (!_sameType(DBTypeName(column), info.GetTypeFullName()) && nullCount != totalCount) { // change db type, the column value must be null if (!info.isnullable) { dbCmd = db.CreateSqlCommand("alter table {0} modify {1} null", table.TableName, column.ColumnName); dbCmd.ExecuteNonQuery(); info.isnullable = true; } _tempSql(String.Format("update {0} set {1} = null where {1} is not null", table.TableName, column.ColumnName)); nullCount = totalCount; } } string sqlPadding = ""; if (DBTypeName(column) != info.GetTypeFullName()) sqlPadding += " " + DBTypeName(column); if (column.DBDefaultValue != info.dfvalue) sqlPadding += " " + DF_constraint(table, column); bool lazyNotNullable = false; if (column.IsNullable != info.isnullable) { if (column.IsNullable || nullCount == 0) sqlPadding += " " + IsNullableString(column); else lazyNotNullable = true; } if (sqlPadding != "") { dbCmd = db.CreateSqlCommand("alter table {0} modify {1}", table.TableName, column.ColumnName); dbCmd.CommandText += sqlPadding; dbCmd.ExecuteNonQuery(); } if (lazyNotNullable) { string dfv = column.DBDefaultValue; if (dfv == "") dfv = "0"; _tempSql(String.Format("update {0} set {1} = {2} where {1} is null", table.TableName, column.ColumnName, dfv)); dbCmd = db.CreateSqlCommand("alter table {0} modify {1} not null", table.TableName, column.ColumnName); dbCmd.ExecuteNonQuery(); } // alter table table_nae modify column_name type_name default dfvalue [not] null // go }
private void _dropIndex(APDatabase db, APGenTable table, indexinfo info) { if (info.indtype != indexType.Index) { _dropConstraint(db, table, info.indname); } else { DbCommand dbCmd = db.CreateSqlCommand("drop index {1} on {0}", table.TableName, info.indname); dbCmd.ExecuteNonQuery(); } }
private bool _isTableEmpty(APDatabase db, APGenTable table) { DbCommand dbCmd = db.CreateSqlCommand( @"select count(*) from {0}", table.TableName); int count = Convert.ToInt32(dbCmd.ExecuteScalar()); return count == 0; }
private void _dropColumn(APDatabase db, APGenTable table, columninfo info) { if (info.dfname != "") _dropConstraint(db, table, info.dfname); DbCommand dbCmd = db.CreateSqlCommand("alter table {0} drop column {1}", table.TableName, info.colname); dbCmd.ExecuteNonQuery(); }
private void CreateData(CodeNamespace cns, APGenTable table, bool isView) { CodeTypeDeclaration ctd; ctd = NewClass(table.DataInheritFromBase ? table.DataBaseName : table.DataName, TypeAttributes.Public, table.Comment + (table.DataInheritFromBase ? " Base" : "")); ctd.CustomAttributes.Add(AttrDecl(TypeRef("Serializable"))); ctd.IsPartial = true; if (table.DataInheritFromBase) { ctd.TypeAttributes |= TypeAttributes.Abstract; } if (table.Inherits != "") { ctd.BaseTypes.Add(TypeRef(table.Inherits)); } cns.Types.Add(ctd); // constructor // CodeConstructor constructor = NewCtor(MemberAttributes.Public, APResource.APBusiness_DefaultConstructorComment); ctd.Members.Add(constructor); constructor = NewCtor(MemberAttributes.Public, APResource.APBusiness_InitFieldsConstructorComment); ctd.Members.Add(constructor); // update self CodeMemberMethod assignment = NewMemberMethod(assignmentMethodName, MemberAttributes.Public, APResource.APBusiness_AssignmentComment, Param(table.DataType, "data")); ctd.Members.Add(assignment); // compare equals CodeMemberMethod compareEqulas = NewMemberMethod(compareEqualsMethodName, MemberAttributes.Public, TypeRef(typeof(bool)), APResource.APBusiness_CompareEqualsComment, Param(table.DataType, "data")); ctd.Members.Add(compareEqulas); foreach (APGenColumn column in table.Columns) { string comment = string.IsNullOrEmpty(column.Comment) ? column.Name : column.Comment; // field // CodeMemberField filed = NewMemberField(column.FieldName, column.TypeRef, MemberAttributes.Private, comment); if (!string.IsNullOrEmpty(column.DefaultValue)) { filed.InitExpression = Special(column.DefaultValue); } else { if (column.ParsedType == typeof(string) && !column.IsNullable) { filed.InitExpression = PropRef(TypeRefExp(typeof(String)), "Empty"); } } ctd.Members.Add(filed); // property // CodeMemberProperty prop = NewMemberProperty(column.PropertyName, column.TypeRef, MemberAttributes.Public, comment); if (column.Override) { prop.Attributes |= MemberAttributes.Override; } ctd.Members.Add(prop); if (!String.IsNullOrEmpty(column.Display)) { prop.CustomAttributes.Add(AttrDecl(TypeRef("Display"), AttrArg("Name", Const(column.Display)))); } if (column.Required) { prop.CustomAttributes.Add(AttrDecl(TypeRef("Required"))); } if (column.ParsedType == typeof(String)) { prop.CustomAttributes.Add(AttrDecl(TypeRef("StringLength"), AttrArg(Const(column.DataLength)))); } prop.GetStatements.Add(Return(FieldRef(column.FieldName))); prop.SetStatements.Add(Let(FieldRef(column.FieldName), Value())); // APColumnDef property CodeMemberProperty defProp = NewMemberProperty(column.PropertyName + "Def", column.DefRef, MemberAttributes.Public | MemberAttributes.Static, comment + " APColumnDef"); ctd.Members.Add(defProp); defProp.GetStatements.Add(Return( PropRef(PropRef(Special(DBDefName), table.DataName), column.PropertyName) )); // constructor constructor.Parameters.Add(Param(column.TypeRef, column.ParamName)); constructor.Statements.Add(Let(FieldRef(column.FieldName), ParamRef(column.ParamName))); // update self assignment.Statements.Add(Let(PropRef(column.PropertyName), PropRef(ParamRef("data"), column.PropertyName))); // compare equals compareEqulas.Statements.Add(If(NotEqualsValue(PropRef(column.PropertyName), PropRef(ParamRef("data"), column.PropertyName)), ReturnFalse())); } compareEqulas.Statements.Add(ReturnTrue()); // APTableDef property CodeMemberProperty tablefProp = NewMemberProperty("TableDef", TypeRef(DBDefName + "." + table.TableDefName), MemberAttributes.Public | MemberAttributes.Static, table.TableDefName + " APTableDef"); ctd.Members.Add(tablefProp); tablefProp.GetStatements.Add(Return( PropRef(Special(DBDefName), table.DataName) )); // APSqlAsteriskExpr property CodeMemberProperty asteriskProp = NewMemberProperty("Asterisk", TypeRef("APSqlAsteriskExpr"), MemberAttributes.Public | MemberAttributes.Static, table.TableDefName + " APSqlAsteriskExpr"); ctd.Members.Add(asteriskProp); asteriskProp.GetStatements.Add(Return( PropRef(PropRef(Special(DBDefName), table.DataName), "Asterisk") )); #region [ associate with Bpl ] CodePropertyReferenceExpression bpl = PropRef(Special(BplDefName), table.BplName); CodeParameterDeclarationExpression whereDef = Param(WherePhraseType, "condition"); CodeArgumentReferenceExpression whereRef = ParamRef("condition"); // insert { CodeMemberMethod method = NewMemberMethod(insertMethodName, MemberAttributes.Public, APResource.APBusiness_InsertComment); method.Statements.Add(MethodInvoke(bpl, insertMethodName, Cast(table.DataType, This()))); ctd.Members.Add(method); } // update { CodeMemberMethod method = NewMemberMethod(updateMethodName, MemberAttributes.Public, APResource.APBusiness_UpdateComment); method.Statements.Add(MethodInvoke(bpl, updateMethodName, Cast(table.DataType, This()))); ctd.Members.Add(method); } // update partial { CodeMemberMethod method = NewMemberMethod(updatePartialMethodName, MemberAttributes.Public | MemberAttributes.Static, APResource.APBusiness_UpdateComment); CodeMethodInvokeExpression call = MethodInvoke(bpl, updatePartialMethodName); method.Statements.Add(call); ctd.Members.Add(method); foreach (APGenColumn pk in table.PrimaryKeyColumns) { method.Parameters.Add(Param(pk.TypeRef, pk.ParamName)); call.Parameters.Add(ParamRef(pk.ParamName)); } method.Parameters.Add(Param(ObjectType, "metadata")); call.Parameters.Add(ParamRef("metadata")); } // primary delete { CodeMemberMethod method = NewMemberMethod(primaryDeleteMethodName, MemberAttributes.Public | MemberAttributes.Static, APResource.APBusiness_PrimaryDeleteComment); CodeMethodInvokeExpression call = MethodInvoke(bpl, primaryDeleteMethodName); method.Statements.Add(call); ctd.Members.Add(method); foreach (APGenColumn pk in table.PrimaryKeyColumns) { method.Parameters.Add(Param(pk.TypeRef, pk.ParamName)); call.Parameters.Add(ParamRef(pk.ParamName)); } } // condition delete { CodeMemberMethod method = NewMemberMethod(conditionDeleteMethodName, MemberAttributes.Public | MemberAttributes.Static, APResource.APBusiness_ConditionDeleteComment, whereDef); method.Statements.Add(MethodInvoke(bpl, conditionDeleteMethodName, whereRef)); ctd.Members.Add(method); } // condition query count { CodeMemberMethod method = NewMemberMethod(conditionQueryCountMethodName, MemberAttributes.Public | MemberAttributes.Static, APResource.APBusiness_ConditionQueryCountComment, whereDef); method.ReturnType = IntType; method.Statements.Add(Return(MethodInvoke(bpl, conditionQueryCountMethodName, whereRef))); ctd.Members.Add(method); } // primary get { CodeMemberMethod method = NewMemberMethod(primaryGetMethodName, MemberAttributes.Public | MemberAttributes.Static, APResource.APBusiness_PrimaryGetComment); method.ReturnType = table.DataType; CodeMethodInvokeExpression call = MethodInvoke(bpl, primaryGetMethodName); method.Statements.Add(Return(call)); ctd.Members.Add(method); foreach (APGenColumn pk in table.PrimaryKeyColumns) { method.Parameters.Add(Param(pk.TypeRef, pk.ParamName)); call.Parameters.Add(ParamRef(pk.ParamName)); } } CodeTypeReference listType = TypeTRef("List", table.DataType); // condition query { CodeMemberMethod method = NewMemberMethod(conditionQueryMethodName, MemberAttributes.Public | MemberAttributes.Static, APResource.APBusiness_ConditionQueryComment, whereDef, Param(OrderPhraseType, "orderBy"), Param(IntType, "take"), Param(IntType, "skip")); method.ReturnType = listType; method.Statements.Add(Return(MethodInvoke(bpl, conditionQueryMethodName, whereRef, ParamRef("orderBy"), ParamRef("take"), ParamRef("skip")))); ctd.Members.Add(method); } { CodeMemberMethod method = NewMemberMethod(conditionQueryMethodName, MemberAttributes.Public | MemberAttributes.Static, APResource.APBusiness_ConditionQueryComment, whereDef, Param(OrderPhraseType, "orderBy"), Param(IntType, "take")); method.ReturnType = listType; method.Statements.Add(Return(MethodInvoke(bpl, conditionQueryMethodName, whereRef, ParamRef("orderBy"), ParamRef("take")))); ctd.Members.Add(method); } { CodeMemberMethod method = NewMemberMethod(conditionQueryMethodName, MemberAttributes.Public | MemberAttributes.Static, APResource.APBusiness_ConditionQueryComment, whereDef, Param(OrderPhraseType, "orderBy")); method.ReturnType = listType; method.Statements.Add(Return(MethodInvoke(bpl, conditionQueryMethodName, whereRef, ParamRef("orderBy")))); ctd.Members.Add(method); } // get all { CodeMemberMethod method = NewMemberMethod(getAllMethodName, MemberAttributes.Public | MemberAttributes.Static, APResource.APBusiness_GetAllComment); method.ReturnType = listType; method.Statements.Add(Return(MethodInvoke(bpl, getAllMethodName))); ctd.Members.Add(method); } #endregion // if FromBase // if (table.DataInheritFromBase) { CodeTypeDeclaration ctd_ex; ctd_ex = NewClass(table.DataName, TypeAttributes.Public, table.Comment); ctd_ex.CustomAttributes.Add(AttrDecl(TypeRef("Serializable"))); ctd_ex.IsPartial = true; ctd_ex.BaseTypes.Add(TypeRef(table.DataBaseName)); cns.Types.Add(ctd_ex); // constructor // constructor = NewCtor(MemberAttributes.Public, APResource.APBusiness_DefaultConstructorComment); ctd_ex.Members.Add(constructor); constructor = NewCtor(MemberAttributes.Public, APResource.APBusiness_InitFieldsConstructorComment); ctd_ex.Members.Add(constructor); foreach (APGenColumn column in table.Columns) { constructor.Parameters.Add(Param(column.TypeRef, column.ParamName)); constructor.BaseConstructorArgs.Add(ParamRef(column.ParamName)); } } }
private void _createColumn(APDatabase db, APGenTable table, APGenColumn column, bool isTableEmpty) { bool changeNullable = (!isTableEmpty && !column.IsNullable); if (changeNullable) { column.IsNullable = true; } string sql; if (column.IdentityType == APColumnIdentityType.Database) sql = string.Format("alter table {0} add {1} {2} IDENTITY {3} {4}", table.TableName, column.ColumnName, DBTypeName(column), IsNullableString(column), DF_constraint(table, column)); else sql = string.Format("alter table {0} add {1} {2} {3} {4}", table.TableName, column.ColumnName, DBTypeName(column), IsNullableString(column), DF_constraint(table, column)); DbCommand dbCmd = db.CreateSqlCommand(sql); dbCmd.ExecuteNonQuery(); if (changeNullable) { column.IsNullable = false; string defaultValue = column.DBDefaultValue == "" ? "''" : column.DBDefaultValue; dbCmd = db.CreateSqlCommand("update {0} set {1} = {2}", table.TableName, column.ColumnName, defaultValue); dbCmd.ExecuteNonQuery(); dbCmd = db.CreateSqlCommand("alter table {0} alter column {1} {2} {3}", table.TableName, column.ColumnName, DBTypeName(column), IsNullableString(column)); dbCmd.ExecuteNonQuery(); } }
private string DF_constraint(APGenTable table, APGenColumn column) { if (column.DBDefaultValue != "") return String.Format("default {0}", column.DBDefaultValue); return "default null"; }
private Dictionary<string, columninfo> _getColumns(APDatabase db, APGenTable table) { DbCommand dbCmd = db.CreateSqlCommand( @"select col.colid, col.name as colname, tp.name as typename, tp.variable, col.length, col.xprec, col.xscale, col.isnullable, df.name as dfname, df.definition as dfvalue, id.is_identity from syscolumns as col inner join systypes as tp on col.xtype = tp.xtype and tp.name <> 'sysname' left join sys.default_constraints as df on col.cdefault = df.object_id left join sys.identity_columns as id on col.colid = id.column_id and id.object_id = col.id where col.id = object_id('{0}') order by col.colid", table.TableName); Dictionary<string, columninfo> dbColumns = new Dictionary<string, columninfo>(); using (IDataReader reader = dbCmd.ExecuteReader()) { while (reader.Read()) { int idx = 0; columninfo data = new columninfo() { colid = Convert.ToInt32(reader.GetValue(idx++)), colname = Convert.ToString(reader.GetValue(idx++)), typename = Convert.ToString(reader.GetValue(idx++)), variable = Convert.ToBoolean(reader.GetValue(idx++)), length = Convert.ToInt32(reader.GetValue(idx++)), xprec = Convert.ToInt32(reader.GetValue(idx++)), xscale = Convert.ToInt32(reader.GetValue(idx++)), isnullable = Convert.ToBoolean(reader.GetValue(idx++)), dfname = Convert.ToString(reader.GetValue(idx++)), dfvalue = Convert.ToString(reader.GetValue(idx++)), is_identity = reader.IsDBNull(idx++) ? false : true, }; data.Resolve(); dbColumns.Add(data.colname, data); } } return dbColumns; }
private void ModifyTable(APDatabase db, APGenTable table) { Dictionary<string, columninfo> dbColumns = _getColumns(db, table); Dictionary<string, indexinfo> dbIndexes = _getIndexes(db, table); bool isTableEmpty = _isTableEmpty(db, table); // analysis columns List<APGenColumn> listCreateColumn = new List<APGenColumn>(); List<APGenColumn> listModifyColumn = new List<APGenColumn>(); Dictionary<string, columninfo> deleteColumns = new Dictionary<string, columninfo>(dbColumns); foreach (APGenColumn column in table.Columns) { _setScanColumn(column.ColumnName); string colname = column.ColumnName; if (!dbColumns.ContainsKey(colname)) { // db has not this column, wait for create. listCreateColumn.Add(column); } else { deleteColumns.Remove(colname); columninfo colinfo = dbColumns[colname]; if (column.IsNullable != colinfo.isnullable || column.DBDefaultValue != colinfo.dfvalue || DBTypeName(column) != colinfo.GetTypeFullName() // no safe mode to change identity, so ingone change this // || (column.IdentityType == APColumnIdentityType.Database ^ colinfo.is_identity) ) { listModifyColumn.Add(column); } } } // analysis indexes List<APGenIndex> listCreateIndex = new List<APGenIndex>(); foreach (APGenIndex index in table.Indexes) { string ix_name = index.Name;// IX_name(table, index); if (!dbIndexes.ContainsKey(ix_name)) { // db has not this index, wait for create. listCreateIndex.Add(index); } else { // db has this index and columns according fitted, then to nothing. // elsewise, wait fo modify this index. // drop in db indexes residual in dbIndexes. indexinfo info = dbIndexes[ix_name]; string ix_keys = IndKeys(table, index); if (info.indkeys == ix_keys) { bool maybe = false; foreach (APGenColumn column in listModifyColumn) { if (info.columns.ContainsKey(column.ColumnName)) { listCreateIndex.Add(index); maybe = true; break; } } if (!maybe) dbIndexes.Remove(ix_name); } else { listCreateIndex.Add(index); } } } // analysis uniques List<APGenIndex> listCreateUnique = new List<APGenIndex>(); foreach (APGenIndex index in table.Uniques) { string ix_name = index.Name;// UQ_name(table, index); if (!dbIndexes.ContainsKey(ix_name)) { // db has not this unique, wait for create. listCreateUnique.Add(index); } else { // db has this unique, then to nothing. // elsewise, wait fo modify this unique. // drop in db uniques residual in dbIndexes. indexinfo info = dbIndexes[ix_name]; string uq_keys = IndKeys(table, index); if (info.indkeys == uq_keys) { bool maybe = false; foreach (APGenColumn column in listModifyColumn) { if (info.columns.ContainsKey(column.ColumnName)) { listCreateUnique.Add(index); maybe = true; break; } } if (!maybe) dbIndexes.Remove(ix_name); } else { listCreateUnique.Add(index); } } } // 1. dbIndexes for 'drop', but PK_ index analysis columns. // 2. listCreateIndex for 'create'. // 2. listCreateUnique for 'create'. // process string pkKeys = ""; foreach (APGenColumn column in table.PrimaryKeyColumns) { if (pkKeys != "") pkKeys += ","; pkKeys += column.ColumnName; } // 1. drop indexes bool needAddPrimary = true; foreach (indexinfo info in dbIndexes.Values) { if (info.indtype == indexType.Primary && info.indkeys == pkKeys) needAddPrimary = false; else _dropIndex(db, table, info); } // 2. drop columns foreach (columninfo info in deleteColumns.Values) { _dropColumn(db, table, info); } // 3. modify columns foreach (APGenColumn column in listModifyColumn) { _alterColumn(db, table, column, dbColumns[column.ColumnName]); } // 4. create columns foreach (APGenColumn column in listCreateColumn) { _createColumn(db, table, column, isTableEmpty); } // 5. mayby primary key if (needAddPrimary) { _createPrimaryKey(db, table); } // 6. create indexes foreach (APGenIndex index in listCreateIndex) { _createIndex(db, table, index); } // 7. create unique foreach (APGenIndex unique in listCreateUnique) { _createUnique(db, table, unique); } }
private void _createTable(APDatabase db, APGenTable table) { StringBuilder sb = new StringBuilder(); sb.AppendFormat("create table {0} (", table.TableName); foreach (APGenColumn column in table.Columns) { if (column.IdentityType == APColumnIdentityType.Database) sb.AppendFormat("\r\n\t{0} {1} identity {2} {3},", column.ColumnName, DBTypeName(column), IsNullableString(column), DF_constraint(table, column)); else sb.AppendFormat("\r\n\t{0} {1} {2} {3},", column.ColumnName, DBTypeName(column), IsNullableString(column), DF_constraint(table, column)); } sb.Length--; sb.Append("\r\n)"); // create table table_name ( // column_name column_type [identity] [not] null [constraint ... default ...], // ... // ) DbCommand dbCmd = db.CreateSqlCommand(sb.ToString()); dbCmd.ExecuteNonQuery(); }
private void _createPrimaryKey(APDatabase db, APGenTable table) { StringBuilder sb = new StringBuilder(); sb.AppendFormat("alter table {0} add constraint {1} primary key (", table.TableName, PK_name(table)); foreach (APGenColumn column in table.PrimaryKeyColumns) { sb.AppendFormat("\r\n\t{0},", column.ColumnName); } sb.Length--; sb.Append("\r\n)"); // alter table tablen_ame add constraint PK_table_name primary key( // column_name, // ... // ) DbCommand dbCmd = db.CreateSqlCommand(sb.ToString()); dbCmd.ExecuteNonQuery(); }
private string DF_name(APGenTable table, APGenColumn column) { return "DF_" + table.TableName + "_" + column.ColumnName; }
private void _createIndex(APDatabase db, APGenTable table, APGenIndex index) { StringBuilder sb = new StringBuilder(); sb.AppendFormat("create index {0} on {1} (", index.Name/* IX_name(table, index)*/, table.TableName); foreach (APGenOrder order in index.Orders) { sb.AppendFormat("\r\n\t{0} {1},", table.Columns[order.Name].ColumnName, order.According.ToString()); } sb.Length--; sb.Append("\r\n)"); // create index index_name on ( // column_name [ASC|DESC], // ... // ) DbCommand dbCmd = db.CreateSqlCommand(sb.ToString()); dbCmd.ExecuteNonQuery(); }
private string IndKeys(APGenTable table, APGenIndex index) { string ix_keys = ""; foreach (APGenOrder order in index.Orders) { if (ix_keys != "") ix_keys += ","; ix_keys += table.Columns[order.Name].ColumnName; if (order.According == APSqlOrderAccording.Desc) ix_keys += "(-)"; } return ix_keys; }
private void CreateBpl(CodeTypeDeclaration cns, APGenTable table, bool isView) { CodeTypeDeclaration ctd = NewClass(table.BplInheritFromBase ? table.BplBaseName : table.BplName, TypeAttributes.Public, table.Comment + (table.BplInheritFromBase ? " BplBase" : " Bpl")); ctd.IsPartial = true; cns.Members.Add(ctd); if (table.DalInheritFromBase) { CodeTypeDeclaration ctd_ex; ctd_ex = NewClass(table.BplName, TypeAttributes.Public, table.Comment + " Dal"); ctd_ex.IsPartial = true; ctd_ex.BaseTypes.Add(TypeRef(table.BplBaseName)); cns.Members.Add(ctd_ex); } CodeParameterDeclarationExpression dataDef = Param(table.DataType, "data"); CodeArgumentReferenceExpression dataRef = ParamRef("data"); CodeParameterDeclarationExpression whereDef = Param(WherePhraseType, "condition"); CodeArgumentReferenceExpression whereRef = ParamRef("condition"); CodeTypeReference listType = TypeTRef("List", table.DataType); if (!isView) { #region [ Insert(...) ] { CodeMemberMethod method = NewMemberMethod(insertMethodName, MemberAttributes.Public | MemberAttributes.Static, APResource.APBusiness_InsertComment, dataDef); ctd.Members.Add(method); method.Statements.Add(VarDecl(DBType, "db", New(DBType))); CodeTryCatchFinallyStatement _try; method.Statements.Add(_try = Try()); _try.TryStatements.Add(MethodInvoke(PropRef(Local("db"), table.DalName), insertMethodName, dataRef)); _try.FinallyStatements.Add(MethodInvoke("db", "Close")); } #endregion #region [ Update(...) ] { CodeMemberMethod method = NewMemberMethod(updateMethodName, MemberAttributes.Public | MemberAttributes.Static, APResource.APBusiness_UpdateComment, dataDef); ctd.Members.Add(method); method.Statements.Add(VarDecl(DBType, "db", New(DBType))); CodeTryCatchFinallyStatement _try; method.Statements.Add(_try = Try()); _try.TryStatements.Add(MethodInvoke(PropRef(Local("db"), table.DalName), updateMethodName, dataRef)); _try.FinallyStatements.Add(MethodInvoke("db", "Close")); } #endregion #region [ UpdatePartial(...) ] { CodeMemberMethod method = NewMemberMethod(updatePartialMethodName, MemberAttributes.Public | MemberAttributes.Static, APResource.APBusiness_UpdateComment); ctd.Members.Add(method); foreach (APGenColumn pk in table.PrimaryKeyColumns) { method.Parameters.Add(Param(pk.TypeRef, pk.ParamName)); } method.Parameters.Add(Param(ObjectType, "metadata")); method.Statements.Add(VarDecl(DBType, "db", New(DBType))); CodeTryCatchFinallyStatement _try; method.Statements.Add(_try = Try()); CodeMethodInvokeExpression update = MethodInvoke(PropRef(Local("db"), table.DalName), updatePartialMethodName); foreach (APGenColumn pk in table.PrimaryKeyColumns) { update.Parameters.Add(ParamRef(pk.ParamName)); } update.Parameters.Add(ParamRef("metadata")); _try.TryStatements.Add(update); _try.FinallyStatements.Add(MethodInvoke("db", "Close")); } #endregion #region [ PrimaryDelete(...) ] { CodeMemberMethod method = NewMemberMethod(primaryDeleteMethodName, MemberAttributes.Public | MemberAttributes.Static, APResource.APBusiness_PrimaryDeleteComment); ctd.Members.Add(method); foreach (APGenColumn pk in table.PrimaryKeyColumns) { method.Parameters.Add(Param(pk.TypeRef, pk.ParamName)); } method.Statements.Add(VarDecl(DBType, "db", New(DBType))); CodeTryCatchFinallyStatement _try = Try(); CodeMethodInvokeExpression primaryDelete = MethodInvoke(PropRef(Local("db"), table.DalName), primaryDeleteMethodName); foreach (APGenColumn pk in table.PrimaryKeyColumns) { primaryDelete.Parameters.Add(ParamRef(pk.ParamName)); } _try.TryStatements.Add(primaryDelete); _try.FinallyStatements.Add(MethodInvoke(Local("db"), "Close")); method.Statements.Add(_try); } #endregion #region [ ConditionDelete(...) ] { CodeMemberMethod method = NewMemberMethod(conditionDeleteMethodName, MemberAttributes.Public | MemberAttributes.Static, APResource.APBusiness_ConditionDeleteComment, whereDef); ctd.Members.Add(method); method.Statements.Add(VarDecl(DBType, "db", New(DBType))); CodeTryCatchFinallyStatement _try; method.Statements.Add(_try = Try()); _try.TryStatements.Add(MethodInvoke(PropRef(Local("db"), table.DalName), conditionDeleteMethodName, whereRef)); _try.FinallyStatements.Add(MethodInvoke("db", "Close")); } #endregion } #region [ ConditionQueryCount(...) ] { CodeMemberMethod method = NewMemberMethod(conditionQueryCountMethodName, MemberAttributes.Public | MemberAttributes.Static, APResource.APBusiness_ConditionQueryCountComment, whereDef); method.ReturnType = IntType; ctd.Members.Add(method); method.Statements.Add(VarDecl(DBType, "db", New(DBType))); CodeTryCatchFinallyStatement _try; method.Statements.Add(_try = Try()); _try.TryStatements.Add(Return(MethodInvoke(PropRef(Local("db"), table.DalName), conditionQueryCountMethodName, whereRef))); _try.FinallyStatements.Add(MethodInvoke("db", "Close")); } #endregion #region [ PrimaryGet(...) ] { CodeMemberMethod method = NewMemberMethod(primaryGetMethodName, MemberAttributes.Public | MemberAttributes.Static, APResource.APBusiness_PrimaryGetComment); ctd.Members.Add(method); method.ReturnType = table.DataType; CodeMethodInvokeExpression baseCall = MethodInvoke(PropRef(Local("db"), table.DalName), primaryGetMethodName); foreach (APGenColumn pk in table.PrimaryKeyColumns) { method.Parameters.Add(Param(pk.TypeRef, pk.ParamName)); baseCall.Parameters.Add(ParamRef(pk.ParamName)); } method.Statements.Add(VarDecl(DBType, "db", New(DBType))); CodeTryCatchFinallyStatement _try; method.Statements.Add(_try = Try()); _try.TryStatements.Add(Return(baseCall)); _try.FinallyStatements.Add(MethodInvoke("db", "Close")); } #endregion #region [ ConditionQuery(...) #1 ] { CodeMemberMethod method = NewMemberMethod(conditionQueryMethodName, MemberAttributes.Public | MemberAttributes.Static, APResource.APBusiness_ConditionQueryComment, whereDef, Param(OrderPhraseType, "orderBy"), Param(typeof(int?), "take"), Param(typeof(int?), "skip")); method.ReturnType = listType; ctd.Members.Add(method); method.Statements.Add(VarDecl(DBType, "db", New(DBType))); CodeTryCatchFinallyStatement _try; method.Statements.Add(_try = Try()); _try.TryStatements.Add(Return(MethodInvoke(PropRef(Local("db"), table.DalName), conditionQueryMethodName, whereRef, FieldRef("orderBy"), ParamRef("take"), ParamRef("skip")))); _try.FinallyStatements.Add(MethodInvoke("db", "Close")); } #endregion #region [ ConditionQuery(...) #2 ] { CodeMemberMethod method = NewMemberMethod(conditionQueryMethodName, MemberAttributes.Public | MemberAttributes.Static, APResource.APBusiness_ConditionQueryComment, whereDef, Param(OrderPhraseType, "orderBy"), Param(typeof(int?), "take")); method.ReturnType = listType; ctd.Members.Add(method); method.Statements.Add(VarDecl(DBType, "db", New(DBType))); CodeTryCatchFinallyStatement _try; method.Statements.Add(_try = Try()); _try.TryStatements.Add(Return(MethodInvoke(PropRef(Local("db"), table.DalName), conditionQueryMethodName, whereRef, FieldRef("orderBy"), ParamRef("take"), Null()))); _try.FinallyStatements.Add(MethodInvoke("db", "Close")); } #endregion #region [ ConditionQuery(...) #3 ] { CodeMemberMethod method = NewMemberMethod(conditionQueryMethodName, MemberAttributes.Public | MemberAttributes.Static, APResource.APBusiness_ConditionQueryComment, whereDef, Param(OrderPhraseType, "orderBy")); method.ReturnType = listType; ctd.Members.Add(method); method.Statements.Add(VarDecl(DBType, "db", New(DBType))); CodeTryCatchFinallyStatement _try; method.Statements.Add(_try = Try()); _try.TryStatements.Add(Return(MethodInvoke(PropRef(Local("db"), table.DalName), conditionQueryMethodName, whereRef, FieldRef("orderBy"), Null(), Null()))); _try.FinallyStatements.Add(MethodInvoke("db", "Close")); } #endregion #region [ GetAll() ] { CodeMemberMethod method = NewMemberMethod(getAllMethodName, MemberAttributes.Public | MemberAttributes.Static, APResource.APBusiness_GetAllComment); method.ReturnType = listType; ctd.Members.Add(method); method.Statements.Add(Return(MethodInvoke(conditionQueryMethodName, Null(), Null()))); } #endregion }