public override SqlSchema GetSchema(GetSchemaArgs args) { SqlSchema schema = base.GetSchema(args); if (schema == null) { throw new InvalidOperationException("schema is null."); } // mbr - 02-10-2007 - for c7 - if we have a search spec, don't do sprocs... if (args.ConstrainTableNames.Count == 0) { // mbr - 15-06-2006 - now do procedures... DataTable table = this.Connection.ExecuteDataTable(new SqlStatement("select specific_name, routine_definition from information_schema.routines where routine_type='PROCEDURE' order by specific_name", this.Dialect)); foreach (DataRow row in table.Rows) { try { // create... SqlProcedure proc = this.GetSchemaProcedure(schema, row); schema.Procedures.Add(proc); } catch (Exception ex) { throw new InvalidOperationException(string.Format("Failed to handle stored procedure '{0}'.\r\nBody: {1}", row["specific_name"], row["routine_definition"]), ex); } } } // return... return(schema); }
/// <summary> /// Returns true if the link is supported within the given schema. /// </summary> /// <param name="schema"></param> /// <returns></returns> /// <remarks>Essentially, this will check that the parent table is referenced in the schema.</remarks> internal bool IsSupported(SqlSchema schema) { if (this.ChildToParentEntityLink != null) { // check... EntityType et = this.ChildToParentEntityLink.ParentEntityType; if (et == null) { throw new InvalidOperationException("et is null."); } // walk... foreach (SqlTable table in schema.Tables) { if (string.Compare(table.Name, et.NativeName.Name, true, Cultures.System) == 0) { return(true); } } // nope... return(false); } else { // if we don't have a child to parent link, we're ok... return(true); } }
internal override void Fixup() { base.Fixup(); // mangle... SqlSchema.MangleDuplicateNames(this.Columns.ToArray()); }
/// <summary> /// Constructor. /// </summary> internal SqlChildToParentLink(SqlSchema schema, ChildToParentEntityLink entityLink) : base(entityLink.NativeName.Name) { // mbr - 04-10-2007 - force the schema... // _schema = schema; this.SetSchema(schema); _childToParentEntityLink = entityLink; }
/// <summary> /// Gets the schema structure for the given entity type. /// </summary> /// <param name="entityType"></param> /// <returns></returns> public static SqlTable GetTable(SqlSchema schema, EntityType entityType) { if (entityType == null) { throw new ArgumentNullException("entityType"); } return(new SqlTable(schema, entityType)); }
///// <summary> ///// Gets the work units that describe the differences between two schemas. ///// </summary> ///// <param name="existingSchema"></param> ///// <returns></returns> //public WorkUnitCollection GetSchemaWorkUnits(SqlSchema existingSchema) //{ // return this.GetSchemaWorkUnits(existingSchema, null); //} /// <summary> /// Gets the work units that describe the differences between two schemas. /// </summary> /// <param name="existingSchema"></param> /// <returns></returns> public WorkUnitCollection GetSchemaWorkUnits(SqlSchema existingSchema, IOperationItem operation = null) { if (existingSchema == null) { throw new ArgumentNullException("existingSchema"); } // item... if (operation == null) { operation = new OperationItem(); } // results... WorkUnitCollection results = new WorkUnitCollection(); // find missing tables... operation.ProgressMaximum = this.Tables.Count; operation.ProgressValue = 0; foreach (SqlTable table in this.Tables) { // walk... SqlTable matchingTable = null; foreach (SqlTable existingTable in existingSchema.Tables) { if (string.Compare(table.NativeName, existingTable.NativeName, true, System.Globalization.CultureInfo.InvariantCulture) == 0) { matchingTable = existingTable; break; } } // found? if (matchingTable == null) { results.AddRange(table.GetCreateTableWorkUnit()); } else { results.AddRange(table.GetSchemaWorkUnits(matchingTable)); } // next... operation.IncrementProgress(); } // mbr - 14-12-2005 - sort the units... results.Sort(new SchemaWorkUnitTypeComparer()); // return... return(results); }
/// <summary> /// Creates the schema. /// </summary> /// <returns></returns> // mbr - 02-10-2007 - added optional specification. public virtual SqlSchema GetSchema(GetSchemaArgs args) { // create... SqlSchema schema = new SqlSchema(); // gets a datatable of information_schema... if (Connection == null) { throw new InvalidOperationException("Connection is null."); } // sql... SqlStatement sql = new SqlStatement(this.Dialect); // mbr - 02-10-2007 - build the sql, now including the search specification... StringBuilder builder = new StringBuilder(); builder.Append("SELECT DISTINCT TABLE_NAME FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_TYPE='BASE TABLE'"); if (args.ConstrainTableNames.Count > 0) { builder.Append(" AND ("); this.AppendTableNameConstraint(sql, builder, args.ConstrainTableNames); builder.Append(")"); } if (args.ConstrainSchemaNames.Count > 0) { builder.Append(" AND ("); this.AppendSchemaNameConstraint(sql, builder, args.ConstrainSchemaNames); builder.Append(")"); } builder.Append(" ORDER BY TABLE_NAME"); // get... sql.CommandText = builder.ToString(); DataTable table = this.Connection.ExecuteDataTable(sql); // walk... foreach (DataRow row in table.Rows) { // create a new schema table... SqlTable schemaTable = this.GetSchemaTable(row, schema); schema.Tables.Add(schemaTable); // mbr - 04-10-2007 - set owner... schemaTable.SetSchema(schema); } // return... return(schema); }
public override void AddSchemaTables(EntityType et, Type type, BootFX.Common.Data.Schema.SqlTable coreTable, BootFX.Common.Data.Schema.SqlSchema entitySchema) { // base... base.AddSchemaTables(et, type, coreTable, entitySchema); // have we done anything? if (!(et.HasExtendedProperties)) { return; } // create a table... SqlTable table = new SqlTable(et, et.NativeNameExtended.Name); // key... EntityField[] keyFields = et.GetKeyFields(); if (keyFields == null) { throw new InvalidOperationException("keyFields is null."); } ArrayList extendedKeyColumns = new ArrayList(); foreach (EntityField keyField in keyFields) { SqlColumn column = new SqlColumn(MangleIdColumnName(keyField.NativeName), keyField.DBType, keyField.Size, EntityFieldFlags.Key); // add... table.Columns.Add(column); extendedKeyColumns.Add(column); } // columns... foreach (EntityField field in et.GetExtendedProperties()) { table.Columns.Add(new SqlColumn(field)); } // relationship to parent... SqlChildToParentLink link = new SqlChildToParentLink(string.Format("FK_{0}_{1}", et.NativeName.Name, et.NativeNameExtended.Name), coreTable); link.LinkFields.AddRange((SqlColumn[])extendedKeyColumns.ToArray(typeof(SqlColumn))); link.Columns.AddRange(coreTable.GetKeyColumns()); table.LinksToParents.Add(link); // add... entitySchema.Tables.Add(table); }
/// <summary> /// Loads the project from XML. /// </summary> /// <param name="filePath"></param> /// <returns></returns> public static SqlSchema FromXml(XmlDocument document) { if (document == null) { throw new ArgumentNullException("document"); } // create a new one... SqlSchema newSchema = new SqlSchema(); newSchema.MergeInternal(document, true); // return... return(newSchema); }
/// <summary> /// Creates a table for the given type. /// </summary> /// <param name="type"></param> public static void CreateTable(Type type, IConnection conn = null) { if (type == null) { throw new ArgumentNullException("type"); } // get it... EntityType et = EntityType.GetEntityType(type, OnNotFound.ThrowException); if (et == null) { throw new InvalidOperationException("et is null."); } // create... SqlSchema schema = new SqlSchema(); SqlTable table = new SqlTable(schema, et); string[] scripts = Database.DefaultDialect.GetCreateTableScript(table, SqlTableScriptFlags.None); if (scripts == null) { throw new InvalidOperationException("scripts is null."); } // walk... var doClose = false; if (conn == null) { conn = Database.CreateConnection(et); doClose = true; } try { foreach (string script in scripts) { conn.ExecuteNonQuery(new SqlStatement(script)); } } finally { if (doClose) { conn.Dispose(); } } }
/// <summary> /// Fixes up the object. /// </summary> internal override void Fixup() { // base... base.Fixup(); // make sure we don't have columns with the same name as the table... foreach (SqlColumn column in this.Columns) { if (string.Compare(column.Name, Name, true, System.Globalization.CultureInfo.InvariantCulture) == 0) { column.Name += "Value"; } } // TODO: make sure we don't have duplicate items... // fixup columns... for (int index = 0; index < this.Columns.Count; index++) { this.Columns[index].Fixup(); this.Columns[index].Ordinal = index; } // mangle index names... SqlSchema.MangleDuplicateNames(this.Indexes.ToArray()); // fixup indexes... for (int index = 0; index < this.Indexes.Count; index++) { // fix... this.Indexes[index].Fixup(); this.Indexes[index].Ordinal = index; } // copy... foreach (SqlChildToParentLink parentLink in this.LinksToParents) { if (parentLink.Name == null || parentLink.Name.Length == 0 || parentLink.Name == parentLink.NativeName) { parentLink.Name = parentLink.ParentTable.Name; } } // mangle link names... SqlSchema.MangleDuplicateNames(this.LinksToParents.ToArray()); }
/// <summary> /// Creates a SQL table from an entity type. /// </summary> /// <param name="entityType"></param> public SqlTable(SqlSchema schema, EntityType entityType) : base(entityType.NativeName.Name, entityType.Name) { // store the entity type for later use _entityType = entityType; // init... this.Initialize(); // mbr - 04-10-2007 - set the schema... this.SetSchema(schema); // columns... foreach (EntityField field in entityType.Fields) { // mbr - 07-12-2005 - only non-extended... if (!(field.IsExtendedProperty)) { // mbr - 04-10-2007 - set schema... SqlColumn column = new SqlColumn(field); column.SetSchema(schema); this.Columns.Add(column); } } // indexes... foreach (EntityIndex index in entityType.Indexes) { // mbr - 04-10-2007 - set schema... SqlIndex sqlIndex = new SqlIndex(this, index); sqlIndex.SetSchema(schema); this.Indexes.Add(sqlIndex); } // relationships... foreach (ChildToParentEntityLink relationship in entityType.Links) { this.LinksToParents.Add(new SqlChildToParentLink(schema, relationship)); } }
private SqlProcedure GetSchemaProcedure(SqlSchema schema, DataRow row) { if (schema == null) { throw new ArgumentNullException("schema"); } if (row == null) { throw new ArgumentNullException("row"); } // create... SqlProcedure proc = new SqlProcedure((string)row["specific_name"]); proc.Body = ConversionHelper.ToString(row["routine_definition"], Cultures.System); // handle... this.ParseProcedureBody(schema, proc); // return... return(proc); }
/// <summary> /// Fixes up the project after the schema has been loaded, or a merge has been performed. /// </summary> /// <remarks>The principle of this is to automatically smooth over some of the sins of auto-generation. For example, /// if the entity is called Rate, and this has a field called Rate, the field name will be changed to RateValue.</remarks> internal void Fixup() { // mangle... SqlSchema.MangleDuplicateNames(this.Tables.ToArray()); // fix... foreach (SqlTable table in this.Tables) { table.Fixup(); } // with each table done, walk them again and reset the child tables... foreach (SqlTable table in this.Tables) { // clear... table.AssociatedLinks.Clear(); // walk the other tables... foreach (SqlTable childTable in this.Tables) { // not this... if (table != childTable) { // child to parent... foreach (SqlChildToParentLink link in childTable.LinksToParents) { // found... if (link.ParentTable == table) { table.AssociatedLinks.Add(link); } } } } } }
/// <summary> /// Sets the schema. /// </summary> /// <param name="schema"></param> internal void SetSchema(SqlSchema schema) { _schema = schema; }
private void ParseProcedureBody(SqlSchema schema, SqlProcedure proc) { if (schema == null) { throw new ArgumentNullException("schema"); } if (proc == null) { throw new ArgumentNullException("proc"); } // reset... proc.Parameters.Clear(); if (proc.Body == null || proc.Body.Length == 0) { return; } // add the params... Match asMatch = AsRegex.Match(proc.Body); if (asMatch.Success) { // header... string header = proc.Body.Substring(0, asMatch.Index); // get... foreach (Match paramMatch in ParamsRegex.Matches(header)) { string name = paramMatch.Groups["name"].Value; if (name == null) { throw new InvalidOperationException("'name' is null."); } if (name.Length == 0) { throw new InvalidOperationException("'name' is zero-length."); } try { // type... string typeName = paramMatch.Groups["type"].Value; if (typeName == null) { throw new InvalidOperationException("'typeName' is null."); } if (typeName.Length == 0) { throw new InvalidOperationException("'typeName' is zero-length."); } // mbr - 26-02-2007 - is the type name parameterized? typeName = typeName.ToLower(); // are we output? const string outputDirective = " output"; if (typeName.EndsWith(outputDirective)) { typeName = typeName.Substring(typeName.Length - outputDirective.Length).TrimEnd(); } // field... FieldSpecification spec = this.Connection.GetFieldSpecificationForNativeTypeName(typeName, false); if (spec != null) { DbType dbType = spec.DbType; // dimension et al... string dimensionAsString = paramMatch.Groups["dimension"].Value; string defaultValueAsString = paramMatch.Groups["default"].Value; // direction... string directionAsString = paramMatch.Groups["direction"].Value; ParameterDirection direction = ParameterDirection.Input; if (directionAsString != null && directionAsString.Length > 0) { directionAsString = directionAsString.ToLower(); if (directionAsString.StartsWith("out")) { direction = ParameterDirection.Output; } } // value... object defaultValue = DBNull.Value; // create... proc.Parameters.Add(new SqlStatementParameter(name, dbType, defaultValue, direction)); } else { proc.Parameters.Add(new SqlStatementParameter(name, DbType.Object, DBNull.Value)); } } catch (Exception ex) { throw new InvalidOperationException(string.Format("Failed when processing parameter '{0}'\r\nText: {1}", name, paramMatch.Value), ex); } } } }
/// <summary> /// Creates a table from the given row. /// </summary> /// <param name="row"></param> /// <returns></returns> private SqlTable GetSchemaTable(DataRow row, SqlSchema schema) { if (row == null) { throw new ArgumentNullException("row"); } if (schema == null) { throw new ArgumentNullException("schema"); } // get the name... string nativeName = (string)row["table_name"]; if (nativeName == null) { throw new ArgumentNullException("nativeName"); } if (nativeName.Length == 0) { throw new ArgumentOutOfRangeException("'nativeName' is zero-length."); } try { // name... string name = SqlTable.SuggestSingularName(nativeName); name = CodeDomHelper.GetPascalName(name); // create... SqlTable schemaTable = new SqlTable(nativeName, name); // mbr - 04-10-2007 - set schema... schemaTable.SetSchema(schema); // get the columns... if (Connection == null) { throw new InvalidOperationException("Connection is null."); } DataTable table = this.Connection.ExecuteDataTable(new SqlStatement("select column_name, is_nullable, data_type, character_maximum_length from information_schema.columns where table_name=@p0 order by ordinal_position", new object[] { nativeName }, this.Dialect)); foreach (DataRow columnRow in table.Rows) { // create... SqlColumn schemaColumn = this.GetSchemaColumn(columnRow); schemaTable.Columns.Add(schemaColumn); // mbr - 04-10-2007 - set owner... schemaColumn.SetSchema(schemaTable.Schema); // mbr - 01-11-2005 - added SQL Server specific stuff... this.ColumnDiscovered(schemaColumn); } // fix... FixupCommonFlags(schemaTable); // mbr - 01-11-2005 - added opportunity to fixup... TableDiscovered(schemaTable); // return... return(schemaTable); } catch (Exception ex) { throw new InvalidOperationException(string.Format("Failed when processing table '{0}'.", nativeName), ex); } }