/// <summary> /// Create a representation of the creation of a foreign key constraint. /// </summary> /// <param name="relationSchema">The description of the foreign key constraint.</param> public CodeForeignKeyConstraint(ForeignKeyConstraintSchema foreignKeyConstraintSchema) { // new global::System.Data.DataColumn[] {this.tableCountry.CountryIdColumn} List <CodeExpression> parentFieldList = new List <CodeExpression>(); foreach (ColumnSchema columnSchema in foreignKeyConstraintSchema.RelatedColumns) { parentFieldList.Add( new CodePropertyReferenceExpression( new CodeFieldReferenceExpression(new CodeThisReferenceExpression(), String.Format("table{0}", foreignKeyConstraintSchema.RelatedTable.Name)), String.Format("{0}Column", columnSchema.Name))); } // new global::System.Data.DataColumn[] {this.tableAccountBase.CountryIdColumn} List <CodeExpression> childFieldList = new List <CodeExpression>(); foreach (ColumnSchema columnSchema in foreignKeyConstraintSchema.Columns) { childFieldList.Add( new CodePropertyReferenceExpression( new CodeFieldReferenceExpression(new CodeThisReferenceExpression(), String.Format("table{0}", foreignKeyConstraintSchema.Table.Name)), String.Format("{0}Column", columnSchema.Name))); } // new global::System.Data.ForeignKeyConstraint("FK_Country_AccountBase", new global::System.Data.DataColumn[] { // this.tableCountry.CountryIdColumn}, new global::System.Data.DataColumn[] { // this.tableAccountBase.CountryIdColumn}); this.CreateType = new CodeGlobalTypeReference(typeof(ForeignKeyConstraint)); this.Parameters.Add(new CodePrimitiveExpression(foreignKeyConstraintSchema.Name)); this.Parameters.Add(new CodeArrayCreateExpression(new CodeGlobalTypeReference(typeof(DataColumn)), parentFieldList.ToArray())); this.Parameters.Add(new CodeArrayCreateExpression(new CodeGlobalTypeReference(typeof(DataColumn)), childFieldList.ToArray())); }
/// <summary> /// Create a representation of the creation of a foreign key constraint. /// </summary> /// <param name="relationSchema">The description of the foreign key constraint.</param> public CodeForeignKeyConstraint(ForeignKeyConstraintSchema foreignKeyConstraintSchema) { // Collect the key fields in the parent table. List <CodeExpression> parentFieldList = new List <CodeExpression>(); foreach (ColumnSchema columnSchema in foreignKeyConstraintSchema.RelatedColumns) { parentFieldList.Add(new CodePropertyReferenceExpression(new CodeFieldReferenceExpression(new CodeTypeReferenceExpression(foreignKeyConstraintSchema.RelatedTable.DataModel.Name), String.Format("table{0}", foreignKeyConstraintSchema.RelatedTable.Name)), String.Format("{0}Column", columnSchema.Name))); } // Collect the referenced fields in the child table. List <CodeExpression> childFieldList = new List <CodeExpression>(); foreach (ColumnSchema columnSchema in foreignKeyConstraintSchema.Columns) { childFieldList.Add(new CodePropertyReferenceExpression(new CodeFieldReferenceExpression(new CodeTypeReferenceExpression(foreignKeyConstraintSchema.Table.DataModel.Name), String.Format("table{0}", foreignKeyConstraintSchema.Table.Name)), String.Format("{0}Column", columnSchema.Name))); } // new System.Data.ForeignKeyConstraint("FK_Object_Department", new FluidTrade.Core.Column[] { // FluidTrade.UnitTest.Server.DataModel.tableObject.ObjectIdColumn}, new FluidTrade.Core.Column[] { // FluidTrade.UnitTest.Server.DataModel.tableDepartment.DepartmentIdColumn}); this.CreateType = new CodeGlobalTypeReference(typeof(System.Data.ForeignKeyConstraint)); this.Parameters.Add(new CodePrimitiveExpression(foreignKeyConstraintSchema.Name)); this.Parameters.Add(new CodeArrayCreateExpression(new CodeGlobalTypeReference(typeof(System.Data.DataColumn)), parentFieldList.ToArray())); this.Parameters.Add(new CodeArrayCreateExpression(new CodeGlobalTypeReference(typeof(System.Data.DataColumn)), childFieldList.ToArray())); }
public override ConstraintSchemaCollection GetTableConstraints(TableSchema table) { ConstraintSchemaCollection constraints = new ConstraintSchemaCollection(); using (IPooledDbConnection conn = connectionPool.Request()) { using (IDbCommand command = conn.CreateCommand(string.Format(@"select sysobjects.name, sysobjects.xtype from sysobjects inner join sysobjects sysobjectsParents ON sysobjectsParents.id = sysobjects.parent_obj where sysobjectsParents.name = '{0}' and sysobjects.xtype in ('C', 'UQ', 'F','PK','CK')" , table.Name))) try { using (IDataReader r = command.ExecuteReader()) { while (r.Read()) { ConstraintSchema constraint = null; switch (r.GetString(1)) { case "F": //foreign key constraint = new ForeignKeyConstraintSchema(this); break; case "PK": //primary key constraint = new PrimaryKeyConstraintSchema(this); break; case "C": case "CK": //check constraint constraint = new CheckConstraintSchema(this); break; case "UQ": constraint = new UniqueConstraintSchema(this); break; default: break; } if (constraint != null) { constraint.Name = r.GetString(0); constraints.Add(constraint); } } r.Close(); } } catch (Exception e) { QueryService.RaiseException(e); }finally { conn.Release(); } } return(constraints); }
protected virtual void AddClicked(object sender, EventArgs e) { ForeignKeyConstraintSchema fk = schemaProvider.GetNewForeignKeyConstraintSchema("fk_new"); int index = 1; while (constraints.Contains(fk.Name)) { fk.Name = "fk_new" + (index++); } constraints.Add(fk); AddConstraint(fk); EmitContentChanged(); }
protected virtual string GetConstraintString(ConstraintSchema constraint) { if (constraint.ConstraintType == ConstraintType.Check) { return(String.Format("CHECK ({0})", (constraint as CheckConstraintSchema).Source)); } StringBuilder sb = new StringBuilder(); sb.Append("CONSTRAINT "); sb.Append(constraint.Name); sb.Append(' '); switch (constraint.ConstraintType) { case ConstraintType.PrimaryKey: sb.Append("PRIMARY KEY "); sb.Append(GetColumnsString(constraint.Columns, true)); break; case ConstraintType.Unique: sb.Append("UNIQUE KEY "); sb.Append(GetColumnsString(constraint.Columns, true)); break; case ConstraintType.ForeignKey: sb.Append("FOREIGN KEY "); sb.Append(GetColumnsString(constraint.Columns, true)); sb.Append(" REFERENCES "); ForeignKeyConstraintSchema fk = constraint as ForeignKeyConstraintSchema; sb.Append(fk.ReferenceTableName); sb.Append(' '); if (fk.ReferenceColumns != null) { sb.Append(GetColumnsString(fk.ReferenceColumns, true)); } sb.Append(Environment.NewLine); sb.Append(" ON DELETE "); sb.Append(GetConstraintActionString(fk.DeleteAction)); sb.Append(Environment.NewLine); sb.Append(" ON UPDATE "); sb.Append(GetConstraintActionString(fk.UpdateAction)); break; default: throw new NotImplementedException(); } return(sb.ToString()); }
protected virtual void AddClicked(object sender, EventArgs e) { ForeignKeyConstraintSchema fk = schemaProvider.CreateForeignKeyConstraintSchema(string.Concat(table.Name, "_", "fk_new")); int index = 1; while (constraints.Contains(fk.Name)) { fk.Name = string.Concat(table.Name, "_", "fk_new", (index++).ToString()); } constraints.Add(fk); AddConstraint(fk); EmitContentChanged(); }
protected virtual string GetConstraintString(ConstraintSchema constraint) { StringBuilder sb = new StringBuilder(); sb.Append("CONSTRAINT "); sb.Append(constraint.Name); sb.Append(' '); switch (constraint.ConstraintType) { case ConstraintType.PrimaryKey: sb.Append("PRIMARY KEY "); sb.Append(GetColumnsString(constraint.Columns, true)); break; case ConstraintType.Unique: sb.Append("UNIQUE "); sb.Append(GetColumnsString(constraint.Columns, true)); break; case ConstraintType.Check: sb.Append("CHECK ("); sb.Append((constraint as CheckConstraintSchema).Source); sb.Append(")"); break; case ConstraintType.ForeignKey: sb.Append("FOREIGN KEY "); sb.Append(GetColumnsString(constraint.Columns, true)); sb.Append(" REFERENCES "); ForeignKeyConstraintSchema fk = constraint as ForeignKeyConstraintSchema; sb.Append(fk.ReferenceTableName); sb.Append(' '); if (fk.ReferenceColumns != null) { sb.Append(GetColumnsString(fk.ReferenceColumns, true)); } break; default: throw new NotImplementedException(); } return(sb.ToString()); }
protected virtual void RemoveClicked(object sender, EventArgs e) { TreeIter iter; if (listFK.Selection.GetSelected(out iter)) { ForeignKeyConstraintSchema fk = store.GetValue(iter, colObjIndex) as ForeignKeyConstraintSchema; if (MessageService.Confirm( AddinCatalog.GetString("Are you sure you want to remove foreign key constraint '{0}'?", fk.Name), AlertButton.Remove )) { store.Remove(ref iter); constraints.Remove(fk); EmitContentChanged(); } } }
protected virtual void RemoveClicked(object sender, EventArgs e) { TreeIter iter; if (listFK.Selection.GetSelected(out iter)) { ForeignKeyConstraintSchema fk = store.GetValue(iter, colObjIndex) as ForeignKeyConstraintSchema; if (Services.MessageService.AskQuestion( GettextCatalog.GetString("Are you sure you want to remove constraint '{0}'?", fk.Name), GettextCatalog.GetString("Remove Constraint") )) { store.Remove(ref iter); constraints.Remove(fk); EmitContentChanged(); } } }
public override ConstraintSchemaCollection GetTableConstraints(TableSchema table) { ConstraintSchemaCollection constraints = new ConstraintSchemaCollection(); using (IPooledDbConnection conn = connectionPool.Request()) { using (IDbCommand command = conn.CreateCommand(string.Concat("SHOW TABLE STATUS FROM `", table.SchemaName, "`;"))) { try { using (IDataReader r = command.ExecuteReader()) { while (r.Read()) { string[] chunks = ((string)r["Comment"]).Split(';'); // the values we are looking for are in the format: // (`table`) REFER `database\table2` (`table2`) foreach (string chunk in chunks) { if (constraintRegex.IsMatch(chunk)) { MatchCollection matches = constraintRegex.Matches(chunk); ForeignKeyConstraintSchema constraint = new ForeignKeyConstraintSchema(this); constraint.ReferenceTableName = matches[1].Groups[1].ToString(); constraint.Name = matches[0].Groups[1].ToString(); constraints.Add(constraint); } } } r.Close(); } } catch (Exception e) { // Don't raise error, if the table doesn't exists return an empty collection } finally { conn.Release(); } } } return(constraints); }
public virtual void FillSchemaObjects() { TreeIter iter; if (store.GetIterFirst(out iter)) { do { ForeignKeyConstraintSchema fk = store.GetValue(iter, colObjIndex) as ForeignKeyConstraintSchema; fk.Name = store.GetValue(iter, colNameIndex) as string; fk.IsColumnConstraint = (bool)store.GetValue(iter, colIsColumnConstraintIndex); fk.ReferenceTableName = store.GetValue(iter, colReferenceTableIndex) as string; fk.DeleteAction = GetForeignKeyAction(iter, colDeleteActionIndex); fk.UpdateAction = GetForeignKeyAction(iter, colUpdateActionIndex); string colstr = store.GetValue(iter, colColumnsIndex) as string; string[] cols = colstr.Split(','); foreach (string col in cols) { ColumnSchema column = columns.Search(col); fk.Columns.Add(column); } colstr = store.GetValue(iter, colReferenceColumnsIndex) as string; cols = colstr.Split(','); foreach (string col in cols) { ColumnSchema column = columns.Search(col); fk.ReferenceColumns.Add(column); } table.Constraints.Add(fk); } while (store.IterNext(ref iter)); } }
public override ConstraintSchemaCollection GetTableConstraints (TableSchema table) { ConstraintSchemaCollection constraints = new ConstraintSchemaCollection (); using (IPooledDbConnection conn = connectionPool.Request ()) { using (IDbCommand command = conn.CreateCommand (string.Concat ("SHOW TABLE STATUS FROM `", table.SchemaName, "`;"))) { try { using (IDataReader r = command.ExecuteReader()) { while (r.Read ()) { string[] chunks = ((string)r["Comment"]).Split (';'); // the values we are looking for are in the format: // (`table`) REFER `database\table2` (`table2`) foreach (string chunk in chunks) { if (constraintRegex.IsMatch (chunk)) { MatchCollection matches = constraintRegex.Matches (chunk); ForeignKeyConstraintSchema constraint = new ForeignKeyConstraintSchema (this); constraint.ReferenceTableName = matches[1].Groups[1].ToString (); constraint.Name = matches[0].Groups[1].ToString (); constraints.Add (constraint); } } } r.Close (); } } catch (Exception e) { // Don't raise error, if the table doesn't exists return an empty collection } finally { conn.Release (); } } } return constraints; }
/// <summary> /// Create a static constructor for the data model. /// </summary> /// <param name="dataModelSchema">A description of the data model.</param> public StaticConstructor(DataModelSchema dataModelSchema) { /// <summary> // static DataModel() { this.Comments.Add(new CodeCommentStatement("<summary>", true)); this.Comments.Add(new CodeCommentStatement(string.Format("Static Constructor for the {0}.", dataModelSchema.Name), true)); this.Comments.Add(new CodeCommentStatement("</summary>", true)); // DataModel.lockTimeout = global::FluidTrade.Core.Properties.Settings.Default.LockTimeout; this.Statements.Add( new CodeAssignStatement( new CodePropertyReferenceExpression(new CodeTypeReferenceExpression(dataModelSchema.Name), "lockTimeout"), new CodePropertyReferenceExpression( new CodePropertyReferenceExpression(new CodeGlobalTypeReferenceExpression(typeof(FluidTrade.Core.Properties.Settings)), "Default"), "LockTimeout"))); // DataModel.dataSet = new global::System.Data.DataSet(); this.Statements.Add( new CodeAssignStatement( new CodePropertyReferenceExpression(new CodeTypeReferenceExpression(dataModelSchema.Name), String.Format("{0}DataSet", CommonConversion.ToCamelCase(dataModelSchema.Name))), new CodeObjectCreateExpression(new CodeTypeReference(String.Format("{0}DataSet", dataModelSchema.Name))))); // DataModel.dataSet.DataSetName = "DataModel"; this.Statements.Add( new CodeAssignStatement( new CodePropertyReferenceExpression( new CodePropertyReferenceExpression(new CodeTypeReferenceExpression(dataModelSchema.Name), String.Format("{0}DataSet", CommonConversion.ToCamelCase(dataModelSchema.Name))), "DataSetName"), new CodePrimitiveExpression(dataModelSchema.Name))); // DataModel.dataSet.CaseSensitive = true; this.Statements.Add( new CodeAssignStatement( new CodePropertyReferenceExpression( new CodePropertyReferenceExpression(new CodeTypeReferenceExpression(dataModelSchema.Name), String.Format("{0}DataSet", CommonConversion.ToCamelCase(dataModelSchema.Name))), "CaseSensitive"), new CodePrimitiveExpression(true))); // DataModel.dataSet.EnforceConstraints = true; this.Statements.Add( new CodeAssignStatement( new CodePropertyReferenceExpression( new CodePropertyReferenceExpression(new CodeTypeReferenceExpression(dataModelSchema.Name), String.Format("{0}DataSet", CommonConversion.ToCamelCase(dataModelSchema.Name))), "EnforceConstraints"), new CodePrimitiveExpression(true))); // Create each of the tables and add them to the data set. for (int tableIndex = 0; tableIndex < dataModelSchema.Tables.Count; tableIndex++) { KeyValuePair <string, TableSchema> keyValuePair = Enumerable.ElementAt(dataModelSchema.Tables, tableIndex); // FluidTrade.UnitTest.Server.DataModel.tableConfiguration = new ConfigurationDataTable(); this.Statements.Add( new CodeAssignStatement( new CodePropertyReferenceExpression(new CodeTypeReferenceExpression(dataModelSchema.Name), String.Format("table{0}", keyValuePair.Value.Name)), new CodeObjectCreateExpression(string.Format("{0}DataTable", keyValuePair.Value.Name)))); // DataModel.tableConfiguration.Ordinal = 0; this.Statements.Add( new CodeAssignStatement( new CodePropertyReferenceExpression( new CodePropertyReferenceExpression( new CodeTypeReferenceExpression(dataModelSchema.Name), String.Format("table{0}", keyValuePair.Value.Name)), "Ordinal"), new CodePrimitiveExpression(tableIndex))); // FluidTrade.UnitTest.Server.DataModel.dataSet.Tables.Add(FluidTrade.UnitTest.Server.DataModel.tableConfiguration); this.Statements.Add( new CodeMethodInvokeExpression( new CodePropertyReferenceExpression( new CodePropertyReferenceExpression(new CodeTypeReferenceExpression(dataModelSchema.Name), String.Format("{0}DataSet", CommonConversion.ToCamelCase(dataModelSchema.Name))), "Tables"), "Add", new CodePropertyReferenceExpression( new CodeTypeReferenceExpression(dataModelSchema.Name), String.Format("table{0}", keyValuePair.Value.Name)))); } // global::System.Data.ForeignKeyConstraint foreignKeyConstraint0 = new System.Data.ForeignKeyConstraint("FK_Object_Department", new FluidTrade.Core.Column[] { // FluidTrade.UnitTest.Server.DataModel.tableObject.ObjectIdColumn}, new FluidTrade.Core.Column[] { // FluidTrade.UnitTest.Server.DataModel.tableDepartment.DepartmentIdColumn}); // FluidTrade.UnitTest.Server.DataModel.tableDepartment.Constraints.Add(foreignKeyConstraint0); // global::System.Data.ForeignKeyConstraint foreignKeyConstraint1 = new System.Data.ForeignKeyConstraint("FK_Department_Employee", new FluidTrade.Core.Column[] { // FluidTrade.UnitTest.Server.DataModel.tableDepartment.DepartmentIdColumn}, new FluidTrade.Core.Column[] { // FluidTrade.UnitTest.Server.DataModel.tableEmployee.DepartmentIdColumn}); // FluidTrade.UnitTest.Server.DataModel.tableEmployee.Constraints.Add(foreignKeyConstraint1); // global::System.Data.ForeignKeyConstraint foreignKeyConstraint2 = new System.Data.ForeignKeyConstraint("FK_Object_Employee", new FluidTrade.Core.Column[] { // FluidTrade.UnitTest.Server.DataModel.tableObject.ObjectIdColumn}, new FluidTrade.Core.Column[] { // FluidTrade.UnitTest.Server.DataModel.tableEmployee.EmployeeIdColumn}); // FluidTrade.UnitTest.Server.DataModel.tableEmployee.Constraints.Add(foreignKeyConstraint2); // global::System.Data.ForeignKeyConstraint foreignKeyConstraint3 = new System.Data.ForeignKeyConstraint("FK_Race_Employee", new FluidTrade.Core.Column[] { // FluidTrade.UnitTest.Server.DataModel.tableRace.RaceCodeColumn}, new FluidTrade.Core.Column[] { // FluidTrade.UnitTest.Server.DataModel.tableEmployee.RaceCodeColumn}); // FluidTrade.UnitTest.Server.DataModel.tableEmployee.Constraints.Add(foreignKeyConstraint3); // global::System.Data.ForeignKeyConstraint foreignKeyConstraint4 = new System.Data.ForeignKeyConstraint("FK_Employee_Engineer", new FluidTrade.Core.Column[] { // FluidTrade.UnitTest.Server.DataModel.tableEmployee.EmployeeIdColumn}, new FluidTrade.Core.Column[] { // FluidTrade.UnitTest.Server.DataModel.tableEngineer.EngineerIdColumn}); // FluidTrade.UnitTest.Server.DataModel.tableEngineer.Constraints.Add(foreignKeyConstraint4); // global::System.Data.ForeignKeyConstraint foreignKeyConstraint5 = new System.Data.ForeignKeyConstraint("FK_Manager_Engineer", new FluidTrade.Core.Column[] { // FluidTrade.UnitTest.Server.DataModel.tableManager.ManagerIdColumn}, new FluidTrade.Core.Column[] { // FluidTrade.UnitTest.Server.DataModel.tableEngineer.ManagerIdColumn}); // FluidTrade.UnitTest.Server.DataModel.tableEngineer.Constraints.Add(foreignKeyConstraint5); // global::System.Data.ForeignKeyConstraint foreignKeyConstraint6 = new System.Data.ForeignKeyConstraint("FK_Employee_Manager", new FluidTrade.Core.Column[] { // FluidTrade.UnitTest.Server.DataModel.tableEmployee.EmployeeIdColumn}, new FluidTrade.Core.Column[] { // FluidTrade.UnitTest.Server.DataModel.tableManager.ManagerIdColumn}); // FluidTrade.UnitTest.Server.DataModel.tableManager.Constraints.Add(foreignKeyConstraint6); // global::System.Data.ForeignKeyConstraint foreignKeyConstraint7 = new System.Data.ForeignKeyConstraint("FK_Object_Project", new FluidTrade.Core.Column[] { // FluidTrade.UnitTest.Server.DataModel.tableObject.ObjectIdColumn}, new FluidTrade.Core.Column[] { // FluidTrade.UnitTest.Server.DataModel.tableProject.ProjectIdColumn}); // FluidTrade.UnitTest.Server.DataModel.tableProject.Constraints.Add(foreignKeyConstraint7); // global::System.Data.ForeignKeyConstraint foreignKeyConstraint8 = new System.Data.ForeignKeyConstraint("FK_Employee_ProjectMember", new FluidTrade.Core.Column[] { // FluidTrade.UnitTest.Server.DataModel.tableEmployee.EmployeeIdColumn}, new FluidTrade.Core.Column[] { // FluidTrade.UnitTest.Server.DataModel.tableProjectMember.EmployeeIdColumn}); // FluidTrade.UnitTest.Server.DataModel.tableProjectMember.Constraints.Add(foreignKeyConstraint8); // global::System.Data.ForeignKeyConstraint foreignKeyConstraint9 = new System.Data.ForeignKeyConstraint("FK_Project_ProjectMember", new FluidTrade.Core.Column[] { // FluidTrade.UnitTest.Server.DataModel.tableProject.ProjectIdColumn}, new FluidTrade.Core.Column[] { // FluidTrade.UnitTest.Server.DataModel.tableProjectMember.ProjectIdColumn}); // FluidTrade.UnitTest.Server.DataModel.tableProjectMember.Constraints.Add(foreignKeyConstraint9); int foreignKeyCount = 0; foreach (KeyValuePair <string, TableSchema> tablePair in dataModelSchema.Tables) { foreach (KeyValuePair <string, ConstraintSchema> constraintPair in tablePair.Value.Constraints) { if (constraintPair.Value is ForeignKeyConstraintSchema) { // Construct a foreign key constraint described by this schema. ForeignKeyConstraintSchema foreignKeyConstraintSchema = constraintPair.Value as ForeignKeyConstraintSchema; // FluidTrade.UnitTest.Client.DataModel.relationDepartmentEmployee = new System.Data.DataRelation("FK_Department_Employee", new global::System.Data.DataColumn[] { // FluidTrade.UnitTest.Client.DataModel.tableDepartment.DepartmentIdColumn}, new global::System.Data.DataColumn[] { // FluidTrade.UnitTest.Client.DataModel.tableEmployee.DepartmentIdColumn}, false); // FluidTrade.UnitTest.Client.DataModel.dataSet.Relations.Add(FluidTrade.UnitTest.Client.DataModel.relationDepartmentEmployee); CodeVariableReferenceExpression foreignKeyConstraintExpression = new CodeVariableReferenceExpression(string.Format("foreignKeyConstraint{0}", foreignKeyCount++)); this.Statements.Add(new CodeVariableDeclarationStatement(new CodeGlobalTypeReference(typeof(System.Data.ForeignKeyConstraint)), foreignKeyConstraintExpression.VariableName, new CodeForeignKeyConstraint(foreignKeyConstraintSchema))); this.Statements.Add(new CodeMethodInvokeExpression(new CodePropertyReferenceExpression(new CodePropertyReferenceExpression(new CodeTypeReferenceExpression(dataModelSchema.Name), string.Format("table{0}", tablePair.Value.Name)), "Constraints"), "Add", foreignKeyConstraintExpression)); } } } // FluidTrade.UnitTest.Server.DataModel.relationDepartmentEmployee = new System.Data.DataRelation("FK_Department_Employee", new FluidTrade.Core.Column[] { // FluidTrade.UnitTest.Server.DataModel.tableDepartment.DepartmentIdColumn}, new FluidTrade.Core.Column[] { // FluidTrade.UnitTest.Server.DataModel.tableEmployee.DepartmentIdColumn}, false); // FluidTrade.UnitTest.Server.DataModel.dataSet.Relations.Add(FluidTrade.UnitTest.Server.DataModel.relationDepartmentEmployee); // FluidTrade.UnitTest.Server.DataModel.relationEmployeeEngineer = new System.Data.DataRelation("FK_Employee_Engineer", new FluidTrade.Core.Column[] { // FluidTrade.UnitTest.Server.DataModel.tableEmployee.EmployeeIdColumn}, new FluidTrade.Core.Column[] { // FluidTrade.UnitTest.Server.DataModel.tableEngineer.EngineerIdColumn}, false); // FluidTrade.UnitTest.Server.DataModel.dataSet.Relations.Add(FluidTrade.UnitTest.Server.DataModel.relationEmployeeEngineer); // FluidTrade.UnitTest.Server.DataModel.relationEmployeeManager = new System.Data.DataRelation("FK_Employee_Manager", new FluidTrade.Core.Column[] { // FluidTrade.UnitTest.Server.DataModel.tableEmployee.EmployeeIdColumn}, new FluidTrade.Core.Column[] { // FluidTrade.UnitTest.Server.DataModel.tableManager.ManagerIdColumn}, false); // FluidTrade.UnitTest.Server.DataModel.dataSet.Relations.Add(FluidTrade.UnitTest.Server.DataModel.relationEmployeeManager); // FluidTrade.UnitTest.Server.DataModel.relationEmployeeProjectMember = new System.Data.DataRelation("FK_Employee_ProjectMember", new FluidTrade.Core.Column[] { // FluidTrade.UnitTest.Server.DataModel.tableEmployee.EmployeeIdColumn}, new FluidTrade.Core.Column[] { // FluidTrade.UnitTest.Server.DataModel.tableProjectMember.EmployeeIdColumn}, false); // FluidTrade.UnitTest.Server.DataModel.dataSet.Relations.Add(FluidTrade.UnitTest.Server.DataModel.relationEmployeeProjectMember); // FluidTrade.UnitTest.Server.DataModel.relationManagerEngineer = new System.Data.DataRelation("FK_Manager_Engineer", new FluidTrade.Core.Column[] { // FluidTrade.UnitTest.Server.DataModel.tableManager.ManagerIdColumn}, new FluidTrade.Core.Column[] { // FluidTrade.UnitTest.Server.DataModel.tableEngineer.ManagerIdColumn}, false); // FluidTrade.UnitTest.Server.DataModel.dataSet.Relations.Add(FluidTrade.UnitTest.Server.DataModel.relationManagerEngineer); // FluidTrade.UnitTest.Server.DataModel.relationObjectDepartment = new System.Data.DataRelation("FK_Object_Department", new FluidTrade.Core.Column[] { // FluidTrade.UnitTest.Server.DataModel.tableObject.ObjectIdColumn}, new FluidTrade.Core.Column[] { // FluidTrade.UnitTest.Server.DataModel.tableDepartment.DepartmentIdColumn}, false); // FluidTrade.UnitTest.Server.DataModel.dataSet.Relations.Add(FluidTrade.UnitTest.Server.DataModel.relationObjectDepartment); // FluidTrade.UnitTest.Server.DataModel.relationObjectEmployee = new System.Data.DataRelation("FK_Object_Employee", new FluidTrade.Core.Column[] { // FluidTrade.UnitTest.Server.DataModel.tableObject.ObjectIdColumn}, new FluidTrade.Core.Column[] { // FluidTrade.UnitTest.Server.DataModel.tableEmployee.EmployeeIdColumn}, false); // FluidTrade.UnitTest.Server.DataModel.dataSet.Relations.Add(FluidTrade.UnitTest.Server.DataModel.relationObjectEmployee); // FluidTrade.UnitTest.Server.DataModel.relationObjectProject = new System.Data.DataRelation("FK_Object_Project", new FluidTrade.Core.Column[] { // FluidTrade.UnitTest.Server.DataModel.tableObject.ObjectIdColumn}, new FluidTrade.Core.Column[] { // FluidTrade.UnitTest.Server.DataModel.tableProject.ProjectIdColumn}, false); // FluidTrade.UnitTest.Server.DataModel.dataSet.Relations.Add(FluidTrade.UnitTest.Server.DataModel.relationObjectProject); // FluidTrade.UnitTest.Server.DataModel.relationProjectProjectMember = new System.Data.DataRelation("FK_Project_ProjectMember", new FluidTrade.Core.Column[] { // FluidTrade.UnitTest.Server.DataModel.tableProject.ProjectIdColumn}, new FluidTrade.Core.Column[] { // FluidTrade.UnitTest.Server.DataModel.tableProjectMember.ProjectIdColumn}, false); // FluidTrade.UnitTest.Server.DataModel.dataSet.Relations.Add(FluidTrade.UnitTest.Server.DataModel.relationProjectProjectMember); // FluidTrade.UnitTest.Server.DataModel.relationRaceEmployee = new System.Data.DataRelation("FK_Race_Employee", new FluidTrade.Core.Column[] { // FluidTrade.UnitTest.Server.DataModel.tableRace.RaceCodeColumn}, new FluidTrade.Core.Column[] { // FluidTrade.UnitTest.Server.DataModel.tableEmployee.RaceCodeColumn}, false); // FluidTrade.UnitTest.Server.DataModel.dataSet.Relations.Add(FluidTrade.UnitTest.Server.DataModel.relationRaceEmployee); foreach (KeyValuePair <string, RelationSchema> relationPair in dataModelSchema.Relations) { // The name of the relation is decorated with the relation name when the relation between the child and the parent // isn't unique. string relationName = relationPair.Value.IsDistinctPathToParent ? string.Format("relation{0}{1}", relationPair.Value.ParentTable.Name, relationPair.Value.ChildTable.Name) : string.Format("relation{0}{1}By{2}", relationPair.Value.ParentTable.Name, relationPair.Value.ChildTable.Name, relationPair.Value.Name); // FluidTrade.UnitTest.Server.DataModel.relationRaceEmployee = new System.Data.DataRelation("FK_Race_Employee", new FluidTrade.Core.Column[] { // FluidTrade.UnitTest.Server.DataModel.tableRace.RaceCodeColumn}, new FluidTrade.Core.Column[] { // FluidTrade.UnitTest.Server.DataModel.tableEmployee.RaceCodeColumn}, false); // FluidTrade.UnitTest.Server.DataModel.dataSet.Relations.Add(FluidTrade.UnitTest.Server.DataModel.relationRaceEmployee); CodeExpression relationFieldExpression = new CodePropertyReferenceExpression(new CodeTypeReferenceExpression(dataModelSchema.Name), relationName); this.Statements.Add(new CodeAssignStatement(relationFieldExpression, new CodeDataRelation(relationPair.Value))); this.Statements.Add(new CodeMethodInvokeExpression(new CodePropertyReferenceExpression(new CodeFieldReferenceExpression(new CodeTypeReferenceExpression(dataModelSchema.Name), String.Format("{0}DataSet", CommonConversion.ToCamelCase(dataModelSchema.Name))), "Relations"), "Add", relationFieldExpression)); } // FluidTrade.UnitTest.Server.DataModel.Configuration.InitializeRelations(); // FluidTrade.UnitTest.Server.DataModel.Department.InitializeRelations(); // FluidTrade.UnitTest.Server.DataModel.Employee.InitializeRelations(); // FluidTrade.UnitTest.Server.DataModel.Engineer.InitializeRelations(); // FluidTrade.UnitTest.Server.DataModel.Manager.InitializeRelations(); // FluidTrade.UnitTest.Server.DataModel.Object.InitializeRelations(); // FluidTrade.UnitTest.Server.DataModel.Project.InitializeRelations(); // FluidTrade.UnitTest.Server.DataModel.ProjectMember.InitializeRelations(); // FluidTrade.UnitTest.Server.DataModel.Race.InitializeRelations(); foreach (KeyValuePair <string, TableSchema> keyValuePair in dataModelSchema.Tables) { this.Statements.Add(new CodeMethodInvokeExpression(new CodePropertyReferenceExpression(new CodeTypeReferenceExpression(dataModelSchema.Name), keyValuePair.Value.Name), "InitializeRelations")); } // global::System.Threading.ThreadPool.QueueUserWorkItem(LoadData); this.Statements.Add( new CodeMethodInvokeExpression( new CodeGlobalTypeReferenceExpression(typeof(ThreadPool)), "QueueUserWorkItem", new CodeMethodReferenceExpression( new CodeFieldReferenceExpression(new CodeTypeReferenceExpression(dataModelSchema.Name), "dataModelDataSet"), "LoadData"))); // } }
public override ConstraintSchemaCollection GetTableConstraints (TableSchema table) { ConstraintSchemaCollection constraints = new ConstraintSchemaCollection (); using (IPooledDbConnection conn = connectionPool.Request ()) { using (IDbCommand command = conn.CreateCommand (String.Format ( @"SELECT pc.conname, pg_catalog.pg_get_constraintdef(pc.oid, true) AS consrc, pc.contype, CASE WHEN pc.contype='u' OR pc.contype='p' THEN ( SELECT indisclustered FROM pg_catalog.pg_depend pd, pg_catalog.pg_class pl, pg_catalog.pg_index pi WHERE pd.refclassid=pc.tableoid AND pd.refobjid=pc.oid AND pd.objid=pl.oid AND pl.oid=pi.indexrelid) ELSE NULL END AS indisclustered FROM pg_catalog.pg_constraint pc WHERE pc.conrelid = ( SELECT oid FROM pg_catalog.pg_class WHERE relname='{0}' AND relnamespace = (SELECT oid FROM pg_catalog.pg_namespace WHERE nspname='{1}')) ORDER BY 1;", table.Name, table.SchemaName))) { try { using (IDataReader r = command.ExecuteReader()) { while (r.Read ()) { ConstraintSchema constraint = null; //TODO: Add support for Check constraints. switch (r.GetString (2)) { case "f": string match = @".*REFERENCES (.+)\(.*\).*"; constraint = new ForeignKeyConstraintSchema (this); if (Regex.IsMatch (r.GetString (1), match)) (constraint as ForeignKeyConstraintSchema).ReferenceTableName = Regex.Match (r.GetString (1), match).Groups[0].Captures[0].Value; break; case "u": constraint = new UniqueConstraintSchema (this); break; case "p": default: constraint = new PrimaryKeyConstraintSchema (this); break; } constraint.Name = r.GetString (0); constraint.Definition = r.GetString (1); int parenOpen = constraint.Definition.IndexOf ('('); if (parenOpen > 0) { int parenClose = constraint.Definition.IndexOf (')'); string colstr = constraint.Definition.Substring (parenOpen + 1, parenClose - parenOpen - 1); foreach (string col in colstr.Split (',')) { ColumnSchema column = new ColumnSchema (this, table); column.Name = col.Trim (); constraint.Columns.Add (column); } } constraints.Add (constraint); } r.Close (); } } catch (Exception) { // Don't raise error, if the table doesn't exists return an empty collection } finally { conn.Release (); } } } return constraints;
//http://www.sqlite.org/pragma.html public virtual ConstraintSchemaCollection GetConstraints(TableSchema table, ColumnSchema column) { if (table == null) { throw new ArgumentNullException("table"); } string columnName = column == null ? null : column.Name; ConstraintSchemaCollection constraints = new ConstraintSchemaCollection(); IPooledDbConnection conn = connectionPool.Request(); //fk and unique IDbCommand command = conn.CreateCommand("SELECT name, tbl_name FROM sqlite_master WHERE sql IS NULL AND type = 'index'"); try { using (command) { using (IDataReader r = command.ExecuteReader()) { while (r.Read()) { ConstraintSchema constraint = null; if (r.IsDBNull(1) || r.GetString(1) == null) { constraint = new UniqueConstraintSchema(this); } else { ForeignKeyConstraintSchema fkc = new ForeignKeyConstraintSchema(this); fkc.ReferenceTableName = r.GetString(1); constraint = fkc; } constraint.Name = r.GetString(0); constraints.Add(constraint); } r.Close(); } } //pk, column if (columnName != null) { command = conn.CreateCommand( "PRAGMA table_info('" + table.Name + "')" ); using (command) { using (IDataReader r = command.ExecuteReader()) { while (r.Read()) { if (r.GetInt32(5) == 1 && r.GetString(1) == columnName) { PrimaryKeyConstraintSchema constraint = new PrimaryKeyConstraintSchema(this); ColumnSchema priColumn = new ColumnSchema(this, table); priColumn.Name = r.GetString(1); constraint.Columns.Add(priColumn); constraint.IsColumnConstraint = true; constraint.Name = "pk_" + table.Name + "_" + priColumn.Name; constraints.Add(constraint); } } r.Close(); } } } } catch (Exception e) { QueryService.RaiseException(e); } conn.Release(); return(constraints); }
/// <summary> /// Generates a property to get a parent row. /// </summary> /// <param name="foreignKeyConstraintSchema">The foreign key that references the parent table.</param> public VoidConstructor(DataModelSchema dataModelSchema) { // /// <summary> // /// Creates the System.DataSet used to hold the data for the DataModel. // /// </summary> // internal DataModelDataSet(String connectionString) // { this.Comments.Add(new CodeCommentStatement("<summary>", true)); this.Comments.Add(new CodeCommentStatement(String.Format("Creates the System.DataSet used to hold the data for the {0}.", dataModelSchema.Name), true)); this.Comments.Add(new CodeCommentStatement("</summary>", true)); this.Attributes = MemberAttributes.Assembly; this.Parameters.Add(new CodeParameterDeclarationExpression(new CodeGlobalTypeReference(typeof(String)), "connectionString")); // this.connectionString = connectionString; this.Statements.Add( new CodeAssignStatement( new CodeFieldReferenceExpression(new CodeThisReferenceExpression(), "connectionString"), new CodeArgumentReferenceExpression("connectionString"))); // this.DataSetName = "DataModel"; this.Statements.Add( new CodeAssignStatement( new CodePropertyReferenceExpression(new CodeThisReferenceExpression(), "DataSetName"), new CodePrimitiveExpression(dataModelSchema.Name))); // this.CaseSensitive = true; this.Statements.Add( new CodeAssignStatement( new CodePropertyReferenceExpression(new CodeThisReferenceExpression(), "CaseSensitive"), new CodePrimitiveExpression(true))); // this.EnforceConstraints = true; this.Statements.Add( new CodeAssignStatement( new CodePropertyReferenceExpression(new CodeThisReferenceExpression(), "EnforceConstraints"), new CodePrimitiveExpression(true))); // Create each of the tables and add them to the data set. for (int tableIndex = 0; tableIndex < dataModelSchema.Tables.Count; tableIndex++) { // The 'Tables' element of the schema is indexed by the name of the table normally. We're going to initialize the tables in the order of their // ordinals (order in which they were declared). This is done primarily to be able to give each table a 'Ordinal' number that is used during // transaction processing to quickly find the table (without using the table name). KeyValuePair <String, TableSchema> keyValuePair = Enumerable.ElementAt(dataModelSchema.Tables, tableIndex); // this.tableConfiguration = new ConfigurationDataTable(); this.Statements.Add( new CodeAssignStatement( new CodeFieldReferenceExpression(new CodeThisReferenceExpression(), String.Format("table{0}", keyValuePair.Value.Name)), new CodeObjectCreateExpression(String.Format("{0}.{1}DataTable", keyValuePair.Value.DataModel.Name, keyValuePair.Value.Name)))); // this.tableConfiguration.Ordinal = 0; this.Statements.Add( new CodeAssignStatement( new CodePropertyReferenceExpression( new CodeFieldReferenceExpression(new CodeThisReferenceExpression(), String.Format("table{0}", keyValuePair.Value.Name)), "Ordinal"), new CodePrimitiveExpression(tableIndex))); // this.Tables.Add(this.tableConfiguration); this.Statements.Add( new CodeMethodInvokeExpression( new CodePropertyReferenceExpression(new CodeThisReferenceExpression(), "Tables"), "Add", new CodePropertyReferenceExpression(new CodeThisReferenceExpression(), String.Format("table{0}", keyValuePair.Value.Name)))); } // global::System.Data.ForeignKeyConstraint foreignKeyConstraint4 = new global::System.Data.ForeignKeyConstraint("FK_AccountBase_Account", new global::System.Data.DataColumn[] { // this.tableAccountBase.AccountBaseIdColumn}, new global::System.Data.DataColumn[] { // this.tableAccount.AccountIdColumn}); // this.tableAccountBase.Constraints.Add(foreignKeyConstraint4); // global::System.Data.ForeignKeyConstraint foreignKeyConstraint5 = new global::System.Data.ForeignKeyConstraint("FK_LotHandling_Account", new global::System.Data.DataColumn[] { // this.tableLotHandling.LotHandlingIdColumn}, new global::System.Data.DataColumn[] { // this.tableAccount.LotHandlingIdColumn}); // this.tableLotHandling.Constraints.Add(foreignKeyConstraint5); foreach (KeyValuePair <String, TableSchema> tablePair in dataModelSchema.Tables) { foreach (KeyValuePair <String, ConstraintSchema> constraintPair in tablePair.Value.Constraints) { if (constraintPair.Value is ForeignKeyConstraintSchema) { // Construct a foreign key constraint described by this schema. ForeignKeyConstraintSchema foreignKeyConstraintSchema = constraintPair.Value as ForeignKeyConstraintSchema; // Refers to the foreign key constraint. CodeVariableReferenceExpression foreignKeyConstraintExpression = new CodeRandomVariableReferenceExpression(); // global::System.Data.ForeignKeyConstraint foreignKeyConstraint6 = new global::System.Data.ForeignKeyConstraint("FK_Country_AccountBase", new global::System.Data.DataColumn[] { // this.tableCountry.CountryIdColumn}, new global::System.Data.DataColumn[] { // this.tableAccountBase.CountryIdColumn}); this.Statements.Add( new CodeVariableDeclarationStatement( new CodeGlobalTypeReference(typeof(ForeignKeyConstraint)), foreignKeyConstraintExpression.VariableName, new CodeForeignKeyConstraint(foreignKeyConstraintSchema))); this.Statements.Add( new CodeMethodInvokeExpression( new CodePropertyReferenceExpression(new CodeFieldReferenceExpression(new CodeThisReferenceExpression(), String.Format("table{0}", tablePair.Value.Name)), "Constraints"), "Add", foreignKeyConstraintExpression)); } } } // this.relationAccessRightAccessControl = new global::System.Data.DataRelation("FK_AccessRight_AccessControl", new global::System.Data.DataColumn[] { // this.tableAccessRight.AccessRightIdColumn}, new global::System.Data.DataColumn[] { // this.tableAccessControl.AccessRightIdColumn}, false); foreach (KeyValuePair <String, RelationSchema> relationPair in dataModelSchema.Relations) { // The name of the relation is decorated with the relation name when the relation between the child and the parent isn't unique. String relationName = relationPair.Value.IsDistinctPathToParent ? String.Format("relation{0}{1}", relationPair.Value.ParentTable.Name, relationPair.Value.ChildTable.Name) : String.Format("relation{0}{1}By{2}", relationPair.Value.ParentTable.Name, relationPair.Value.ChildTable.Name, relationPair.Value.Name); // this.relationRaceEmployee = new System.Data.DataRelation("FK_Race_Employee", new Teraque.Column[] { // Teraque.UnitTest.Server.DataModel.tableRace.RaceCodeColumn}, new Teraque.Column[] { // Teraque.UnitTest.Server.DataModel.tableEmployee.RaceCodeColumn}, false); // this.Relations.Add(Teraque.UnitTest.Server.DataModel.relationRaceEmployee); CodeExpression relationFieldExpression = new CodePropertyReferenceExpression(new CodeThisReferenceExpression(), relationName); this.Statements.Add(new CodeAssignStatement(relationFieldExpression, new CodeDataRelation(relationPair.Value))); this.Statements.Add( new CodeMethodInvokeExpression( new CodePropertyReferenceExpression(new CodeThisReferenceExpression(), "Relations"), "Add", relationFieldExpression)); } // Teraque.UnitTest.Server.DataModel.Configuration.InitializeRelations(); // Teraque.UnitTest.Server.DataModel.Department.InitializeRelations(); foreach (KeyValuePair <string, TableSchema> keyValuePair in dataModelSchema.Tables) { this.Statements.Add( new CodeMethodInvokeExpression(new CodeFieldReferenceExpression(new CodeThisReferenceExpression(), String.Format("table{0}", keyValuePair.Value.Name)), "InitializeRelations")); } // this.dataLock = new global::System.Threading.ReaderWriterLockSlim(); this.Statements.Add( new CodeAssignStatement( new CodeFieldReferenceExpression(new CodeThisReferenceExpression(), "dataLock"), new CodeObjectCreateExpression(new CodeGlobalTypeReference(typeof(ReaderWriterLockSlim))))); // this.identifier = global::System.Guid.NewGuid(); this.Statements.Add( new CodeAssignStatement( new CodePropertyReferenceExpression(new CodeThisReferenceExpression(), "identifier"), new CodeMethodInvokeExpression(new CodeGlobalTypeReferenceExpression(typeof(Guid)), "NewGuid"))); // this.rowVersion = 0; this.Statements.Add( new CodeAssignStatement( new CodePropertyReferenceExpression(new CodeThisReferenceExpression(), "rowVersion"), new CodePrimitiveExpression(0L))); // this.transactionLog = new global::System.Collections.Generic.LinkedList<TransactionLogItem>(); this.Statements.Add( new CodeAssignStatement( new CodePropertyReferenceExpression(new CodeThisReferenceExpression(), "transactionLog"), new CodeObjectCreateExpression(new CodeTypeReference("global::System.Collections.Generic.LinkedList<TransactionLogItem>")))); // this.transactionLogBatchSize = 10000; this.Statements.Add( new CodeAssignStatement( new CodePropertyReferenceExpression(new CodeThisReferenceExpression(), "transactionLogBatchSize"), new CodePrimitiveExpression(10000))); // this.logCompressionInterval = global::System.TimeSpan.FromSeconds(10); this.Statements.Add( new CodeAssignStatement( new CodePropertyReferenceExpression(new CodeThisReferenceExpression(), "logCompressionInterval"), new CodeMethodInvokeExpression( new CodeGlobalTypeReferenceExpression(typeof(TimeSpan)), "FromSeconds", new CodePrimitiveExpression(10)))); // this.transactionLogItemAge = global::System.TimeSpan.FromSeconds(60); this.Statements.Add( new CodeAssignStatement( new CodePropertyReferenceExpression(new CodeThisReferenceExpression(), "transactionLogItemAge"), new CodeMethodInvokeExpression( new CodeGlobalTypeReferenceExpression(typeof(TimeSpan)), "FromSeconds", new CodePrimitiveExpression(60)))); // this.transactionLogLock = new global::System.Threading.ReaderWriterLockSlim(); this.Statements.Add( new CodeAssignStatement( new CodeFieldReferenceExpression(new CodeThisReferenceExpression(), "transactionLogLock"), new CodeObjectCreateExpression(new CodeGlobalTypeReference(typeof(ReaderWriterLockSlim))))); // this.compressorThread = new global::System.Threading.Thread(this.CompressLog); this.Statements.Add( new CodeAssignStatement( new CodePropertyReferenceExpression(new CodeThisReferenceExpression(), "compressorThread"), new CodeObjectCreateExpression( new CodeGlobalTypeReference(typeof(Thread)), new CodeMethodReferenceExpression(new CodeThisReferenceExpression(), "CompressLog")))); // this.compressorThread.IsBackground = true; this.Statements.Add( new CodeAssignStatement( new CodePropertyReferenceExpression( new CodePropertyReferenceExpression(new CodeThisReferenceExpression(), "compressorThread"), "IsBackground"), new CodePrimitiveExpression(true))); // this.compressorThread.Name = "Transaction Log Compressor"; this.Statements.Add( new CodeAssignStatement( new CodePropertyReferenceExpression(new CodePropertyReferenceExpression(new CodeThisReferenceExpression(), "compressorThread"), "Name"), new CodePrimitiveExpression("Transaction Log Compressor"))); // this.compressorThread.Priority = global::System.Threading.ThreadPriority.Lowest; this.Statements.Add( new CodeAssignStatement( new CodePropertyReferenceExpression( new CodePropertyReferenceExpression(new CodeThisReferenceExpression(), "compressorThread"), "Priority"), new CodePropertyReferenceExpression(new CodeGlobalTypeReferenceExpression(typeof(ThreadPriority)), "Lowest"))); // this.compressorThread.Start(); this.Statements.Add( new CodeMethodInvokeExpression(new CodePropertyReferenceExpression(new CodeThisReferenceExpression(), "compressorThread"), "Start")); // } // this.LoadData(); this.Statements.Add(new CodeMethodInvokeExpression(new CodeThisReferenceExpression(), "LoadData")); // } }
public override ConstraintSchemaCollection GetTableConstraints (TableSchema table) { ConstraintSchemaCollection constraints = new ConstraintSchemaCollection (); using (IPooledDbConnection conn = connectionPool.Request ()) { using (IDbCommand command = conn.CreateCommand (string.Format (@"select sysobjects.name, sysobjects.xtype from sysobjects inner join sysobjects sysobjectsParents ON sysobjectsParents.id = sysobjects.parent_obj where sysobjectsParents.name = '{0}' and sysobjects.xtype in ('C', 'UQ', 'F','PK','CK')", table.Name))) try { using (IDataReader r = command.ExecuteReader()) { while (r.Read ()) { ConstraintSchema constraint = null; switch (r.GetString (1)) { case "F": //foreign key constraint = new ForeignKeyConstraintSchema (this); break; case "PK": //primary key constraint = new PrimaryKeyConstraintSchema (this); break; case "C": case "CK": //check constraint constraint = new CheckConstraintSchema (this); break; case "UQ": constraint = new UniqueConstraintSchema (this); break; default: break; } if (constraint != null) { constraint.Name = r.GetString (0); constraints.Add (constraint); } } r.Close (); } } catch (Exception e) { QueryService.RaiseException (e); } finally { conn.Release (); } } return constraints;
/// <summary> /// Generates the DDL for a table. /// </summary> /// <param name="streamWriter">The file to which the DDL is written.</param> /// <param name="tableSchema">The schema description of the table.</param> private static void GenerateTable(StreamWriter streamWriter, TableSchema tableSchema) { // Generate the prolog for this table. streamWriter.WriteLine("/* The {0} Table */", tableSchema.Name); // Generate a prolog showing the time of creation and the current version of the table for the log file. streamWriter.WriteLine("if not exists (select * from \"VersionControl\" where \"Name\" = '{0}')", tableSchema.Name); streamWriter.WriteLine(" print convert(varchar, getdate(), 120) + 'Z <Undefined>: \"{0}\" doesn''t exist in the catalogs.'", tableSchema.Name); streamWriter.WriteLine("else"); streamWriter.WriteLine("begin"); streamWriter.WriteLine(" declare @revision \"decimal\""); streamWriter.WriteLine(" select @revision = \"Revision\" from \"VersionControl\" where \"Name\" = '{0}'", tableSchema.Name); streamWriter.WriteLine(" print convert(varchar, getdate(), 120) + 'Z Table: \"{0}\", Initial revision: ' + convert(varchar, @revision)", tableSchema.Name); streamWriter.WriteLine("end"); streamWriter.WriteLine(); // The table schema is only run if the version control table indicates that the update is needed. streamWriter.WriteLine("/* This checks the version control table to determine if an update is needed. */"); streamWriter.WriteLine("declare @currentRevision \"decimal\""); streamWriter.WriteLine("declare @requiredRevision \"decimal\""); streamWriter.WriteLine("select @currentRevision = isnull((select \"Revision\" from \"VersionControl\" where \"VersionControl\".\"Name\" = '{0}'), -1.0)", tableSchema.Name); streamWriter.WriteLine("select @requiredRevision = isnull((select \"Revision\" from \"VersionHistory\", \"VersionTag\""); streamWriter.WriteLine(" where \"VersionHistory\".\"Active\" = 1 and \"VersionHistory\".\"Label\" = \"VersionTag\".\"Label\" and \"VersionTag\".\"Name\" = '{0}'), {1})", tableSchema.Name, tableSchema.DataModel.Version); streamWriter.WriteLine("if @currentRevision < {0} and {0} <= @requiredRevision", tableSchema.DataModel.Version); streamWriter.WriteLine("begin"); streamWriter.WriteLine(""); // This transaction will remove the previous version of the table and create the new version. streamWriter.WriteLine(" /* The revision must be completed as a unit. */"); streamWriter.WriteLine(" begin transaction"); streamWriter.WriteLine(""); streamWriter.WriteLine(" /* Remove the object and any dependancies. */"); foreach (KeyValuePair <string, ConstraintSchema> constraintPair in tableSchema.Constraints) { if (constraintPair.Value is ForeignKeyConstraintSchema) { ForeignKeyConstraintSchema foreignKeyConstraintSchema = constraintPair.Value as ForeignKeyConstraintSchema; streamWriter.WriteLine(" if exists (select * from sysobjects where type = 'F' and name = '{0}')", foreignKeyConstraintSchema.Name); streamWriter.WriteLine(" alter table \"{0}\" drop constraint \"{1}\"", foreignKeyConstraintSchema.Table.Name, foreignKeyConstraintSchema.Name); } } streamWriter.WriteLine(" if exists (select * from sysobjects where type = 'U' and name = '{0}')", tableSchema.Name); streamWriter.WriteLine(" drop table \"{0}\"", tableSchema.Name); streamWriter.WriteLine(""); // The table is described here. streamWriter.WriteLine(" /* Create the table. */"); streamWriter.WriteLine(string.Format(" create table \"{0}\" (", tableSchema.Name)); // Generate each of the column descriptions. foreach (ColumnSchema columnSchema in tableSchema.Columns.Values) { streamWriter.WriteLine(string.Format(" \"{0}\" {1} {2},", columnSchema.Name, GetSqlDataType(columnSchema), columnSchema.IsNullable ? "null" : "not null")); } // These columns are always included for house keeping. streamWriter.WriteLine(" \"IsArchived\" \"bit\" not null,"); streamWriter.WriteLine(" \"IsDeleted\" \"bit\" not null,"); // The table is always generated on the primary (default) device. streamWriter.WriteLine(" ) on \"PRIMARY\""); streamWriter.WriteLine(""); // Generate the keys, foreign keys and defaults on this table. GenerateKeys(streamWriter, tableSchema); GenerateIndices(streamWriter, tableSchema); GenerateForeignKeys(streamWriter, tableSchema); GenerateDefaults(streamWriter, tableSchema); // This will update the version control table to indicate that the table was updated to the new version. streamWriter.WriteLine(" /* Update the versionControl table to reflect the change. */"); streamWriter.WriteLine(" if exists (select * from \"VersionControl\" where \"Name\" = '{0}')", tableSchema.Name); streamWriter.WriteLine(" update \"VersionControl\" set \"Revision\" = {0} where \"Name\" = '{1}'", tableSchema.DataModel.Version, tableSchema.Name); streamWriter.WriteLine(" else"); streamWriter.WriteLine(" insert \"VersionControl\" (\"Name\", \"Revision\") select '{0}', {1}", tableSchema.Name, tableSchema.DataModel.Version); streamWriter.WriteLine(""); // Commit or reject the changes to the table. streamWriter.WriteLine(" /* Commit the changes to the table. */"); streamWriter.WriteLine(" commit transaction"); streamWriter.WriteLine(""); streamWriter.WriteLine("end"); streamWriter.WriteLine("go"); streamWriter.WriteLine(""); // Generate the epilog for a successful update. streamWriter.WriteLine("if @@error = 0"); streamWriter.WriteLine("begin"); streamWriter.WriteLine(" declare @newRevision \"decimal\""); streamWriter.WriteLine(" select @newRevision = \"Revision\" from \"VersionControl\" where \"Name\" = '{0}'", tableSchema.Name); streamWriter.WriteLine(" print convert(varchar, getdate(), 120) + 'Z Table: \"{0}\", Final revision: ' + convert(varchar, @newRevision)", tableSchema.Name); streamWriter.WriteLine("end"); streamWriter.WriteLine("else"); streamWriter.WriteLine("begin"); streamWriter.WriteLine(" declare @oldRevision \"decimal\""); streamWriter.WriteLine(" select @oldRevision = isnull((select \"Revision\" from \"VersionControl\" where \"Name\" = '{0}'), 0.0)", tableSchema.Name); streamWriter.WriteLine(" print convert(varchar, getdate(), 120) + 'Z Table: \"{0}\", Error upgrading from revision: ' + convert(varchar, @oldRevision)", tableSchema.Name); streamWriter.WriteLine("end"); streamWriter.WriteLine("go"); streamWriter.WriteLine(""); }
/// <summary> /// Create a series of statements that resolves an external reference. /// </summary> /// <param name="targetVariable">The variable that recieves the resolved row.</param> /// <param name="transactionExpression">The manager for the middle tier transaction.</param> /// <param name="foreignKeyConstraintSchema">The foreign constraint that is to be resolved.</param> public CodeResolveForeignKeyExpression(CodeVariableReferenceExpression targetVariable, CodeVariableReferenceExpression transactionExpression, CodeExpression rootKeyExpression, ForeignKeyConstraintSchema foreignKeyConstraintSchema) { // The middle tier context is used by the intermediate expressions to lock rows. this.transactionExpression = transactionExpression; // This will recurse into the relations and build the statements needed to resolve the external row reference. RecurseIntoRelation(targetVariable, foreignKeyConstraintSchema, rootKeyExpression, foreignKeyConstraintSchema); }
protected virtual string GetConstraintString(ConstraintSchema constraint) { bool first = true; //PRIMARY KEY [sort-order] [ conflict-clause ] [AUTOINCREMENT] //UNIQUE [ conflict-clause ] //CHECK ( expr ) //COLLATE collation-name StringBuilder sb = new StringBuilder(); switch (constraint.ConstraintType) { case ConstraintType.PrimaryKey: sb.Append("PRIMARY KEY ("); //TODO: auto inc + sort first = true; foreach (ColumnSchema col in constraint.Columns) { if (!first) { sb.Append(","); } sb.Append(col.Name); first = false; } sb.Append(")"); break; case ConstraintType.Unique: sb.Append("UNIQUE ("); first = true; foreach (ColumnSchema col in constraint.Columns) { if (!first) { sb.Append(","); } sb.Append(col.Name); first = false; } sb.Append(")"); break; case ConstraintType.Check: CheckConstraintSchema chk = constraint as CheckConstraintSchema; sb.Append("CHECK ("); sb.Append(chk.Source); sb.Append(")"); break; case ConstraintType.ForeignKey: sb.Append("FOREIGN KEY "); sb.Append(GetColumnsString(constraint.Columns, true)); sb.Append(" REFERENCES "); ForeignKeyConstraintSchema fk = constraint as ForeignKeyConstraintSchema; string tableName; if (fk.ReferenceTableName.IndexOf('.') > 0) { tableName = fk.ReferenceTableName.Substring(fk.ReferenceTableName.IndexOf('.') + 1); } else { tableName = fk.ReferenceTableName; } sb.Append(tableName); sb.Append(' '); if (fk.ReferenceColumns != null) { sb.Append(GetColumnsString(fk.ReferenceColumns, true)); } sb.Append(Environment.NewLine); sb.Append(" ON DELETE "); sb.Append(GetConstraintActionString(fk.DeleteAction)); sb.Append(Environment.NewLine); sb.Append(" ON UPDATE "); sb.Append(GetConstraintActionString(fk.UpdateAction)); break; default: throw new NotImplementedException(); } return(sb.ToString()); }
/// <summary> /// Resolves the primary key. /// </summary> /// <param name="tableSchema">A description of a table.</param> /// <param name="uniqueConstraintParameterItem">A description of a unique key parameter.</param> public CodeResolvePrimaryKeyStatements(TableSchema tableSchema, CodeVariableReferenceExpression transactionExpression, UniqueConstraintParameterItem uniqueConstraintParameterItem, CodeExpression targetDataSet) { // This keeps us from having to pass this into the recursion. this.targetDataSet = targetDataSet; // All the external identifiers have been resolved. Now it is time to see if the record exists or if it has to be // created. Finding the record requires a unique index. If there are more than one unique index, a decision needs to // be made as to which one should be used. The configuration will drive that decision. If there is only one unique // constraint, then the decision doesn't need to be made. UniqueConstraintSchema[] uniqueConstraints = tableSchema.UniqueConstraintSchemas; CodeVariableReferenceExpression rowExpression = uniqueConstraintParameterItem.CodeVariableReferenceExpression; CodeVariableReferenceExpression uniqueKeyExpression = new CodeRandomVariableReferenceExpression(); // Optimized code is provided when there is only one unique constraint on a table. This saves the database // administrator from having to configure every single table in the data model with a description of the unique index // that is to be used when finding a row in that table. If there is more than one unique constraint on a table, a // value will need to be provided in the configuration to tell the loader which one to use. if (uniqueConstraints.Length == 1) { // If there are no foreign keys attached to the selected primary key, then the key value is taken directly from // the input parameters. ForeignKeyConstraintSchema foreignKeyConstraintSchema = uniqueConstraints[0].ForeignKey; if (foreignKeyConstraintSchema == null) { this.Add(new CodeVariableDeclarationStatement( new CodeGlobalTypeReference(typeof(Object[])), uniqueKeyExpression.VariableName, new CodeArgumentReferenceExpression(uniqueConstraintParameterItem.Name))); this.Add( new CodeVariableDeclarationStatement( new CodeTypeReference(String.Format("{0}Row", tableSchema.Name)), uniqueConstraintParameterItem.CodeVariableReferenceExpression.VariableName, new CodeMethodInvokeExpression( new CodePropertyReferenceExpression( new CodeFieldReferenceExpression(targetDataSet, String.Format("table{0}", tableSchema.Name)), uniqueConstraints[0].Name), "Find", uniqueKeyExpression))); } else { // When there are foreign keys associated with the selected unique constraint, the foreign keys are resolved // using the key passed in as a parameter to this method. This is a recursive operation that digs through the // table hierarchy until a record is found that matches the key. CodeVariableReferenceExpression rootRowExpression = new CodeRandomVariableReferenceExpression(); this.AddRange( new CodeResolveForeignKeyExpression( rootRowExpression, transactionExpression, new CodeArgumentReferenceExpression(uniqueConstraintParameterItem.Name), foreignKeyConstraintSchema, targetDataSet)); List <CodeExpression> keyItems = new List <CodeExpression>(); for (int columnIndex = 0; columnIndex < tableSchema.PrimaryKey.Columns.Length; columnIndex++) { keyItems.Add(new CodePropertyReferenceExpression(rootRowExpression, foreignKeyConstraintSchema.RelatedColumns[columnIndex].Name)); } this.Add( new CodeVariableDeclarationStatement( new CodeGlobalTypeReference(typeof(Object[])), uniqueKeyExpression.VariableName, new CodeArrayCreateExpression(new CodeGlobalTypeReference(typeof(Object)), keyItems.ToArray()))); this.Add( new CodeVariableDeclarationStatement( new CodeTypeReference(String.Format("{0}Row", tableSchema.Name)), uniqueConstraintParameterItem.CodeVariableReferenceExpression.VariableName, new CodeMethodInvokeExpression( new CodePropertyReferenceExpression( new CodeFieldReferenceExpression(targetDataSet, String.Format("table{0}", tableSchema.Name)), uniqueConstraints[0].Name), "Find", uniqueKeyExpression))); } } else { // // This will find and lock the configuration row that selects the unique constraint for this table. // object[] configurationKey3 = new object[] { // configurationId, // "ObjectTree"}; // ConfigurationRow configurationRow4 = DataModel.Configuration.ConfigurationKey.Find(configurationKey3); // if ((configurationRow4 == null)) { // throw new global::System.ServiceModel.FaultException<RecordNotFoundFault>(new global::Teraque.RecordNotFoundFault("Attempt to access a Configuration record ({0}) that doesn\'t exist", configurationKey3)); // } // configurationRow4.AcquireReaderLock(middleTierTransaction.AdoResourceManager.Guid, DataModel.lockTimeout); // middleTierTransaction.AdoResourceManager.AddLock(configurationRow4); // if ((configurationRow4.RowState == global::System.Data.DataRowState.Detached)) { // throw new global::System.ServiceModel.FaultException<RecordNotFoundFault>(new global::Teraque.RecordNotFoundFault("Attempt to access a Configuration record ({0}) that doesn\'t exist", configurationKey3)); // } CodeVariableReferenceExpression configurationKeyExpression = new CodeRandomVariableReferenceExpression(); this.Add( new CodeVariableDeclarationStatement( new CodeGlobalTypeReference(typeof(Object[])), configurationKeyExpression.VariableName, new CodeKeyCreateExpression(new CodeArgumentReferenceExpression("configurationId"), new CodePrimitiveExpression(tableSchema.Name)))); CodeVariableReferenceExpression configurationRowExpression = new CodeRandomVariableReferenceExpression(); this.Add( new CodeVariableDeclarationStatement( new CodeTypeReference("ConfigurationRow"), configurationRowExpression.VariableName, new CodeMethodInvokeExpression( new CodePropertyReferenceExpression( new CodeFieldReferenceExpression(targetDataSet, "tableConfiguration"), "ConfigurationKey"), "Find", configurationKeyExpression))); TableSchema configurationTableSchema = tableSchema.DataModel.Tables["Configuration"]; this.Add(new CodeCheckRecordExistsStatement(configurationTableSchema, configurationRowExpression, configurationKeyExpression)); this.Add(new CodeAcquireRecordReaderLockExpression(transactionExpression, configurationRowExpression, tableSchema.DataModel)); this.Add(new CodeAddLockToTransactionExpression(transactionExpression, configurationRowExpression)); this.Add(new CodeCheckRecordDetachedStatement(configurationTableSchema, configurationRowExpression, configurationKeyExpression)); // // This constructs a key based on the unique constraint specified by the configuration. // object[] objectTreeKey2 = null; // if ((configurationRow4.IndexName == "ObjectTreeKeyExternalId0")) { // objectTreeKey2 = new object[] { // externalId0}; // } // if ((configurationRow4.IndexName == "ObjectTreeKeyParentIdChildId")) { // objectTreeKey2 = new object[] { // parentId, // childId}; // } CodePropertyReferenceExpression keyNameExpression = new CodePropertyReferenceExpression(configurationRowExpression, "IndexName"); this.Add(new CodeVariableDeclarationStatement(new CodeGlobalTypeReference(typeof(Object[])), uniqueKeyExpression.VariableName, new CodePrimitiveExpression(null))); foreach (UniqueConstraintSchema uniqueConstraintSchema in uniqueConstraints) { // For each unique index on this table, a key is created that matches the key columns of the index selected by // the configuration. CodeConditionStatement ifConfiguration = new CodeConditionStatement(new CodeBinaryOperatorExpression(keyNameExpression, CodeBinaryOperatorType.IdentityEquality, new CodePrimitiveExpression(uniqueConstraintSchema.Name))); // If there are no foreign keys attached to the selected primary key, then the key value is taken directly from // the input parameters. ForeignKeyConstraintSchema foreignKeyConstraintSchema = uniqueConstraintSchema.ForeignKey; if (foreignKeyConstraintSchema == null) { // securityKey1 = new object[] { // objectRow4.ObjectId}; ifConfiguration.TrueStatements.Add(new CodeAssignStatement(uniqueKeyExpression, new CodeArgumentReferenceExpression(uniqueConstraintParameterItem.Name))); } else { // When there are foreign keys associated with the selected unique constraint, the foreign keys are resolved // using the key passed in as a parameter to this method. This is a recursive operation that digs through the // table hierarchy until a record is found that matches the key. CodeVariableReferenceExpression rootRowExpression = new CodeRandomVariableReferenceExpression(); ifConfiguration.TrueStatements.AddRange(new CodeResolveForeignKeyExpression(rootRowExpression, transactionExpression, new CodeArgumentReferenceExpression(uniqueConstraintParameterItem.Name), foreignKeyConstraintSchema, targetDataSet)); List <CodeExpression> keyItems = new List <CodeExpression>(); for (int columnIndex = 0; columnIndex < tableSchema.PrimaryKey.Columns.Length; columnIndex++) { keyItems.Add(new CodePropertyReferenceExpression(rootRowExpression, foreignKeyConstraintSchema.RelatedColumns[columnIndex].Name)); } ifConfiguration.TrueStatements.Add(new CodeAssignStatement(uniqueKeyExpression, new CodeArrayCreateExpression(new CodeGlobalTypeReference(typeof(Object)), keyItems.ToArray()))); } // } this.Add(ifConfiguration); } // // Use the index and the key specified by the configuration to find the record. // IObjectTreeIndex dataIndex2 = ((IObjectTreeIndex)(DataModel.ObjectTree.Indices[configurationRow4.IndexName])); // ObjectTreeRow objectTreeRow = dataIndex2.Find(objectTreeKey2); CodeTypeReference dataIndexType = new CodeTypeReference(String.Format("I{0}Index", tableSchema.Name)); CodeVariableReferenceExpression dataIndexExpression = new CodeRandomVariableReferenceExpression(); this.Add(new CodeVariableDeclarationStatement(dataIndexType, dataIndexExpression.VariableName, new CodeCastExpression(dataIndexType, new CodeIndexerExpression(new CodePropertyReferenceExpression(new CodeFieldReferenceExpression(targetDataSet, String.Format("table{0}", tableSchema.Name)), "Indices"), keyNameExpression)))); this.Add(new CodeCheckIndexExistsStatement(dataIndexExpression, tableSchema, keyNameExpression)); this.Add(new CodeVariableDeclarationStatement(new CodeTypeReference(String.Format("{0}Row", tableSchema.Name)), rowExpression.VariableName, new CodeMethodInvokeExpression(dataIndexExpression, "Find", uniqueKeyExpression))); } // if ((engineerRow == null)) { // throw new global::System.ServiceModel.FaultException<RecordNotFoundFault>(new global::Teraque.RecordNotFoundFault("Attempt to access a Engineer record ({0}) that doesn\'t exist", engineerKey5)); // } // engineerRow.AcquireReaderLock(middleTierTransaction.AdoResourceManager.Guid, DataModel.lockTimeout); // middleTierTransaction.AdoResourceManager.AddLock(engineerRow); // if ((engineerRow.RowState == global::System.Data.DataRowState.Detached)) { // throw new global::System.ServiceModel.FaultException<RecordNotFoundFault>(new global::Teraque.RecordNotFoundFault("Attempt to access a Engineer record ({0}) that doesn\'t exist", engineerKey5)); // } this.Add(new CodeCheckRecordExistsStatement(tableSchema, rowExpression, uniqueKeyExpression)); this.Add(new CodeAcquireRecordReaderLockExpression(transactionExpression, rowExpression, tableSchema.DataModel)); this.Add(new CodeAddLockToTransactionExpression(transactionExpression, rowExpression)); this.Add(new CodeCheckRecordDetachedStatement(tableSchema, rowExpression, uniqueKeyExpression)); }
/// <summary> /// Resolves the variables related to foreign tables. /// </summary> /// <param name="tableSchema">A description of a table.</param> /// <param name="transactionExpression">Used to support locking and provide database resources.</param> /// <param name="foreignKeyConstraintParameterItem">A description of a variable related to a foreign table.</param> public CodeResolveExternalVariableStatements(TableSchema tableSchema, CodeVariableReferenceExpression transactionExpression, ForeignKeyConstraintParameterItem foreignKeyConstraintParameterItem) { // This is the foreign key that will be resolved here. ForeignKeyConstraintSchema foreignKeyConstraintSchema = foreignKeyConstraintParameterItem.ForeignKeyConstraintSchema; // // This will resolve the optional managerKey foreign key. // object managerId; foreach (ForeignKeyVariableItem foreignKeyVariableItem in foreignKeyConstraintParameterItem.ForeignKeyVariables) { this.Add(new CodeVariableDeclarationStatement(foreignKeyVariableItem.DataType, foreignKeyVariableItem.Expression.VariableName)); } // Optional parameters tied to foreign constraints can be explicitly set to DBNull.Value by passing an empty key. They // can implicitly be set to the default by passing null. CodeStatementCollection codeStatementCollection = this; if (foreignKeyConstraintParameterItem.IsNullable) { // if ((managerKey == null)) { // managerId = null; // } CodeConditionStatement ifIsNull = new CodeConditionStatement(new CodeBinaryOperatorExpression(new CodeArgumentReferenceExpression(foreignKeyConstraintParameterItem.Name), CodeBinaryOperatorType.IdentityEquality, new CodePrimitiveExpression(null))); codeStatementCollection = ifIsNull.FalseStatements; foreach (ForeignKeyVariableItem foreignKeyVariableItem in foreignKeyConstraintParameterItem.ForeignKeyVariables) { ifIsNull.TrueStatements.Add(new CodeAssignStatement(foreignKeyVariableItem.Expression, new CodePrimitiveExpression(null))); } // else { // if ((managerKey.Length == 0)) { // managerId = global::System.DBNull.Value; // } CodeConditionStatement ifArrayEmpty = new CodeConditionStatement(new CodeBinaryOperatorExpression(new CodePropertyReferenceExpression(new CodeArgumentReferenceExpression(foreignKeyConstraintParameterItem.Name), "Length"), CodeBinaryOperatorType.IdentityEquality, new CodePrimitiveExpression(0))); foreach (ForeignKeyVariableItem foreignKeyVariableItem in foreignKeyConstraintParameterItem.ForeignKeyVariables) { ifArrayEmpty.TrueStatements.Add(new CodeAssignStatement(foreignKeyVariableItem.Expression, new CodePropertyReferenceExpression(new CodeGlobalTypeReferenceExpression(typeof(System.DBNull)), "Value"))); } codeStatementCollection = ifArrayEmpty.FalseStatements; ifIsNull.FalseStatements.Add(ifArrayEmpty); // else { this.Add(ifIsNull); } // object[] configurationKey2 = new object[] { // configurationId, // "FK_Manager_Engineer"}; // ConfigurationRow configurationRow3 = DataModel.Configuration.ConfigurationKey.Find(configurationKey2); // if ((configurationRow3 == null)) { // throw new global::System.ServiceModel.FaultException<RecordNotFoundFault>(new global::FluidTrade.Core.RecordNotFoundFault("Attempt to access a Configuration record ({0}) that doesn\'t exist", configurationKey2)); // } // configurationRow3.AcquireReaderLock(middleTierTransaction.AdoResourceManager.Guid, DataModel.lockTimeout); // middleTierTransaction.AdoResourceManager.AddLock(configurationRow3); // if ((configurationRow3.RowState == global::System.Data.DataRowState.Detached)) { // throw new global::System.ServiceModel.FaultException<RecordNotFoundFault>(new global::FluidTrade.Core.RecordNotFoundFault("Attempt to access a Configuration record ({0}) that doesn\'t exist", configurationKey2)); // } // IObjectIndex dataIndex1 = ((IObjectIndex)(DataModel.Object.Indices[configurationRow3.IndexName])); // ObjectRow objectRow4 = dataIndex1.Find(managerKey); // if ((objectRow4 == null)) { // throw new global::System.ServiceModel.FaultException<RecordNotFoundFault>(new global::FluidTrade.Core.RecordNotFoundFault("Attempt to access a Object record ({0}) that doesn\'t exist", managerKey)); // } // objectRow4.AcquireReaderLock(middleTierTransaction.AdoResourceManager.Guid, DataModel.lockTimeout); // middleTierTransaction.AdoResourceManager.AddLock(objectRow4); // if ((objectRow4.RowState == global::System.Data.DataRowState.Detached)) { // throw new global::System.ServiceModel.FaultException<RecordNotFoundFault>(new global::FluidTrade.Core.RecordNotFoundFault("Attempt to access a Object record ({0}) that doesn\'t exist", managerKey)); // } // // Employee level of the managerKey foreign key search. // object[] employeeKey3 = new object[] { // objectRow4.ObjectId}; // EmployeeRow employeeRow5 = DataModel.Employee.EmployeeKey.Find(employeeKey3); // if ((employeeRow5 == null)) { // throw new global::System.ServiceModel.FaultException<RecordNotFoundFault>(new global::FluidTrade.Core.RecordNotFoundFault("Attempt to access a Employee record ({0}) that doesn\'t exist", employeeKey3)); // } // employeeRow5.AcquireReaderLock(middleTierTransaction.AdoResourceManager.Guid, DataModel.lockTimeout); // middleTierTransaction.AdoResourceManager.AddLock(employeeRow5); // if ((employeeRow5.RowState == global::System.Data.DataRowState.Detached)) { // throw new global::System.ServiceModel.FaultException<RecordNotFoundFault>(new global::FluidTrade.Core.RecordNotFoundFault("Attempt to access a Employee record ({0}) that doesn\'t exist", employeeKey3)); // } // // Manager level of the managerKey foreign key search. // object[] managerKey4 = new object[] { // employeeRow5.EmployeeId}; // ManagerRow managerRow6 = DataModel.Manager.ManagerKey.Find(managerKey4); // if ((managerRow6 == null)) { // throw new global::System.ServiceModel.FaultException<RecordNotFoundFault>(new global::FluidTrade.Core.RecordNotFoundFault("Attempt to access a Manager record ({0}) that doesn\'t exist", managerKey4)); // } // managerRow6.AcquireReaderLock(middleTierTransaction.AdoResourceManager.Guid, DataModel.lockTimeout); // middleTierTransaction.AdoResourceManager.AddLock(managerRow6); // if ((managerRow6.RowState == global::System.Data.DataRowState.Detached)) { // throw new global::System.ServiceModel.FaultException<RecordNotFoundFault>(new global::FluidTrade.Core.RecordNotFoundFault("Attempt to access a Manager record ({0}) that doesn\'t exist", managerKey4)); // } CodeVariableReferenceExpression rootRowExpression = new CodeRandomVariableReferenceExpression(); CodeArgumentReferenceExpression rootKeyExpression = new CodeArgumentReferenceExpression(foreignKeyConstraintParameterItem.Name); codeStatementCollection.AddRange(new CodeResolveForeignKeyExpression(rootRowExpression, transactionExpression, rootKeyExpression, foreignKeyConstraintSchema)); // managerId = managerRow6.ManagerId; // } for (int columnIndex = 0; columnIndex < foreignKeyConstraintSchema.Columns.Length; columnIndex++) { if (foreignKeyConstraintParameterItem.ForeignKeyVariables[columnIndex] != null) { codeStatementCollection.Add(new CodeAssignStatement(foreignKeyConstraintParameterItem.ForeignKeyVariables[columnIndex].Expression, new CodePropertyReferenceExpression(rootRowExpression, foreignKeyConstraintSchema.RelatedColumns[columnIndex].Name))); } } // } }
/// <summary> /// Create a static constructor for the data model. /// </summary> /// <param name="dataModelSchema">A description of the data model.</param> public StaticConstructor(DataModelSchema dataModelSchema) { /// <summary> // /// Static Constructor for the DataModel. // /// </summary> // static DataModel() { this.Comments.Add(new CodeCommentStatement("<summary>", true)); this.Comments.Add(new CodeCommentStatement(string.Format("Static Constructor for the {0}.", dataModelSchema.Name), true)); this.Comments.Add(new CodeCommentStatement("</summary>", true)); // DataModel.purgeBufferSize = FluidTrade.Guardian.Properties.Settings.Default.PurgeBufferSize; this.Statements.Add( new CodeAssignStatement( new CodeFieldReferenceExpression(new CodeTypeReferenceExpression(dataModelSchema.Name), "purgeBufferSize"), new CodePropertyReferenceExpression( new CodePropertyReferenceExpression( new CodePropertyReferenceExpression( new CodeTypeReferenceExpression(string.Format("{0}.{1}", dataModelSchema.TargetNamespace, "Properties")), "Settings"), "Default"), "PurgeBufferSize"))); // FluidTrade.UnitTest.Server.DataModel.dataSet = new global::System.Data.DataSet(); // FluidTrade.UnitTest.Server.DataModel.dataSet.DataSetName = "DataModel"; // FluidTrade.UnitTest.Server.DataModel.dataSet.CaseSensitive = true; // FluidTrade.UnitTest.Server.DataModel.dataSet.EnforceConstraints = true; this.Statements.Add(new CodeAssignStatement(new CodePropertyReferenceExpression(new CodeTypeReferenceExpression(dataModelSchema.Name), "dataSet"), new CodeObjectCreateExpression(new CodeGlobalTypeReference(typeof(System.Data.DataSet))))); this.Statements.Add(new CodeAssignStatement(new CodePropertyReferenceExpression(new CodePropertyReferenceExpression(new CodeTypeReferenceExpression(dataModelSchema.Name), "dataSet"), "DataSetName"), new CodePrimitiveExpression(dataModelSchema.Name))); this.Statements.Add(new CodeAssignStatement(new CodePropertyReferenceExpression(new CodePropertyReferenceExpression(new CodeTypeReferenceExpression(dataModelSchema.Name), "dataSet"), "CaseSensitive"), new CodePrimitiveExpression(true))); this.Statements.Add(new CodeAssignStatement(new CodePropertyReferenceExpression(new CodePropertyReferenceExpression(new CodeTypeReferenceExpression(dataModelSchema.Name), "dataSet"), "EnforceConstraints"), new CodePrimitiveExpression(true))); // FluidTrade.UnitTest.Server.DataModel.tableConfiguration = new ConfigurationDataTable(); // FluidTrade.UnitTest.Server.DataModel.dataSet.Tables.Add(FluidTrade.UnitTest.Server.DataModel.tableConfiguration); // FluidTrade.UnitTest.Server.DataModel.tableDepartment = new DepartmentDataTable(); // FluidTrade.UnitTest.Server.DataModel.dataSet.Tables.Add(FluidTrade.UnitTest.Server.DataModel.tableDepartment); // FluidTrade.UnitTest.Server.DataModel.tableEmployee = new EmployeeDataTable(); // FluidTrade.UnitTest.Server.DataModel.dataSet.Tables.Add(FluidTrade.UnitTest.Server.DataModel.tableEmployee); // FluidTrade.UnitTest.Server.DataModel.tableEngineer = new EngineerDataTable(); // FluidTrade.UnitTest.Server.DataModel.dataSet.Tables.Add(FluidTrade.UnitTest.Server.DataModel.tableEngineer); // FluidTrade.UnitTest.Server.DataModel.tableManager = new ManagerDataTable(); // FluidTrade.UnitTest.Server.DataModel.dataSet.Tables.Add(FluidTrade.UnitTest.Server.DataModel.tableManager); // FluidTrade.UnitTest.Server.DataModel.tableObject = new ObjectDataTable(); // FluidTrade.UnitTest.Server.DataModel.dataSet.Tables.Add(FluidTrade.UnitTest.Server.DataModel.tableObject); // FluidTrade.UnitTest.Server.DataModel.tableProject = new ProjectDataTable(); // FluidTrade.UnitTest.Server.DataModel.dataSet.Tables.Add(FluidTrade.UnitTest.Server.DataModel.tableProject); // FluidTrade.UnitTest.Server.DataModel.tableProjectMember = new ProjectMemberDataTable(); // FluidTrade.UnitTest.Server.DataModel.dataSet.Tables.Add(FluidTrade.UnitTest.Server.DataModel.tableProjectMember); // FluidTrade.UnitTest.Server.DataModel.tableRace = new RaceDataTable(); // FluidTrade.UnitTest.Server.DataModel.dataSet.Tables.Add(FluidTrade.UnitTest.Server.DataModel.tableRace); foreach (KeyValuePair <string, TableSchema> keyValuePair in dataModelSchema.Tables) { this.Statements.Add(new CodeAssignStatement(new CodePropertyReferenceExpression(new CodeTypeReferenceExpression(dataModelSchema.Name), String.Format("table{0}", keyValuePair.Value.Name)), new CodeObjectCreateExpression(string.Format("{0}DataTable", keyValuePair.Value.Name)))); this.Statements.Add(new CodeMethodInvokeExpression(new CodePropertyReferenceExpression(new CodePropertyReferenceExpression(new CodeTypeReferenceExpression(dataModelSchema.Name), "dataSet"), "Tables"), "Add", new CodePropertyReferenceExpression(new CodeTypeReferenceExpression(dataModelSchema.Name), String.Format("table{0}", keyValuePair.Value.Name)))); } // // Enforce the foreign key constraint between Object and Department tables. // global::System.Data.ForeignKeyConstraint foreignKeyConstraint0 = new System.Data.ForeignKeyConstraint("FK_Object_Department", new FluidTrade.Core.Column[] { // FluidTrade.UnitTest.Server.DataModel.tableObject.ObjectIdColumn}, new FluidTrade.Core.Column[] { // FluidTrade.UnitTest.Server.DataModel.tableDepartment.DepartmentIdColumn}); // FluidTrade.UnitTest.Server.DataModel.tableDepartment.Constraints.Add(foreignKeyConstraint0); // // Enforce the foreign key constraint between Department and Employee tables. // global::System.Data.ForeignKeyConstraint foreignKeyConstraint1 = new System.Data.ForeignKeyConstraint("FK_Department_Employee", new FluidTrade.Core.Column[] { // FluidTrade.UnitTest.Server.DataModel.tableDepartment.DepartmentIdColumn}, new FluidTrade.Core.Column[] { // FluidTrade.UnitTest.Server.DataModel.tableEmployee.DepartmentIdColumn}); // FluidTrade.UnitTest.Server.DataModel.tableEmployee.Constraints.Add(foreignKeyConstraint1); // // Enforce the foreign key constraint between Object and Employee tables. // global::System.Data.ForeignKeyConstraint foreignKeyConstraint2 = new System.Data.ForeignKeyConstraint("FK_Object_Employee", new FluidTrade.Core.Column[] { // FluidTrade.UnitTest.Server.DataModel.tableObject.ObjectIdColumn}, new FluidTrade.Core.Column[] { // FluidTrade.UnitTest.Server.DataModel.tableEmployee.EmployeeIdColumn}); // FluidTrade.UnitTest.Server.DataModel.tableEmployee.Constraints.Add(foreignKeyConstraint2); // // Enforce the foreign key constraint between Race and Employee tables. // global::System.Data.ForeignKeyConstraint foreignKeyConstraint3 = new System.Data.ForeignKeyConstraint("FK_Race_Employee", new FluidTrade.Core.Column[] { // FluidTrade.UnitTest.Server.DataModel.tableRace.RaceCodeColumn}, new FluidTrade.Core.Column[] { // FluidTrade.UnitTest.Server.DataModel.tableEmployee.RaceCodeColumn}); // FluidTrade.UnitTest.Server.DataModel.tableEmployee.Constraints.Add(foreignKeyConstraint3); // // Enforce the foreign key constraint between Employee and Engineer tables. // global::System.Data.ForeignKeyConstraint foreignKeyConstraint4 = new System.Data.ForeignKeyConstraint("FK_Employee_Engineer", new FluidTrade.Core.Column[] { // FluidTrade.UnitTest.Server.DataModel.tableEmployee.EmployeeIdColumn}, new FluidTrade.Core.Column[] { // FluidTrade.UnitTest.Server.DataModel.tableEngineer.EngineerIdColumn}); // FluidTrade.UnitTest.Server.DataModel.tableEngineer.Constraints.Add(foreignKeyConstraint4); // // Enforce the foreign key constraint between Manager and Engineer tables. // global::System.Data.ForeignKeyConstraint foreignKeyConstraint5 = new System.Data.ForeignKeyConstraint("FK_Manager_Engineer", new FluidTrade.Core.Column[] { // FluidTrade.UnitTest.Server.DataModel.tableManager.ManagerIdColumn}, new FluidTrade.Core.Column[] { // FluidTrade.UnitTest.Server.DataModel.tableEngineer.ManagerIdColumn}); // FluidTrade.UnitTest.Server.DataModel.tableEngineer.Constraints.Add(foreignKeyConstraint5); // // Enforce the foreign key constraint between Employee and Manager tables. // global::System.Data.ForeignKeyConstraint foreignKeyConstraint6 = new System.Data.ForeignKeyConstraint("FK_Employee_Manager", new FluidTrade.Core.Column[] { // FluidTrade.UnitTest.Server.DataModel.tableEmployee.EmployeeIdColumn}, new FluidTrade.Core.Column[] { // FluidTrade.UnitTest.Server.DataModel.tableManager.ManagerIdColumn}); // FluidTrade.UnitTest.Server.DataModel.tableManager.Constraints.Add(foreignKeyConstraint6); // // Enforce the foreign key constraint between Object and Project tables. // global::System.Data.ForeignKeyConstraint foreignKeyConstraint7 = new System.Data.ForeignKeyConstraint("FK_Object_Project", new FluidTrade.Core.Column[] { // FluidTrade.UnitTest.Server.DataModel.tableObject.ObjectIdColumn}, new FluidTrade.Core.Column[] { // FluidTrade.UnitTest.Server.DataModel.tableProject.ProjectIdColumn}); // FluidTrade.UnitTest.Server.DataModel.tableProject.Constraints.Add(foreignKeyConstraint7); // // Enforce the foreign key constraint between Employee and ProjectMember tables. // global::System.Data.ForeignKeyConstraint foreignKeyConstraint8 = new System.Data.ForeignKeyConstraint("FK_Employee_ProjectMember", new FluidTrade.Core.Column[] { // FluidTrade.UnitTest.Server.DataModel.tableEmployee.EmployeeIdColumn}, new FluidTrade.Core.Column[] { // FluidTrade.UnitTest.Server.DataModel.tableProjectMember.EmployeeIdColumn}); // FluidTrade.UnitTest.Server.DataModel.tableProjectMember.Constraints.Add(foreignKeyConstraint8); // // Enforce the foreign key constraint between Project and ProjectMember tables. // global::System.Data.ForeignKeyConstraint foreignKeyConstraint9 = new System.Data.ForeignKeyConstraint("FK_Project_ProjectMember", new FluidTrade.Core.Column[] { // FluidTrade.UnitTest.Server.DataModel.tableProject.ProjectIdColumn}, new FluidTrade.Core.Column[] { // FluidTrade.UnitTest.Server.DataModel.tableProjectMember.ProjectIdColumn}); // FluidTrade.UnitTest.Server.DataModel.tableProjectMember.Constraints.Add(foreignKeyConstraint9); int foreignKeyCount = 0; foreach (KeyValuePair <string, TableSchema> tablePair in dataModelSchema.Tables) { foreach (KeyValuePair <string, ConstraintSchema> constraintPair in tablePair.Value.Constraints) { if (constraintPair.Value is ForeignKeyConstraintSchema) { // Construct a foreign key constraint described by this schema. ForeignKeyConstraintSchema foreignKeyConstraintSchema = constraintPair.Value as ForeignKeyConstraintSchema; // FluidTrade.UnitTest.Client.DataModel.relationDepartmentEmployee = new System.Data.DataRelation("FK_Department_Employee", new global::System.Data.DataColumn[] { // FluidTrade.UnitTest.Client.DataModel.tableDepartment.DepartmentIdColumn}, new global::System.Data.DataColumn[] { // FluidTrade.UnitTest.Client.DataModel.tableEmployee.DepartmentIdColumn}, false); // FluidTrade.UnitTest.Client.DataModel.dataSet.Relations.Add(FluidTrade.UnitTest.Client.DataModel.relationDepartmentEmployee); CodeVariableReferenceExpression foreignKeyConstraintExpression = new CodeVariableReferenceExpression(string.Format("foreignKeyConstraint{0}", foreignKeyCount++)); this.Statements.Add(new CodeVariableDeclarationStatement(new CodeGlobalTypeReference(typeof(System.Data.ForeignKeyConstraint)), foreignKeyConstraintExpression.VariableName, new CodeForeignKeyConstraint(foreignKeyConstraintSchema))); this.Statements.Add( new CodeAssignStatement( new CodeFieldReferenceExpression(new CodeVariableReferenceExpression(foreignKeyConstraintExpression.VariableName), "AcceptRejectRule"), new CodeFieldReferenceExpression(new CodeGlobalTypeReferenceExpression(typeof(System.Data.AcceptRejectRule)), "Cascade"))); this.Statements.Add(new CodeMethodInvokeExpression(new CodePropertyReferenceExpression(new CodePropertyReferenceExpression(new CodeTypeReferenceExpression(dataModelSchema.Name), string.Format("table{0}", tablePair.Value.Name)), "Constraints"), "Add", foreignKeyConstraintExpression)); } } } // // Create a relation between the Department and Employee tables. // FluidTrade.UnitTest.Server.DataModel.relationDepartmentEmployee = new System.Data.DataRelation("FK_Department_Employee", new FluidTrade.Core.Column[] { // FluidTrade.UnitTest.Server.DataModel.tableDepartment.DepartmentIdColumn}, new FluidTrade.Core.Column[] { // FluidTrade.UnitTest.Server.DataModel.tableEmployee.DepartmentIdColumn}, false); // FluidTrade.UnitTest.Server.DataModel.dataSet.Relations.Add(FluidTrade.UnitTest.Server.DataModel.relationDepartmentEmployee); // // Create a relation between the Employee and Engineer tables. // FluidTrade.UnitTest.Server.DataModel.relationEmployeeEngineer = new System.Data.DataRelation("FK_Employee_Engineer", new FluidTrade.Core.Column[] { // FluidTrade.UnitTest.Server.DataModel.tableEmployee.EmployeeIdColumn}, new FluidTrade.Core.Column[] { // FluidTrade.UnitTest.Server.DataModel.tableEngineer.EngineerIdColumn}, false); // FluidTrade.UnitTest.Server.DataModel.dataSet.Relations.Add(FluidTrade.UnitTest.Server.DataModel.relationEmployeeEngineer); // // Create a relation between the Employee and Manager tables. // FluidTrade.UnitTest.Server.DataModel.relationEmployeeManager = new System.Data.DataRelation("FK_Employee_Manager", new FluidTrade.Core.Column[] { // FluidTrade.UnitTest.Server.DataModel.tableEmployee.EmployeeIdColumn}, new FluidTrade.Core.Column[] { // FluidTrade.UnitTest.Server.DataModel.tableManager.ManagerIdColumn}, false); // FluidTrade.UnitTest.Server.DataModel.dataSet.Relations.Add(FluidTrade.UnitTest.Server.DataModel.relationEmployeeManager); // // Create a relation between the Employee and ProjectMember tables. // FluidTrade.UnitTest.Server.DataModel.relationEmployeeProjectMember = new System.Data.DataRelation("FK_Employee_ProjectMember", new FluidTrade.Core.Column[] { // FluidTrade.UnitTest.Server.DataModel.tableEmployee.EmployeeIdColumn}, new FluidTrade.Core.Column[] { // FluidTrade.UnitTest.Server.DataModel.tableProjectMember.EmployeeIdColumn}, false); // FluidTrade.UnitTest.Server.DataModel.dataSet.Relations.Add(FluidTrade.UnitTest.Server.DataModel.relationEmployeeProjectMember); // // Create a relation between the Manager and Engineer tables. // FluidTrade.UnitTest.Server.DataModel.relationManagerEngineer = new System.Data.DataRelation("FK_Manager_Engineer", new FluidTrade.Core.Column[] { // FluidTrade.UnitTest.Server.DataModel.tableManager.ManagerIdColumn}, new FluidTrade.Core.Column[] { // FluidTrade.UnitTest.Server.DataModel.tableEngineer.ManagerIdColumn}, false); // FluidTrade.UnitTest.Server.DataModel.dataSet.Relations.Add(FluidTrade.UnitTest.Server.DataModel.relationManagerEngineer); // // Create a relation between the Object and Department tables. // FluidTrade.UnitTest.Server.DataModel.relationObjectDepartment = new System.Data.DataRelation("FK_Object_Department", new FluidTrade.Core.Column[] { // FluidTrade.UnitTest.Server.DataModel.tableObject.ObjectIdColumn}, new FluidTrade.Core.Column[] { // FluidTrade.UnitTest.Server.DataModel.tableDepartment.DepartmentIdColumn}, false); // FluidTrade.UnitTest.Server.DataModel.dataSet.Relations.Add(FluidTrade.UnitTest.Server.DataModel.relationObjectDepartment); // // Create a relation between the Object and Employee tables. // FluidTrade.UnitTest.Server.DataModel.relationObjectEmployee = new System.Data.DataRelation("FK_Object_Employee", new FluidTrade.Core.Column[] { // FluidTrade.UnitTest.Server.DataModel.tableObject.ObjectIdColumn}, new FluidTrade.Core.Column[] { // FluidTrade.UnitTest.Server.DataModel.tableEmployee.EmployeeIdColumn}, false); // FluidTrade.UnitTest.Server.DataModel.dataSet.Relations.Add(FluidTrade.UnitTest.Server.DataModel.relationObjectEmployee); // // Create a relation between the Object and Project tables. // FluidTrade.UnitTest.Server.DataModel.relationObjectProject = new System.Data.DataRelation("FK_Object_Project", new FluidTrade.Core.Column[] { // FluidTrade.UnitTest.Server.DataModel.tableObject.ObjectIdColumn}, new FluidTrade.Core.Column[] { // FluidTrade.UnitTest.Server.DataModel.tableProject.ProjectIdColumn}, false); // FluidTrade.UnitTest.Server.DataModel.dataSet.Relations.Add(FluidTrade.UnitTest.Server.DataModel.relationObjectProject); // // Create a relation between the Project and ProjectMember tables. // FluidTrade.UnitTest.Server.DataModel.relationProjectProjectMember = new System.Data.DataRelation("FK_Project_ProjectMember", new FluidTrade.Core.Column[] { // FluidTrade.UnitTest.Server.DataModel.tableProject.ProjectIdColumn}, new FluidTrade.Core.Column[] { // FluidTrade.UnitTest.Server.DataModel.tableProjectMember.ProjectIdColumn}, false); // FluidTrade.UnitTest.Server.DataModel.dataSet.Relations.Add(FluidTrade.UnitTest.Server.DataModel.relationProjectProjectMember); // // Create a relation between the Race and Employee tables. // FluidTrade.UnitTest.Server.DataModel.relationRaceEmployee = new System.Data.DataRelation("FK_Race_Employee", new FluidTrade.Core.Column[] { // FluidTrade.UnitTest.Server.DataModel.tableRace.RaceCodeColumn}, new FluidTrade.Core.Column[] { // FluidTrade.UnitTest.Server.DataModel.tableEmployee.RaceCodeColumn}, false); // FluidTrade.UnitTest.Server.DataModel.dataSet.Relations.Add(FluidTrade.UnitTest.Server.DataModel.relationRaceEmployee); foreach (KeyValuePair <string, RelationSchema> relationPair in dataModelSchema.Relations) { // The name of the relation is decorated with the relation name when the relation between the child and the parent // isn't unique. string relationName = relationPair.Value.IsDistinctPathToParent ? string.Format("relation{0}{1}", relationPair.Value.ParentTable.Name, relationPair.Value.ChildTable.Name) : string.Format("relation{0}{1}By{2}", relationPair.Value.ParentTable.Name, relationPair.Value.ChildTable.Name, relationPair.Value.Name); // FluidTrade.UnitTest.Server.DataModel.relationRaceEmployee = new System.Data.DataRelation("FK_Race_Employee", new FluidTrade.Core.Column[] { // FluidTrade.UnitTest.Server.DataModel.tableRace.RaceCodeColumn}, new FluidTrade.Core.Column[] { // FluidTrade.UnitTest.Server.DataModel.tableEmployee.RaceCodeColumn}, false); // FluidTrade.UnitTest.Server.DataModel.dataSet.Relations.Add(FluidTrade.UnitTest.Server.DataModel.relationRaceEmployee); CodeExpression relationFieldExpression = new CodePropertyReferenceExpression(new CodeTypeReferenceExpression(dataModelSchema.Name), relationName); this.Statements.Add(new CodeAssignStatement(relationFieldExpression, new CodeDataRelation(relationPair.Value))); this.Statements.Add(new CodeMethodInvokeExpression(new CodePropertyReferenceExpression(new CodeFieldReferenceExpression(new CodeTypeReferenceExpression(dataModelSchema.Name), "dataSet"), "Relations"), "Add", relationFieldExpression)); } // FluidTrade.UnitTest.Server.DataModel.Configuration.InitializeRelations(); // FluidTrade.UnitTest.Server.DataModel.Department.InitializeRelations(); // FluidTrade.UnitTest.Server.DataModel.Employee.InitializeRelations(); // FluidTrade.UnitTest.Server.DataModel.Engineer.InitializeRelations(); // FluidTrade.UnitTest.Server.DataModel.Manager.InitializeRelations(); // FluidTrade.UnitTest.Server.DataModel.Object.InitializeRelations(); // FluidTrade.UnitTest.Server.DataModel.Project.InitializeRelations(); // FluidTrade.UnitTest.Server.DataModel.ProjectMember.InitializeRelations(); // FluidTrade.UnitTest.Server.DataModel.Race.InitializeRelations(); foreach (KeyValuePair <string, TableSchema> keyValuePair in dataModelSchema.Tables) { this.Statements.Add(new CodeMethodInvokeExpression(new CodeFieldReferenceExpression(new CodeTypeReferenceExpression(dataModelSchema.Name), string.Format("table{0}", keyValuePair.Value.Name)), "InitializeRelations")); } // DataModel.syncUpdate = new global::System.Object(); this.Statements.Add(new CodeAssignStatement(new CodeFieldReferenceExpression(new CodeTypeReferenceExpression(dataModelSchema.Name), "syncUpdate"), new CodeObjectCreateExpression(new CodeGlobalTypeReference(typeof(System.Object))))); // DataModel.syncRoot = new System.Object(); this.Statements.Add(new CodeAssignStatement(new CodePropertyReferenceExpression(new CodeTypeReferenceExpression(dataModelSchema.Name), "syncRoot"), new CodeObjectCreateExpression(new CodeGlobalTypeReference(typeof(System.Object))))); // DataModel.dataSetId = Guid.Empty; this.Statements.Add(new CodeAssignStatement(new CodePropertyReferenceExpression(new CodeTypeReferenceExpression(dataModelSchema.Name), "dataSetId"), new CodePropertyReferenceExpression(new CodeGlobalTypeReferenceExpression(typeof(Guid)), "Empty"))); // DataModel.sequence = int.MinValue; this.Statements.Add(new CodeAssignStatement(new CodePropertyReferenceExpression(new CodeTypeReferenceExpression(dataModelSchema.Name), "sequence"), new CodePropertyReferenceExpression(new CodeGlobalTypeReferenceExpression(typeof(Int64)), "MinValue"))); // DataModel.updateBufferMutex = new Mutex(false); this.Statements.Add(new CodeAssignStatement(new CodePropertyReferenceExpression(new CodeTypeReferenceExpression(dataModelSchema.Name), "updateBufferMutex"), new CodeObjectCreateExpression(new CodeGlobalTypeReference(typeof(System.Threading.Mutex)), new CodePrimitiveExpression(false)))); // } }
private void AddConstraint(ForeignKeyConstraintSchema fk) { store.AppendValues(fk.Name, String.Empty, false, String.Empty, String.Empty, fk.DeleteAction.ToString(), fk.UpdateAction.ToString(), fk ); }
/// <summary> /// Recurse into a hierarchy of relations until a table is found that can resolve external identifiers. /// </summary> /// <param name="foreignKeyConstraintParameterItem">The original foreign key parameter to be resolved.</param> /// <param name="foreignKeyConstraintSchema">The current level of the table hierarchy.</param> /// <returns>An expression representing the unique row identified by the foreign key.</returns> public void RecurseIntoRelation(CodeVariableReferenceExpression rowExpression, ForeignKeyConstraintSchema rootForeignKeyConstraintSchema, CodeExpression rootKeyExpression, ForeignKeyConstraintSchema currentForeignKeyConstraintSchema) { // Each time through the recursion, the parent table will be examined to see if there is another ancestor which can be // used to resolve the external interfaces. If one is found, the recursion continues into the ancestor, if not, we've // found the ancestor that can resolve the external identifiers. TableSchema parentTableSchema = currentForeignKeyConstraintSchema.RelatedTable; ForeignKeyConstraintSchema parentForeignKeyConstraintSchema = parentTableSchema.ParentConstraint; // If this is the end of the line for the foreign relations that can be use to uniquely identify the original row, then // stop recursing and attempt to find a unique constraint. The recursion then unwinds and the row at the original // level of the recursion has values that can be used to identify the target record. if (parentForeignKeyConstraintSchema == null) { // object[] configurationKey0 = new object[] { // configurationId, // "FK_Object_Employee"}; // ConfigurationRow configurationRow0 = DataModel.Configuration.ConfigurationKey.Find(configurationKey0); // if ((configurationRow0 == null)) { // throw new global::System.ServiceModel.FaultException<RecordNotFoundFault>(new global::FluidTrade.Core.RecordNotFoundFault("Attempt to access a Configuration record ({0}) that doesn\'t exist", configurationKey0)); // } // configurationRow0.AcquireReaderLock(middleTierTransaction.AdoResourceManager.Guid, DataModel.lockTimeout); // middleTierTransaction.AdoResourceManager.AddLock(configurationRow0); // if ((configurationRow0.RowState == global::System.Data.DataRowState.Detached)) { // throw new global::System.ServiceModel.FaultException<RecordNotFoundFault>(new global::FluidTrade.Core.RecordNotFoundFault("Attempt to access a Configuration record ({0}) that doesn\'t exist", configurationKey0)); // } CodeVariableReferenceExpression configurationKeyExpression = new CodeRandomVariableReferenceExpression(); Add(new CodeVariableDeclarationStatement(new CodeGlobalTypeReference(typeof(System.Object[])), configurationKeyExpression.VariableName, new CodeKeyCreateExpression(new CodeArgumentReferenceExpression("configurationId"), new CodePrimitiveExpression(rootForeignKeyConstraintSchema.Name)))); CodeVariableReferenceExpression configurationRowExpression = new CodeRandomVariableReferenceExpression(); Add(new CodeVariableDeclarationStatement(new CodeTypeReference("ConfigurationRow"), configurationRowExpression.VariableName, new CodeMethodInvokeExpression(new CodePropertyReferenceExpression(new CodePropertyReferenceExpression(new CodeTypeReferenceExpression(parentTableSchema.DataModel.Name), "Configuration"), "ConfigurationKey"), "Find", configurationKeyExpression))); TableSchema configurationTableSchema = parentTableSchema.DataModel.Tables["Configuration"]; Add(new CodeCheckRecordExistsStatement(configurationTableSchema, configurationRowExpression, configurationKeyExpression)); Add(new CodeAcquireRecordReaderLockExpression(transactionExpression, configurationRowExpression, parentTableSchema.DataModel)); Add(new CodeAddLockToTransactionExpression(transactionExpression, configurationRowExpression)); Add(new CodeCheckRecordDetachedStatement(configurationTableSchema, configurationRowExpression, configurationKeyExpression)); // IObjectIndex dataIndex0 = ((IObjectIndex)(DataModel.Object.Indices[configurationRow0.IndexName])); // ObjectRow objectRow1 = dataIndex0.Find(engineerId); // if ((objectRow1 == null)) { // throw new global::System.ServiceModel.FaultException<RecordNotFoundFault>(new global::FluidTrade.Core.RecordNotFoundFault("Attempt to access a Object record ({0}) that doesn\'t exist", engineerId)); // } CodeTypeReference indexType = new CodeTypeReference(string.Format("I{0}Index", parentTableSchema.Name)); CodeVariableReferenceExpression indexExpression = new CodeRandomVariableReferenceExpression(); CodeExpression indexNameExpression = new CodePropertyReferenceExpression(configurationRowExpression, "IndexName"); Add(new CodeVariableDeclarationStatement(indexType, indexExpression.VariableName, new CodeCastExpression(indexType, new CodeIndexerExpression(new CodePropertyReferenceExpression(new CodePropertyReferenceExpression(new CodeTypeReferenceExpression(parentTableSchema.DataModel.Name), parentTableSchema.Name), "Indices"), indexNameExpression)))); Add(new CodeCheckIndexExistsStatement(indexExpression, parentTableSchema, indexNameExpression)); CodeTypeReference rowTypeReference = new CodeTypeReference(string.Format("{0}Row", parentTableSchema.Name)); Add(new CodeVariableDeclarationStatement(rowTypeReference, rowExpression.VariableName, new CodeMethodInvokeExpression(indexExpression, "Find", rootKeyExpression))); Add(new CodeCheckRecordExistsStatement(parentTableSchema, rowExpression, rootKeyExpression)); // objectRow1.AcquireReaderLock(middleTierTransaction.AdoResourceManager.Guid, DataModel.lockTimeout); // middleTierTransaction.AdoResourceManager.AddLock(objectRow1); // if ((objectRow1.RowState == global::System.Data.DataRowState.Detached)) { // throw new global::System.ServiceModel.FaultException<RecordNotFoundFault>(new global::FluidTrade.Core.RecordNotFoundFault("Attempt to access a Object record ({0}) that doesn\'t exist", engineerId)); // } Add(new CodeAcquireRecordReaderLockExpression(this.transactionExpression, rowExpression, parentTableSchema.DataModel)); Add(new CodeAddLockToTransactionExpression(this.transactionExpression, rowExpression)); Add(new CodeCheckRecordDetachedStatement(parentTableSchema, rowExpression, rootKeyExpression)); } else { // This will recurse into the hierarchy and emit code that will find and lock each row in the line of ancestors to // the current table. When there are no more ancestors to be found, code will be generated to select a record // based on a unique constraint. The generated code then unwinds the relationship choosing one distinct descendant // after another until all the foreign relationships to the starting table have been resolved. CodeVariableReferenceExpression parentRow = new CodeRandomVariableReferenceExpression(); RecurseIntoRelation(parentRow, rootForeignKeyConstraintSchema, rootKeyExpression, parentForeignKeyConstraintSchema); // // Employee level of the engineerId foreign key search. // object[] employeeKey1 = new object[] { // objectRow1.ObjectId}; // EmployeeRow employeeRow2 = DataModel.Employee.EmployeeKey.Find(employeeKey1); // if ((employeeRow2 == null)) { // throw new global::System.ServiceModel.FaultException<RecordNotFoundFault>(new global::FluidTrade.Core.RecordNotFoundFault("Attempt to access a Employee record ({0}) that doesn\'t exist", employeeKey1)); // } CodeVariableReferenceExpression keyExpression = new CodeRandomVariableReferenceExpression(); Add(new CodeVariableDeclarationStatement(new CodeGlobalTypeReference(typeof(System.Object[])), keyExpression.VariableName, new CodeKeyCreateExpression(parentRow, parentForeignKeyConstraintSchema.RelatedColumns))); CodeTypeReference rowType = new CodeTypeReference(string.Format("{0}Row", parentTableSchema.Name)); UniqueConstraintSchema uniqueConstraintSchema = parentTableSchema.GetUniqueConstraint(parentForeignKeyConstraintSchema.Columns); Add(new CodeVariableDeclarationStatement(rowType, rowExpression.VariableName, new CodeMethodInvokeExpression(new CodePropertyReferenceExpression(new CodePropertyReferenceExpression(new CodeTypeReferenceExpression(parentTableSchema.DataModel.Name), parentTableSchema.Name), uniqueConstraintSchema.Name), "Find", keyExpression))); Add(new CodeCheckRecordExistsStatement(parentTableSchema, rowExpression, keyExpression)); // employeeRow2.AcquireReaderLock(middleTierTransaction.AdoResourceManager.Guid, DataModel.lockTimeout); // middleTierTransaction.AdoResourceManager.AddLock(employeeRow2); // if ((employeeRow2.RowState == global::System.Data.DataRowState.Detached)) { // throw new global::System.ServiceModel.FaultException<RecordNotFoundFault>(new global::FluidTrade.Core.RecordNotFoundFault("Attempt to access a Employee record ({0}) that doesn\'t exist", employeeKey1)); // } Add(new CodeAcquireRecordReaderLockExpression(this.transactionExpression, rowExpression, parentTableSchema.DataModel)); Add(new CodeAddLockToTransactionExpression(this.transactionExpression, rowExpression)); Add(new CodeCheckRecordDetachedStatement(parentTableSchema, rowExpression, keyExpression)); } }
//http://www.sqlite.org/pragma.html public virtual ConstraintSchemaCollection GetConstraints (TableSchema table, ColumnSchema column) { if (table == null) throw new ArgumentNullException ("table"); string columnName = column == null ? null : column.Name; ConstraintSchemaCollection constraints = new ConstraintSchemaCollection (); IPooledDbConnection conn = connectionPool.Request (); //fk and unique IDbCommand command = conn.CreateCommand ("SELECT name, tbl_name FROM sqlite_master WHERE sql IS NULL AND type = 'index'"); try { using (command) { using (IDataReader r = command.ExecuteReader()) { while (r.Read ()) { ConstraintSchema constraint = null; if (r.IsDBNull (1) || r.GetString (1) == null) { constraint = new UniqueConstraintSchema (this); } else { ForeignKeyConstraintSchema fkc = new ForeignKeyConstraintSchema (this); fkc.ReferenceTableName = r.GetString (1); constraint = fkc; } constraint.Name = r.GetString (0); constraints.Add (constraint); } r.Close (); } } //pk, column if (columnName != null) { command = conn.CreateCommand ( "PRAGMA table_info('" + table.Name + "')" ); using (command) { using (IDataReader r = command.ExecuteReader()) { while (r.Read ()) { if (r.GetInt32 (5) == 1 && r.GetString (1) == columnName) { PrimaryKeyConstraintSchema constraint = new PrimaryKeyConstraintSchema (this); ColumnSchema priColumn = new ColumnSchema (this, table); priColumn.Name = r.GetString (1); constraint.Columns.Add (priColumn); constraint.IsColumnConstraint = true; constraint.Name = "pk_" + table.Name + "_" + priColumn.Name; constraints.Add (constraint); } } r.Close (); } } } } catch (Exception e) { QueryService.RaiseException (e); } conn.Release (); return constraints; }