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> /// Generate the keys on 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 GenerateKeys(StreamWriter streamWriter, TableSchema tableSchema) { // This architecture foregoes the 'query' mechanism for finding records in favor of a more direct record identifier. // Every table has an implicit key created on the row identifier used to quickly find any given record. streamWriter.WriteLine(" /* Unique Constraints */"); streamWriter.WriteLine(" alter table \"{0}\" with nocheck add ", tableSchema.Name); // Put all the non-nullable unique keys into a list. List <UniqueConstraintSchema> uniqueKeys = new List <UniqueConstraintSchema>(); foreach (ConstraintSchema constraintSchema in tableSchema.Constraints.Values) { if (constraintSchema is UniqueConstraintSchema && !constraintSchema.IsNullable) { uniqueKeys.Add(constraintSchema as UniqueConstraintSchema); } } // This will add any additional keys to the table. for (int keyIndex = 0; keyIndex < uniqueKeys.Count; keyIndex++) { UniqueConstraintSchema uniqueSchema = uniqueKeys[keyIndex]; if (uniqueSchema.IsNullable) { continue; } if (uniqueSchema.IsPrimaryKey) { streamWriter.WriteLine(" constraint \"{0}\" primary key clustered", uniqueSchema.Name); } else { streamWriter.WriteLine(" constraint \"{0}\" unique", uniqueSchema.Name); } streamWriter.WriteLine(" ("); ColumnSchema[] keyFields = uniqueSchema.Columns; for (int columnIndex = 0; columnIndex < keyFields.Length; columnIndex++) { ColumnSchema columnSchema = keyFields[columnIndex]; streamWriter.Write(" \"{0}\"", columnSchema.Name); streamWriter.WriteLine(columnIndex == keyFields.Length - 1 ? "" : ","); } streamWriter.Write(" ) on \"PRIMARY\" "); // End with a comment if there are more foreign constraints comming. streamWriter.WriteLine(keyIndex < uniqueKeys.Count - 1 ? "," : ""); } streamWriter.WriteLine(""); // Roll the transaction back if the indices can't be created. streamWriter.WriteLine(""); }
/// <summary> /// Creates a method that finds a row containing the given elements of an index. /// </summary> /// <param name="uniqueConstraintSchema">A description of a unique constraint.</param> public FindByKeyMethod(UniqueConstraintSchema uniqueConstraintSchema) { // /// <summary> // /// Finds a row in the Configuration table containing the key elements. // /// </summary> // /// <param name="key">An array of key elements.</param> // /// <returns>A ConfigurationKey row that contains the key elements, or null if there is no match.</returns> // public new ConfigurationRow Find(object[] key) { this.Comments.Add(new CodeCommentStatement("<summary>", true)); this.Comments.Add(new CodeCommentStatement(string.Format("Finds a row in the {0} table containing the key elements.", uniqueConstraintSchema.Table.Name), true)); this.Comments.Add(new CodeCommentStatement("</summary>", true)); this.Comments.Add(new CodeCommentStatement("<param name=\"key\">An array of key elements.</param>", true)); this.Comments.Add(new CodeCommentStatement(string.Format("<returns>A {0} row that contains the key elements, or null if there is no match.</returns>", uniqueConstraintSchema.Name), true)); this.Attributes = MemberAttributes.Public | MemberAttributes.New | MemberAttributes.Final; this.ReturnType = new CodeTypeReference(string.Format("{0}Row", uniqueConstraintSchema.Table.Name)); this.Name = "Find"; this.Parameters.Add(new CodeParameterDeclarationExpression(new CodeGlobalTypeReference(typeof(System.Object[])), "key")); // try { // DataModel.Configuration.AcquireLock(); // return ((ConfigurationRow)(base.Find(key))); // } // catch (global::System.ArgumentException argumentException) { // throw new global::System.ServiceModel.FaultException<ArgumentFault>(new global::FluidTrade.Core.ArgumentFault(argumentException.Message)); // } // finally { // DataModel.Configuration.ReleaseLock(); // } CodeTryCatchFinallyStatement tryCatchFinallyStatement = new CodeTryCatchFinallyStatement(); CodePropertyReferenceExpression tableExpression = new CodePropertyReferenceExpression( new CodeTypeReferenceExpression(string.Format("{0}", uniqueConstraintSchema.Table.DataModel.Name)), uniqueConstraintSchema.Table.Name); tryCatchFinallyStatement.TryStatements.Add( new CodeMethodInvokeExpression( new CodePropertyReferenceExpression(new CodeTypeReferenceExpression(uniqueConstraintSchema.Table.DataModel.Name), "DataLock"), "EnterReadLock")); tryCatchFinallyStatement.TryStatements.Add(new CodeMethodReturnStatement(new CodeCastExpression(this.ReturnType, new CodeMethodInvokeExpression(new CodeBaseReferenceExpression(), "Find", new CodeArgumentReferenceExpression("key"))))); CodeCatchClause catchArgumentException = new CodeCatchClause("argumentException", new CodeGlobalTypeReference(typeof(System.ArgumentException))); catchArgumentException.Statements.Add(new CodeThrowArgumentExceptionStatement(new CodePropertyReferenceExpression(new CodeArgumentReferenceExpression("argumentException"), "Message"))); tryCatchFinallyStatement.CatchClauses.Add(catchArgumentException); CodeCatchClause catchFormatException = new CodeCatchClause("formatException", new CodeGlobalTypeReference(typeof(System.FormatException))); catchFormatException.Statements.Add(new CodeThrowFormatExceptionStatement(new CodePropertyReferenceExpression(new CodeArgumentReferenceExpression("formatException"), "Message"))); tryCatchFinallyStatement.CatchClauses.Add(catchFormatException); tryCatchFinallyStatement.FinallyStatements.Add( new CodeMethodInvokeExpression( new CodePropertyReferenceExpression(new CodeTypeReferenceExpression(uniqueConstraintSchema.Table.DataModel.Name), "DataLock"), "ExitReadLock")); this.Statements.Add(tryCatchFinallyStatement); // } }
protected virtual void AddClicked(object sender, EventArgs e) { UniqueConstraintSchema uni = schemaProvider.GetNewUniqueConstraintSchema("uni_new"); int index = 1; while (constraints.Contains(uni.Name)) { uni.Name = "uni_new" + (index++); } constraints.Add(uni); AddConstraint(uni); EmitContentChanged(); }
protected virtual void AddClicked(object sender, EventArgs e) { UniqueConstraintSchema uni = schemaProvider.CreateUniqueConstraintSchema(string.Concat(table.Name, "_", "uni_new")); int index = 1; while (constraints.Contains(uni.Name)) { uni.Name = string.Concat(table.Name, "_", "uni_new", (index++).ToString()); } constraints.Add(uni); AddConstraint(uni); EmitContentChanged(); }
/// <summary> /// Creates an expression to find a record based on the primary index of a table. /// </summary> /// <param name="tableSchema"></param> public CodeFindByIndexExpression(TableSchema tableSchema, CodeExpression keyExpression) { // FluidTrade.UnitTest.Server.DataModel.Employee.EmployeeKey.Find(new object[] { // employeeId}); foreach (KeyValuePair <string, ConstraintSchema> constraintPair in tableSchema.Constraints) { if (constraintPair.Value is UniqueConstraintSchema) { UniqueConstraintSchema uniqueConstraintSchema = constraintPair.Value as UniqueConstraintSchema; if (uniqueConstraintSchema.IsPrimaryKey) { this.Method = new CodeMethodReferenceExpression(new CodePropertyReferenceExpression(new CodePropertyReferenceExpression(new CodeTypeReferenceExpression(tableSchema.DataModel.Name), tableSchema.Name), uniqueConstraintSchema.Name), "Find"); this.Parameters.Add(keyExpression); } } } }
protected virtual void RemoveClicked(object sender, EventArgs e) { TreeIter iter; if (listUnique.Selection.GetSelected(out iter)) { UniqueConstraintSchema uni = store.GetValue(iter, colObjIndex) as UniqueConstraintSchema; if (Services.MessageService.AskQuestion( GettextCatalog.GetString("Are you sure you want to remove constraint '{0}'?", uni.Name), GettextCatalog.GetString("Remove Constraint") )) { store.Remove(ref iter); constraints.Remove(uni); EmitContentChanged(); } } }
/// <summary> /// Creates a method that finds a row containing the given elements of an index. /// </summary> /// <param name="uniqueConstraintSchema">A description of a unique constraint.</param> public FindByMethod(UniqueConstraintSchema uniqueConstraintSchema) { // /// <summary> // /// Finds a row in the Gender table containing the key elements. // /// </summary> // /// <param name="genderCode">The GenderCode element of the key.</param> // /// <returns>The Gender row that contains the key elements, or null if there is no match.</returns> // public GenderRow Find(Teraque.UnitTest.Gender genderCode) { this.Comments.Add(new CodeCommentStatement("<summary>", true)); this.Comments.Add(new CodeCommentStatement(String.Format("Finds a row in the {0} table containing the key elements.", uniqueConstraintSchema.Table.Name), true)); this.Comments.Add(new CodeCommentStatement("</summary>", true)); foreach (ColumnSchema columnSchema in uniqueConstraintSchema.Columns) { this.Comments.Add(new CodeCommentStatement(String.Format("<param name=\"{0}\">The {1} element of the key.</param>", CommonConversion.ToCamelCase(columnSchema.Name), columnSchema.Name), true)); } this.Comments.Add(new CodeCommentStatement(String.Format("<returns>The {0} row that contains the key elements, or null if there is no match.</returns>", uniqueConstraintSchema.Table.Name), true)); this.Attributes = MemberAttributes.Public | MemberAttributes.Final; this.ReturnType = new CodeTypeReference(String.Format("{0}Row", uniqueConstraintSchema.Table.Name)); this.Name = "Find"; foreach (ColumnSchema columnSchema in uniqueConstraintSchema.Columns) { this.Parameters.Add(new CodeParameterDeclarationExpression(columnSchema.DataType, CommonConversion.ToCamelCase(columnSchema.Name))); } // // Return the strongly typed Object row that matches the key element(s). // return ((GenderRow)(base.Find(new object[] { // genderCode}))); this.Statements.Add(new CodeCommentStatement("Return the strongly typed Object row that matches the key element(s).")); List <CodeExpression> findByArguments = new List <CodeExpression>(); foreach (ColumnSchema columnSchema in uniqueConstraintSchema.Columns) { findByArguments.Add(new CodeArgumentReferenceExpression(CommonConversion.ToCamelCase(columnSchema.Name))); } this.Statements.Add( new CodeMethodReturnStatement( new CodeCastExpression( this.ReturnType, new CodeMethodInvokeExpression(new CodeBaseReferenceExpression(), "Find", new CodeArrayCreateExpression(typeof(Object), findByArguments.ToArray()))))); // } }
/// <summary> /// Creates a property to get a index. /// </summary> /// <param name="uniqueConstraintSchema">The description of a unique constraint.</param> public DataIndexProperty(UniqueConstraintSchema uniqueConstraintSchema) { // /// <summary> // /// Gets the DepartmentKey index on the Department table. // /// </summary> // public UnitTest.Server.DataModel.DepartmentKeyIndex DepartmentKey { // get { // return this.indexDepartmentKey; // } // } this.Comments.Add(new CodeCommentStatement("<summary>", true)); this.Comments.Add(new CodeCommentStatement(String.Format("Gets the {0} index on the {1} table.", uniqueConstraintSchema.Name, uniqueConstraintSchema.Table.Name), true)); this.Comments.Add(new CodeCommentStatement("</summary>", true)); this.Attributes = MemberAttributes.Public | MemberAttributes.Final; this.Type = new CodeTypeReference(String.Format("{0}Index", uniqueConstraintSchema.Name)); this.Name = uniqueConstraintSchema.Name; this.GetStatements.Add(new CodeMethodReturnStatement(new CodeCastExpression(this.Type, new CodePropertyReferenceExpression(new CodeThisReferenceExpression(), String.Format("index{0}", uniqueConstraintSchema.Name))))); }
/// <summary> /// Generate the keys on 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 GenerateIndices(StreamWriter streamWriter, TableSchema tableSchema) { bool isCommentEmitted = false; // This will add any additional keys to the table. foreach (KeyValuePair <string, ConstraintSchema> constraintPair in tableSchema.Constraints) { if (constraintPair.Value is UniqueConstraintSchema) { UniqueConstraintSchema uniqueConstraintSchema = constraintPair.Value as UniqueConstraintSchema; if (!uniqueConstraintSchema.IsNullable) { continue; } if (!isCommentEmitted) { isCommentEmitted = true; // This architecture foregoes the 'query' mechanism for finding records in favor of a more direct record identifier. // Every table has an implicit key created on the row identifier used to quickly find any given record. streamWriter.WriteLine(" /* Non-Unique Indices */"); } streamWriter.WriteLine(" create index \"{0}\"", uniqueConstraintSchema.Name); streamWriter.WriteLine(" on \"{0}\"", tableSchema.Name); streamWriter.WriteLine(" ("); ColumnSchema[] keyFields = uniqueConstraintSchema.Columns; for (int columnIndex = 0; columnIndex < keyFields.Length; columnIndex++) { ColumnSchema columnSchema = keyFields[columnIndex]; streamWriter.Write(" \"{0}\"", columnSchema.Name); streamWriter.WriteLine(columnIndex == keyFields.Length - 1 ? "" : ","); } streamWriter.WriteLine(" ) on \"PRIMARY\" "); streamWriter.WriteLine(""); } } }
/// <summary> /// Creates a CodeDOM namespace FluidTrade.ClientGenerator contains the strongly typed DataSet. /// </summary> /// <param name="schema">The schema description of the strongly typed DataSet.</param> public Namespace(DataModelSchema dataModelSchema) { //namespace FluidTrade.ClientGenerator //{ this.Name = dataModelSchema.TargetNamespace; // Delegates foreach (TableSchema tableSchema in dataModelSchema.Tables.Values) { this.Types.Add(new RowChangeDelegate(tableSchema)); } // Classes foreach (TableSchema tableSchema in dataModelSchema.Tables.Values) { this.Types.Add(new TableClass.TableClass(tableSchema)); this.Types.Add(new RowClass.RowClass(tableSchema)); this.Types.Add(new FluidTrade.Core.ChangeEventArgsClass.ChangeEventArgsClass(tableSchema)); this.Types.Add(new FluidTrade.Core.IndexInterface.IndexInterface(tableSchema)); foreach (KeyValuePair <string, ConstraintSchema> constraintPair in tableSchema.Constraints) { if (constraintPair.Value is UniqueConstraintSchema) { UniqueConstraintSchema uniqueConstraintSchema = constraintPair.Value as UniqueConstraintSchema; if (uniqueConstraintSchema.IsPrimaryKey) { this.Types.Add(new ClusteredIndexClass.ClusteredIndexClass(uniqueConstraintSchema)); } else { this.Types.Add(new NonClusteredIndexClass.NonClusteredIndexClass(uniqueConstraintSchema)); } } } } this.Types.Add(new FluidTrade.ClientGenerator.TargetClass.TargetClass(dataModelSchema)); //} }
/// <summary> /// Creates a CodeDOM description of a strongly typed index. /// </summary> /// <param name="constraintSchema">The description of a unique constraint.</param> public Constructor(UniqueConstraintSchema uniqueConstraintSchema) { // /// <summary> // /// Create a secondary, unique index on the AccessControl table. // /// </summary> // /// <param name="indexName">The name of the index.</param> // /// <param name="columns">The columns that describe a unique key.</param> // public GenderKeyIndex(string indexName, System.Data.DataColumn[] columns) : // base(indexName, columns) { this.Comments.Add(new CodeCommentStatement("<summary>", true)); this.Comments.Add(new CodeCommentStatement(String.Format("Create a secondary, unique index on the {0} table.", uniqueConstraintSchema.Table.Name), true)); this.Comments.Add(new CodeCommentStatement("</summary>", true)); this.Comments.Add(new CodeCommentStatement("<param name=\"indexName\">The name of the index.</param>", true)); this.Comments.Add(new CodeCommentStatement("<param name=\"columns\">The columns that describe a unique key.</param>", true)); this.Attributes = MemberAttributes.Public; this.Name = String.Format("{0}Index", uniqueConstraintSchema.Name); this.Parameters.Add(new CodeParameterDeclarationExpression(new CodeGlobalTypeReference(typeof(String)), "indexName")); this.Parameters.Add(new CodeParameterDeclarationExpression(new CodeGlobalTypeReference(typeof(DataColumn[])), "columns")); this.BaseConstructorArgs.Add(new CodeArgumentReferenceExpression("indexName")); this.BaseConstructorArgs.Add(new CodeArgumentReferenceExpression("columns")); // } }
/// <summary> /// Creates a method that finds a row containing the given elements of an index. /// </summary> /// <param name="uniqueConstraintSchema">A description of a unique constraint.</param> public FindByKeyMethod(UniqueConstraintSchema uniqueConstraintSchema) { // /// <summary> // /// Finds a row in the Gender table containing the key elements. // /// </summary> // /// <param name="key">An array of key elements.</param> // /// <returns>A GenderKey row that contains the key elements, or null if there is no match.</returns> // public new GenderRow Find(object[] key) { this.Comments.Add(new CodeCommentStatement("<summary>", true)); this.Comments.Add(new CodeCommentStatement(string.Format("Finds a row in the {0} table containing the key elements.", uniqueConstraintSchema.Table.Name), true)); this.Comments.Add(new CodeCommentStatement("</summary>", true)); this.Comments.Add(new CodeCommentStatement("<param name=\"key\">An array of key elements.</param>", true)); this.Comments.Add(new CodeCommentStatement(string.Format("<returns>A {0} row that contains the key elements, or null if there is no match.</returns>", uniqueConstraintSchema.Name), true)); this.Attributes = MemberAttributes.Public | MemberAttributes.New | MemberAttributes.Final; this.ReturnType = new CodeTypeReference(string.Format("{0}Row", uniqueConstraintSchema.Table.Name)); this.Name = "Find"; this.Parameters.Add(new CodeParameterDeclarationExpression(new CodeGlobalTypeReference(typeof(System.Object[])), "key")); // // Return the strongly typed Object row that matches the key element(s). // return ((GenderRow)(base.Find(key))); this.Statements.Add(new CodeMethodReturnStatement(new CodeCastExpression(this.ReturnType, new CodeMethodInvokeExpression(new CodeBaseReferenceExpression(), "Find", new CodeArgumentReferenceExpression("key"))))); // } }
/// <summary> /// Creates a method that finds a row containing the given elements of an index. /// </summary> /// <param name="uniqueConstraintSchema">A description of a unique constraint.</param> public FindByKeyMethod(UniqueConstraintSchema uniqueConstraintSchema) { // /// <summary> // /// Finds a row in the AccountBase table containing the key elements. // /// </summary> // /// <param name="accountBaseId">The AccountBaseId element of the key.</param> // /// <returns>The AccountBase row that contains the key elements, or null if there is no match.</returns> // public AccountBaseRow Find(System.Guid accountBaseId) // { this.Comments.Add(new CodeCommentStatement("<summary>", true)); this.Comments.Add(new CodeCommentStatement(String.Format("Finds a row in the {0} table containing the key elements.", uniqueConstraintSchema.Table.Name), true)); this.Comments.Add(new CodeCommentStatement("</summary>", true)); this.Comments.Add(new CodeCommentStatement("<param name=\"key\">An array of key elements.</param>", true)); this.Comments.Add(new CodeCommentStatement(String.Format("<returns>A {0} row that contains the key elements, or null if there is no match.</returns>", uniqueConstraintSchema.Name), true)); this.Attributes = MemberAttributes.Public | MemberAttributes.New | MemberAttributes.Final; this.ReturnType = new CodeTypeReference(String.Format("{0}Row", uniqueConstraintSchema.Table.Name)); this.Name = "Find"; this.Parameters.Add(new CodeParameterDeclarationExpression(new CodeGlobalTypeReference(typeof(Object[])), "key")); // try // { // ((TenantDataModel)this.Table.DataSet).dataLock.EnterReadLock(); // return ((AccountBaseRow)(base.Find(new object[] { // accountBaseId}))); // } CodeTryCatchFinallyStatement tryCatchFinallyStatement = new CodeTryCatchFinallyStatement(); CodePropertyReferenceExpression tableExpression = new CodePropertyReferenceExpression( new CodeTypeReferenceExpression(String.Format("{0}", uniqueConstraintSchema.Table.DataModel.Name)), uniqueConstraintSchema.Table.Name); tryCatchFinallyStatement.TryStatements.Add( new CodeMethodInvokeExpression( new CodeFieldReferenceExpression( new CodeCastExpression( new CodeTypeReference(String.Format("Tenant{0}", uniqueConstraintSchema.Table.DataModelSchema.Name)), new CodePropertyReferenceExpression(new CodePropertyReferenceExpression(new CodeThisReferenceExpression(), "Table"), "DataSet")), "dataLock"), "EnterReadLock")); tryCatchFinallyStatement.TryStatements.Add(new CodeMethodReturnStatement(new CodeCastExpression(this.ReturnType, new CodeMethodInvokeExpression(new CodeBaseReferenceExpression(), "Find", new CodeArgumentReferenceExpression("key"))))); // catch (global::System.ArgumentException argumentException) // { // throw new global::System.ServiceModel.FaultException<Teraque.ArgumentFault>(new global::Teraque.ArgumentFault(argumentException.Message)); // } CodeCatchClause catchArgumentException = new CodeCatchClause("argumentException", new CodeGlobalTypeReference(typeof(ArgumentException))); catchArgumentException.Statements.Add(new CodeThrowArgumentExceptionStatement(new CodePropertyReferenceExpression(new CodeArgumentReferenceExpression("argumentException"), "Message"))); tryCatchFinallyStatement.CatchClauses.Add(catchArgumentException); // catch (global::System.FormatException formatException) // { // throw new global::System.ServiceModel.FaultException<Teraque.FormatFault>(new global::Teraque.FormatFault(formatException.Message)); // } CodeCatchClause catchFormatException = new CodeCatchClause("formatException", new CodeGlobalTypeReference(typeof(FormatException))); catchFormatException.Statements.Add(new CodeThrowFormatExceptionStatement(new CodePropertyReferenceExpression(new CodeArgumentReferenceExpression("formatException"), "Message"))); tryCatchFinallyStatement.CatchClauses.Add(catchFormatException); // finally // { // ((TenantDataModel)this.Table.DataSet).dataLock.ExitReadLock(); tryCatchFinallyStatement.FinallyStatements.Add( new CodeMethodInvokeExpression( new CodeFieldReferenceExpression( new CodeCastExpression( new CodeTypeReference(String.Format("Tenant{0}", uniqueConstraintSchema.Table.DataModelSchema.Name)), new CodePropertyReferenceExpression(new CodePropertyReferenceExpression(new CodeThisReferenceExpression(), "Table"), "DataSet")), "dataLock"), "ExitReadLock")); this.Statements.Add(tryCatchFinallyStatement); // } // } }
/// <summary> /// Creates a method that finds a row containing the given elements of an index. /// </summary> /// <param name="uniqueConstraintSchema">A description of a unique constraint.</param> public FindByMethod(UniqueConstraintSchema uniqueConstraintSchema) { // /// <summary> // /// Finds a row in the Configuration table containing the key elements. // /// </summary> // /// <param name="configurationId">The ConfigurationId element of the key.</param> // /// <param name="relationName">The RelationName element of the key.</param> // /// <returns>The Configuration row that contains the key elements, or null if there is no match.</returns> // public ConfigurationRow Find(string configurationId, string relationName) { this.Comments.Add(new CodeCommentStatement("<summary>", true)); this.Comments.Add(new CodeCommentStatement(string.Format("Finds a row in the {0} table containing the key elements.", uniqueConstraintSchema.Table.Name), true)); this.Comments.Add(new CodeCommentStatement("</summary>", true)); foreach (ColumnSchema columnSchema in uniqueConstraintSchema.Columns) { this.Comments.Add(new CodeCommentStatement(string.Format("<param name=\"{0}\">The {1} element of the key.</param>", CommonConversion.ToCamelCase(columnSchema.Name), columnSchema.Name), true)); } this.Comments.Add(new CodeCommentStatement(string.Format("<returns>The {0} row that contains the key elements, or null if there is no match.</returns>", uniqueConstraintSchema.Table.Name), true)); this.Attributes = MemberAttributes.Public | MemberAttributes.Final; this.ReturnType = new CodeTypeReference(string.Format("{0}Row", uniqueConstraintSchema.Table.Name)); this.Name = "Find"; foreach (ColumnSchema columnSchema in uniqueConstraintSchema.Columns) { this.Parameters.Add(new CodeParameterDeclarationExpression(columnSchema.DataType, CommonConversion.ToCamelCase(columnSchema.Name))); } // try { // DataModel.Configuration.AcquireLock(); // return ((ConfigurationRow)(base.Find(new object[] { // configurationId, // relationName}))); // } // catch (global::System.ArgumentException argumentException) { // throw new global::System.ServiceModel.FaultException<ArgumentFault>(new global::FluidTrade.Core.ArgumentFault(argumentException.Message)); // } // finally { // DataModel.Configuration.ReleaseLock(); // } CodeTryCatchFinallyStatement tryCatchFinallyStatement = new CodeTryCatchFinallyStatement(); CodePropertyReferenceExpression tableExpression = new CodePropertyReferenceExpression(new CodeTypeReferenceExpression(string.Format("{0}", uniqueConstraintSchema.Table.DataModel.Name)), uniqueConstraintSchema.Table.Name); tryCatchFinallyStatement.TryStatements.Add( new CodeMethodInvokeExpression( new CodePropertyReferenceExpression(new CodeTypeReferenceExpression(uniqueConstraintSchema.Table.DataModel.Name), "DataLock"), "EnterReadLock")); tryCatchFinallyStatement.TryStatements.Add(new CodeMethodReturnStatement(new CodeCastExpression(this.ReturnType, new CodeMethodInvokeExpression(new CodeBaseReferenceExpression(), "Find", new CodeKeyCreateExpression(uniqueConstraintSchema.Columns))))); CodeCatchClause catchArgumentException = new CodeCatchClause("argumentException", new CodeGlobalTypeReference(typeof(System.ArgumentException))); catchArgumentException.Statements.Add(new CodeThrowArgumentExceptionStatement(new CodePropertyReferenceExpression(new CodeArgumentReferenceExpression("argumentException"), "Message"))); tryCatchFinallyStatement.CatchClauses.Add(catchArgumentException); CodeCatchClause catchFormatException = new CodeCatchClause("formatException", new CodeGlobalTypeReference(typeof(System.FormatException))); catchFormatException.Statements.Add(new CodeThrowFormatExceptionStatement(new CodePropertyReferenceExpression(new CodeArgumentReferenceExpression("formatException"), "Message"))); tryCatchFinallyStatement.CatchClauses.Add(catchFormatException); tryCatchFinallyStatement.FinallyStatements.Add( new CodeMethodInvokeExpression( new CodePropertyReferenceExpression(new CodeTypeReferenceExpression(uniqueConstraintSchema.Table.DataModel.Name), "DataLock"), "ExitReadLock")); this.Statements.Add(tryCatchFinallyStatement); // } }
//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); }
private void AddConstraint(UniqueConstraintSchema uni) { string colstr = GetColumnsString(uni.Columns); store.AppendValues(uni.Name, uni.IsColumnConstraint, colstr, uni); }
/// <summary> /// Creates a method that finds a row containing the given elements of an index. /// </summary> /// <param name="uniqueConstraintSchema">A description of a unique constraint.</param> public FindByMethod(UniqueConstraintSchema uniqueConstraintSchema) { // /// <summary> // /// Finds a row in the BlotterConfiguration table containing the key elements. // /// </summary> // /// <param name="blotterId">The BlotterId element of the key.</param> // /// <param name="reportTypeId">The ReportTypeId element of the key.</param> // /// <returns>The BlotterConfiguration row that contains the key elements, or null if there is no match.</returns> // public BlotterConfigurationRow Find(System.Guid blotterId, System.Guid reportTypeId) // { this.Comments.Add(new CodeCommentStatement("<summary>", true)); this.Comments.Add(new CodeCommentStatement(String.Format("Finds a row in the {0} table containing the key elements.", uniqueConstraintSchema.Table.Name), true)); this.Comments.Add(new CodeCommentStatement("</summary>", true)); foreach (ColumnSchema columnSchema in uniqueConstraintSchema.Columns) { this.Comments.Add(new CodeCommentStatement(String.Format("<param name=\"{0}\">The {1} element of the key.</param>", CommonConversion.ToCamelCase(columnSchema.Name), columnSchema.Name), true)); } this.Comments.Add(new CodeCommentStatement(String.Format("<returns>The {0} row that contains the key elements, or null if there is no match.</returns>", uniqueConstraintSchema.Table.Name), true)); this.Attributes = MemberAttributes.Public | MemberAttributes.Final; this.ReturnType = new CodeTypeReference(String.Format("{0}Row", uniqueConstraintSchema.Table.Name)); this.Name = "Find"; foreach (ColumnSchema columnSchema in uniqueConstraintSchema.Columns) { this.Parameters.Add(new CodeParameterDeclarationExpression(columnSchema.DataType, CommonConversion.ToCamelCase(columnSchema.Name))); } // try // { // ((TenantDataModel)(this.Table.DataSet)).dataLock.EnterReadLock(); // return ((BlotterConfigurationRow)(base.Find(new object[] { // blotterId, // reportTypeId}))); // } CodeTryCatchFinallyStatement tryCatchFinallyStatement = new CodeTryCatchFinallyStatement(); CodePropertyReferenceExpression tableExpression = new CodePropertyReferenceExpression(new CodeTypeReferenceExpression(String.Format("{0}", uniqueConstraintSchema.Table.DataModel.Name)), uniqueConstraintSchema.Table.Name); tryCatchFinallyStatement.TryStatements.Add( new CodeMethodInvokeExpression( new CodeFieldReferenceExpression( new CodeCastExpression( new CodeTypeReference(String.Format("Tenant{0}", uniqueConstraintSchema.Table.DataModelSchema.Name)), new CodePropertyReferenceExpression(new CodePropertyReferenceExpression(new CodeThisReferenceExpression(), "Table"), "DataSet")), "dataLock"), "EnterReadLock")); tryCatchFinallyStatement.TryStatements.Add(new CodeMethodReturnStatement(new CodeCastExpression(this.ReturnType, new CodeMethodInvokeExpression(new CodeBaseReferenceExpression(), "Find", new CodeKeyCreateExpression(uniqueConstraintSchema.Columns))))); // catch (global::System.ArgumentException argumentException) // { // throw new global::System.ServiceModel.FaultException<Teraque.ArgumentFault>(new global::Teraque.ArgumentFault(argumentException.Message)); // } CodeCatchClause catchArgumentException = new CodeCatchClause("argumentException", new CodeGlobalTypeReference(typeof(ArgumentException))); catchArgumentException.Statements.Add(new CodeThrowArgumentExceptionStatement(new CodePropertyReferenceExpression(new CodeArgumentReferenceExpression("argumentException"), "Message"))); tryCatchFinallyStatement.CatchClauses.Add(catchArgumentException); // catch (global::System.FormatException formatException) // { // throw new global::System.ServiceModel.FaultException<Teraque.FormatFault>(new global::Teraque.FormatFault(formatException.Message)); // } CodeCatchClause catchFormatException = new CodeCatchClause("formatException", new CodeGlobalTypeReference(typeof(FormatException))); catchFormatException.Statements.Add(new CodeThrowFormatExceptionStatement(new CodePropertyReferenceExpression(new CodeArgumentReferenceExpression("formatException"), "Message"))); tryCatchFinallyStatement.CatchClauses.Add(catchFormatException); // finally // { // ((TenantDataModel)(this.Table.DataSet)).dataLock.ExitReadLock(); tryCatchFinallyStatement.FinallyStatements.Add( new CodeMethodInvokeExpression( new CodeFieldReferenceExpression( new CodeCastExpression( new CodeTypeReference(String.Format("Tenant{0}", uniqueConstraintSchema.Table.DataModelSchema.Name)), new CodePropertyReferenceExpression(new CodePropertyReferenceExpression(new CodeThisReferenceExpression(), "Table"), "DataSet")), "dataLock"), "ExitReadLock")); this.Statements.Add(tryCatchFinallyStatement); // } // } }
/// <summary> /// Creates a strongly typed DataSet from a schema description. /// </summary> /// <param name="dataSetNamespace">The CodeDOM namespace Teraque.DataModelGenerator.TargetClass public TargetClass(DataModelSchema dataModelSchema) { // /// <summary> // /// A thread-safe, multi-tiered DataModel. // /// </summary> // [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Teraque.DataModelGenerator.Server", "1.3.1.0")] // [global::System.ComponentModel.DesignerCategoryAttribute("code")] // [global::System.ComponentModel.ToolboxItemAttribute(true)] // public class DataModel : Teraque.UnitTest.Server.IDataModel { this.Comments.Add(new CodeCommentStatement("<summary>", true)); this.Comments.Add(new CodeCommentStatement(String.Format("A thread-safe, multi-tiered {0}.", dataModelSchema.Name), true)); this.Comments.Add(new CodeCommentStatement("</summary>", true)); this.CustomAttributes.Add(new CodeGeneratedCodeAttribute(typeof(ClientGenerator))); this.CustomAttributes.Add(new CodeAttributeDeclaration(new CodeGlobalTypeReference(typeof(DesignerCategoryAttribute)), new CodeAttributeArgument(new CodePrimitiveExpression("code")))); this.CustomAttributes.Add(new CodeAttributeDeclaration(new CodeGlobalTypeReference(typeof(ToolboxItemAttribute)), new CodeAttributeArgument(new CodePrimitiveExpression(true)))); this.Name = dataModelSchema.Name; this.TypeAttributes = TypeAttributes.Public | TypeAttributes.Class; this.IsPartial = true; // Private Constants List <CodeMemberField> constantList = new List <CodeMemberField>(); constantList.Add(new DeletedTimeColumnField()); constantList.Add(new PrimaryKeyOffsetField()); constantList.Add(new RefreshIntervalField()); constantList.Add(new RowDataIndexField()); constantList.Add(new RowStateIndexField()); constantList.Add(new RowVersionColumnField()); constantList.Add(new TableRowsIndexField()); constantList.Add(new TableTableNameIndexField()); constantList.Add(new ThreadWaitTimeField()); constantList.Sort(delegate(CodeMemberField firstField, CodeMemberField secondField) { return(firstField.Name.CompareTo(secondField.Name)); }); foreach (CodeMemberField codeMemberField in constantList) { this.Members.Add(codeMemberField); } // Classes List <CodeTypeDeclaration> classItemList = new List <CodeTypeDeclaration>(); classItemList.Add(new MergeStateClass(dataModelSchema)); classItemList.Sort(delegate(CodeTypeDeclaration firstField, CodeTypeDeclaration secondField) { return(firstField.Name.CompareTo(secondField.Name)); }); foreach (CodeTypeDeclaration classItem in classItemList) { this.Members.Add(classItem); } // Private Instance Fields List <CodeMemberField> fieldList = new List <CodeMemberField>(); fieldList.Add(new BatchSizeField()); fieldList.Add(new DataSetField()); fieldList.Add(new DataSetIdField()); fieldList.Add(new IsReadingField()); fieldList.Add(new MergeStateQueueField()); fieldList.Add(new ReadDataModelThreadField()); fieldList.Add(new SequenceField()); fieldList.Add(new SyncRootField()); fieldList.Add(new TenantNotLoadedField()); fieldList.Add(new UpdateBufferMutexField()); fieldList.Add(new SyncUpdateField()); foreach (KeyValuePair <String, TableSchema> keyValuePair in dataModelSchema.Tables) { fieldList.Add(new TableField(keyValuePair.Value)); } foreach (KeyValuePair <String, RelationSchema> relationPair in dataModelSchema.Relations) { fieldList.Add(new RelationField(relationPair.Value)); } fieldList.Sort(delegate(CodeMemberField firstField, CodeMemberField secondField) { return(firstField.Name.CompareTo(secondField.Name)); }); foreach (CodeMemberField codeMemberField in fieldList) { this.Members.Add(codeMemberField); } // Constructors this.Members.Add(new StaticConstructor(dataModelSchema)); // Properties List <CodeMemberProperty> propertyList = new List <CodeMemberProperty>(); propertyList.Add(new IsReconcilingProperty(dataModelSchema)); propertyList.Add(new SyncRootProperty(dataModelSchema)); propertyList.Add(new RelationsProperty(dataModelSchema)); propertyList.Add(new TablesProperty(dataModelSchema)); foreach (KeyValuePair <String, TableSchema> keyValuePair in dataModelSchema.Tables) { propertyList.Add(new TableProperty(keyValuePair.Value)); } propertyList.Sort(delegate(CodeMemberProperty firstProperty, CodeMemberProperty secondProperty) { return(firstProperty.Name.CompareTo(secondProperty.Name)); }); foreach (CodeMemberProperty codeMemberProperty in propertyList) { this.Members.Add(codeMemberProperty); } // Methods List <CodeMemberMethod> methodList = new List <CodeMemberMethod>(); methodList.Add(new MergeDataModelMethod(dataModelSchema)); methodList.Add(new ReadDataModelMethod(dataModelSchema)); methodList.Add(new StartMergeMethod(dataModelSchema)); methodList.Add(new ReadXmlMethod(dataModelSchema)); methodList.Add(new ResetMethod(dataModelSchema)); methodList.Add(new WriteXmlMethod(dataModelSchema)); methodList.Sort(delegate(CodeMemberMethod firstMethod, CodeMemberMethod secondMethod) { return(firstMethod.Name.CompareTo(secondMethod.Name)); }); foreach (CodeMemberMethod codeMemberMethod in methodList) { this.Members.Add(codeMemberMethod); } // Delegates foreach (KeyValuePair <String, TableSchema> keyValuePair in dataModelSchema.Tables) { this.Members.Add(new RowChangeDelegate(keyValuePair.Value)); } // Tables foreach (KeyValuePair <String, TableSchema> keyValuePair in dataModelSchema.Tables) { this.Members.Add(new TableClass.TableClass(keyValuePair.Value)); } // Create a type for each of the rows. foreach (KeyValuePair <String, TableSchema> keyValuePair in dataModelSchema.Tables) { this.Members.Add(new RowClass.RowClass(keyValuePair.Value)); } // Create a strongly typed version of the ChangeEventArgs class for each table. foreach (KeyValuePair <String, TableSchema> keyValuePair in dataModelSchema.Tables) { this.Members.Add(new ChangeEventArgsClass.ChangeEventArgsClass(keyValuePair.Value)); } // Create the strongly typed indices. foreach (KeyValuePair <String, TableSchema> keyValuePair in dataModelSchema.Tables) { this.Members.Add(new Teraque.DataModelGenerator.IndexInterface.IndexInterface(keyValuePair.Value)); foreach (KeyValuePair <string, ConstraintSchema> constraintPair in keyValuePair.Value.Constraints) { if (constraintPair.Value is UniqueConstraintSchema) { UniqueConstraintSchema uniqueConstraintSchema = constraintPair.Value as UniqueConstraintSchema; if (uniqueConstraintSchema.IsPrimaryKey) { this.Members.Add(new ClusteredIndexClass.ClusteredIndexClass(uniqueConstraintSchema)); } else { this.Members.Add(new NonClusteredIndexClass.NonClusteredIndexClass(uniqueConstraintSchema)); } } } } }
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;
/// <summary> /// Creates a strongly typed DataSet from a schema description. /// </summary> /// <param name="dataSetNamespace">The CodeDOM namespace Teraque.DataModelGenerator.TargetClass public TargetClass(DataModelSchema dataModelSchema) { // /// <summary> // /// A thread-safe, multi-tiered DataModel. // /// </summary> // [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Teraque.DataModelGenerator.Server", "1.3.1.0")] // [global::System.ComponentModel.DesignerCategoryAttribute("code")] // [global::System.ComponentModel.ToolboxItemAttribute(true)] // public class DataModel : Teraque.UnitTest.Server.IDataModel { this.Comments.Add(new CodeCommentStatement("<summary>", true)); this.Comments.Add(new CodeCommentStatement(String.Format("A thread-safe, multi-tiered {0}.", dataModelSchema.Name), true)); this.Comments.Add(new CodeCommentStatement("</summary>", true)); this.CustomAttributes.Add(new CodeGeneratedCodeAttribute(typeof(DataModelGenerator))); this.CustomAttributes.Add(new CodeAttributeDeclaration(new CodeGlobalTypeReference(typeof(DesignerCategoryAttribute)), new CodeAttributeArgument(new CodePrimitiveExpression("code")))); this.CustomAttributes.Add(new CodeAttributeDeclaration(new CodeGlobalTypeReference(typeof(ToolboxItemAttribute)), new CodeAttributeArgument(new CodePrimitiveExpression(true)))); this.Name = dataModelSchema.Name; this.TypeAttributes = TypeAttributes.Public | TypeAttributes.Class; this.BaseTypes.Add(new CodeTypeReference(String.Format("I{0}", dataModelSchema.Name))); this.IsPartial = true; // Private Instance Fields List <CodeMemberField> privateInstanceFieldList = new List <CodeMemberField>(); privateInstanceFieldList.Add(new TenantMapField(dataModelSchema)); privateInstanceFieldList.Sort((first, second) => { return(first.Name.CompareTo(second.Name)); }); foreach (CodeMemberField codeMemberField in privateInstanceFieldList) { this.Members.Add(codeMemberField); } // Properties List <CodeMemberProperty> propertyList = new List <CodeMemberProperty>(); propertyList.Add(new LockTimeoutProperty(dataModelSchema)); propertyList.Add(new CurrentTransactionProperty(dataModelSchema)); propertyList.Add(new TenantTargetProperty(dataModelSchema)); propertyList.Add(new DataLockProperty(dataModelSchema)); propertyList.Add(new RelationsProperty(dataModelSchema)); foreach (KeyValuePair <String, TableSchema> keyValuePair in dataModelSchema.Tables) { propertyList.Add(new TableProperty(keyValuePair.Value)); } propertyList.Add(new TablesProperty(dataModelSchema)); propertyList.Sort((first, second) => { return(first.Name.CompareTo(second.Name)); }); foreach (CodeMemberProperty codeMemberProperty in propertyList) { this.Members.Add(codeMemberProperty); } // Methods List <CodeMemberMethod> methodList = new List <CodeMemberMethod>(); methodList.Add(new GetTenantsMethod(dataModelSchema)); methodList.Add(new LoadTenantMethod(dataModelSchema)); methodList.Add(new UnloadTenantMethod(dataModelSchema)); methodList.Add(new ReadMethod(dataModelSchema)); methodList.Add(new ReadXmlMethod(dataModelSchema)); foreach (KeyValuePair <String, TableSchema> tablePair in dataModelSchema.Tables) { methodList.Add(new CreateMethod(tablePair.Value)); methodList.Add(new DestroyMethod(tablePair.Value)); methodList.Add(new StoreMethod(tablePair.Value)); methodList.Add(new UpdateMethod(tablePair.Value)); } methodList.Sort((first, second) => { return(first.Name.CompareTo(second.Name)); }); foreach (CodeMemberMethod codeMemberMethod in methodList) { this.Members.Add(codeMemberMethod); } // Delegates foreach (KeyValuePair <String, TableSchema> keyValuePair in dataModelSchema.Tables) { this.Members.Add(new RowChangeDelegate(keyValuePair.Value)); } // Tables foreach (KeyValuePair <String, TableSchema> keyValuePair in dataModelSchema.Tables) { this.Members.Add(new TableClass.TableClass(keyValuePair.Value)); } // Create a type for each of the rows. foreach (KeyValuePair <String, TableSchema> keyValuePair in dataModelSchema.Tables) { this.Members.Add(new RowClass.RowClass(keyValuePair.Value)); } // Create a strongly typed version of the ChangeEventArgs class for each table. foreach (KeyValuePair <String, TableSchema> keyValuePair in dataModelSchema.Tables) { this.Members.Add(new ChangeEventArgsClass.ChangeEventArgsClass(keyValuePair.Value)); } // Create the strongly typed indices. foreach (KeyValuePair <String, TableSchema> keyValuePair in dataModelSchema.Tables) { this.Members.Add(new Teraque.DataModelGenerator.IndexInterface.IndexInterface(keyValuePair.Value)); foreach (KeyValuePair <String, ConstraintSchema> constraintPair in keyValuePair.Value.Constraints) { if (constraintPair.Value is UniqueConstraintSchema) { UniqueConstraintSchema uniqueConstraintSchema = constraintPair.Value as UniqueConstraintSchema; if (uniqueConstraintSchema.IsPrimaryKey) { this.Members.Add(new ClusteredIndexClass.ClusteredIndexClass(uniqueConstraintSchema)); } else { this.Members.Add(new NonClusteredIndexClass.NonClusteredIndexClass(uniqueConstraintSchema)); } } } } }
/// <summary> /// Creates a CodeDOM namespace FluidTrade.MiddleTierGenerator contains the strongly typed DataSet. /// </summary> /// <param name="schema">The schema description of the strongly typed DataSet.</param> public Namespace(DataModelSchema dataModelSchema) { //namespace FluidTrade.MiddleTierGenerator //{ this.Name = dataModelSchema.TargetNamespace; // Delegates List <CodeTypeDelegate> delegateList = new List <CodeTypeDelegate>(); delegateList.Add(new FilterContextDelegate(dataModelSchema)); foreach (TableSchema tableSchema in dataModelSchema.Tables.Values) { delegateList.Add(new RowChangeDelegate(tableSchema)); } delegateList.Sort( delegate(CodeTypeDelegate firstDelegate, CodeTypeDelegate secondDelegate) { return(firstDelegate.Name.CompareTo(secondDelegate.Name)); }); foreach (CodeTypeDelegate codeTypeDelegate in delegateList) { this.Types.Add(codeTypeDelegate); } // Types List <CodeTypeDeclaration> typeList = new List <CodeTypeDeclaration>(); typeList.Add(new DataSetClass.DataSetClass(dataModelSchema)); typeList.Add(new FieldCollectorClass.FieldCollectorClass(dataModelSchema)); //typeList.Add(new FluidTrade.Core.RowInterface.RowInterface(dataModelSchema)); //typeList.Add(new FluidTrade.Core.TableInterface.TableInterface(dataModelSchema)); typeList.Add(new TargetClass.TargetClass(dataModelSchema)); //typeList.Add(new TransactionClass.TransactionClass(dataModelSchema)); typeList.Add(new TransactionLogItemClass.TransactionLogItemClass(dataModelSchema)); foreach (TableSchema tableSchema in dataModelSchema.Tables.Values) { typeList.Add(new RowClass.RowClass(tableSchema)); typeList.Add(new TableClass.TableClass(tableSchema)); typeList.Add(new FluidTrade.Core.ChangeEventArgsClass.ChangeEventArgsClass(tableSchema)); typeList.Add(new FluidTrade.Core.IndexInterface.IndexInterface(tableSchema)); foreach (KeyValuePair <string, ConstraintSchema> constraintPair in tableSchema.Constraints) { if (constraintPair.Value is UniqueConstraintSchema) { UniqueConstraintSchema uniqueConstraintSchema = constraintPair.Value as UniqueConstraintSchema; if (uniqueConstraintSchema.IsPrimaryKey) { typeList.Add(new ClusteredIndexClass.ClusteredIndexClass(uniqueConstraintSchema)); } else { typeList.Add(new NonClusteredIndexClass.NonClusteredIndexClass(uniqueConstraintSchema)); } } } } typeList.Sort( delegate(CodeTypeDeclaration firstDeclaration, CodeTypeDeclaration secondDeclaration) { return(firstDeclaration.Name.CompareTo(secondDeclaration.Name)); }); foreach (CodeTypeDeclaration codeTypeDeclaration in typeList) { this.Types.Add(codeTypeDeclaration); } //} }
/// <summary> /// Generates a property to get a parent row. /// </summary> /// <param name="foreignKeyConstraintSchema">The foreign key that references the parent table.</param> public VoidConstructor(TableSchema tableSchema) { // Construct the type names for the table and rows within the table. string rowTypeName = string.Format("{0}Row", tableSchema.Name); // /// <summary> // /// Creates the Engineer table. // /// </summary> // internal EngineerDataTable() { this.Comments.Add(new CodeCommentStatement("<summary>", true)); this.Comments.Add(new CodeCommentStatement(string.Format("Creates the {0} table.", tableSchema.Name), true)); this.Comments.Add(new CodeCommentStatement("</summary>", true)); this.Attributes = MemberAttributes.Assembly; // this.TableName = "Account"; this.Statements.Add( new CodeAssignStatement( new CodePropertyReferenceExpression(new CodeThisReferenceExpression(), "TableName"), new CodePrimitiveExpression(tableSchema.Name))); // this.ExtendedProperties["IsPersistent"] = true; this.Statements.Add( new CodeAssignStatement( new CodeIndexerExpression( new CodePropertyReferenceExpression(new CodeThisReferenceExpression(), "ExtendedProperties"), new CodePrimitiveExpression("IsPersistent")), new CodePrimitiveExpression(tableSchema.IsPersistent))); // this.filterRowHandler = this.FilterRow; this.Statements.Add( new CodeAssignStatement( new CodeFieldReferenceExpression(new CodeThisReferenceExpression(), "filterRowHandler"), new CodeMethodReferenceExpression(new CodeThisReferenceExpression(), "FilterRow"))); // this.getContainerHandler = this.GetContainer; this.Statements.Add( new CodeAssignStatement( new CodeFieldReferenceExpression(new CodeThisReferenceExpression(), "getContainerHandler"), new CodeMethodReferenceExpression(new CodeThisReferenceExpression(), "GetContainer"))); // this.columnEngineerId = new global::System.Data.DataColumn("EngineerId", typeof(int), null, global::System.Data.MappingType.Element); // this.columnEngineerId.ExtendedProperties["IsPersistent"] = true; // this.columnEngineerId.AllowDBNull = false; // this.Columns.Add(this.columnEngineerId); // this.columnManagerId = new global::System.Data.DataColumn("ManagerId", typeof(int), null, global::System.Data.MappingType.Element); // this.columnManagerId.ExtendedProperties["IsPersistent"] = true; // this.columnManagerId.DefaultValue = global::System.DBNull.Value; // this.Columns.Add(this.columnManagerId); // this.columnRowVersion = new global::System.Data.DataColumn("RowVersion", typeof(long), null, global::System.Data.MappingType.Element); // this.columnRowVersion.ExtendedProperties["IsPersistent"] = true; // this.columnRowVersion.AllowDBNull = false; // this.Columns.Add(this.columnRowVersion); foreach (ColumnSchema columnSchema in tableSchema.Columns.Values) { // Create the column using the datatype specified in the schema. // this.columnDepartmentId = new global::System.Data.DataColumn("DepartmentId", typeof(int), null, global::System.Data.MappingType.Element); CodeExpression right = new CodeObjectCreateExpression(new CodeGlobalTypeReference(typeof(System.Data.DataColumn)), new CodePrimitiveExpression(columnSchema.Name), new CodeTypeOfExpression(columnSchema.DataType), new CodePrimitiveExpression(null), new CodePropertyReferenceExpression(new CodeGlobalTypeReferenceExpression(typeof(System.Data.MappingType)), "Element")); this.Statements.Add(new CodeAssignStatement(new CodePropertyReferenceExpression(new CodeThisReferenceExpression(), string.Format("column{0}", columnSchema.Name)), right)); // this.columnColumnIndex.ExtendedProperties["IsPersistent"] = true; this.Statements.Add(new CodeAssignStatement(new CodeIndexerExpression(new CodePropertyReferenceExpression(new CodeFieldReferenceExpression(new CodeThisReferenceExpression(), string.Format("column{0}", columnSchema.Name)), "ExtendedProperties"), new CodePrimitiveExpression("IsPersistent")), new CodePrimitiveExpression(columnSchema.IsPersistent))); // AutoIncrement, AutoIncrementSeed and AutoIncrementStep Properties. if (columnSchema.IsAutoIncrement) { this.Statements.Add(new CodeAssignStatement(new CodePropertyReferenceExpression(new CodePropertyReferenceExpression(new CodeThisReferenceExpression(), string.Format("column{0}", columnSchema.Name)), "AutoIncrement"), new CodePrimitiveExpression(true))); if (columnSchema.AutoIncrementSeed > 0) { this.Statements.Add(new CodeAssignStatement(new CodePropertyReferenceExpression(new CodePropertyReferenceExpression(new CodeThisReferenceExpression(), string.Format("column{0}", columnSchema.Name)), "AutoIncrementSeed"), new CodePrimitiveExpression(columnSchema.AutoIncrementSeed))); } if (columnSchema.AutoIncrementStep > 1) { this.Statements.Add(new CodeAssignStatement(new CodePropertyReferenceExpression(new CodePropertyReferenceExpression(new CodeThisReferenceExpression(), string.Format("column{0}", columnSchema.Name)), "AutoIncrementStep"), new CodePrimitiveExpression(columnSchema.AutoIncrementStep))); } } // AllowDBNull Column property if (!columnSchema.IsNullable) { this.Statements.Add(new CodeAssignStatement(new CodePropertyReferenceExpression(new CodePropertyReferenceExpression(new CodeThisReferenceExpression(), string.Format("column{0}", columnSchema.Name)), "AllowDBNull"), new CodePrimitiveExpression(false))); } // The default value exists as a string in the Xml Schema. It must be stronly typed before being inserted into // the target code. Unfortunately, the type information for the destination column is needed to convert the // value properly. if (columnSchema.DefaultValue != DBNull.Value) { this.Statements.Add(new CodeAssignStatement(new CodePropertyReferenceExpression(new CodePropertyReferenceExpression(new CodeThisReferenceExpression(), string.Format("column{0}", columnSchema.Name)), "DefaultValue"), CodeConvert.CreateConstantExpression(columnSchema.DefaultValue))); } // This will add the column created above to the table. this.Statements.Add(new CodeMethodInvokeExpression(new CodePropertyReferenceExpression(new CodeThisReferenceExpression(), "Columns"), "Add", new CodePropertyReferenceExpression(new CodeThisReferenceExpression(), string.Format("column{0}", columnSchema.Name)))); } // // The EngineerKey Index // this.indexEngineerKey = new EngineerKeyIndex(new global::System.Data.DataColumn[] { // this.columnEngineerId}); foreach (KeyValuePair <string, ConstraintSchema> constraintPair in tableSchema.Constraints) { if (constraintPair.Value is UniqueConstraintSchema) { UniqueConstraintSchema uniqueConstraintSchema = constraintPair.Value as UniqueConstraintSchema; string indexVariableName = string.Format("index{0}", uniqueConstraintSchema.Name); List <CodeExpression> keyColumns = new List <CodeExpression>(); foreach (ColumnSchema columnSchema in uniqueConstraintSchema.Columns) { keyColumns.Add(new CodePropertyReferenceExpression(new CodeThisReferenceExpression(), string.Format("column{0}", columnSchema.Name))); } this.Statements.Add(new CodeAssignStatement(new CodePropertyReferenceExpression(new CodeThisReferenceExpression(), indexVariableName), new CodeObjectCreateExpression(new CodeTypeReference(string.Format("{0}Index", uniqueConstraintSchema.Name)), new CodePrimitiveExpression(uniqueConstraintSchema.Name), new CodeArrayCreateExpression(new CodeGlobalTypeReference(typeof(System.Data.DataColumn)), keyColumns.ToArray())))); if (!uniqueConstraintSchema.IsPrimaryKey && !uniqueConstraintSchema.IsNullable) { this.Statements.Add(new CodeMethodInvokeExpression(new CodePropertyReferenceExpression(new CodeThisReferenceExpression(), "Constraints"), "Add", new CodeObjectCreateExpression(new CodeGlobalTypeReference(typeof(System.Data.UniqueConstraint)), new CodeArrayCreateExpression(new CodeGlobalTypeReference(typeof(System.Data.DataColumn)), keyColumns.ToArray())))); } this.Statements.Add(new CodeMethodInvokeExpression(new CodePropertyReferenceExpression(new CodeThisReferenceExpression(), "Indices"), "Add", new CodePropertyReferenceExpression(new CodeThisReferenceExpression(), indexVariableName))); } } // } }
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> /// 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; }