// REWRITTEN... private static IList <ZeroToOneRelationInfo> GetZeroToOneRelations(Table table) { IList <ZeroToOneRelationInfo> relations = new List <ZeroToOneRelationInfo>(); foreach (Column column in table.Columns) { if (!column.IsForeignKey) { continue; } ZeroToOneRelationInfo relation = new ZeroToOneRelationInfo(); SmoForeignKeyColumnInfo fkInfo = SmoHelper.GetForeignKeyColumnInfo(column); relation.TableName = table.Name; relation.ColumnName = column.Name; relation.ReferencedTableName = fkInfo.ReferencedTable.Name; relation.ReferencedColumnName = fkInfo.ReferencedColumn.Name; relations.Add(relation); } return(relations); }
private bool CheckIfForeignKeyColumn(Column column) { if (column.IsForeignKey) { Table table = (Table)column.Parent; SmoForeignKeyColumnInfo fkInfo = SmoHelper.GetForeignKeyColumnInfo(column); if (!column.Name.StartsWith(string.Format("{0}_Id{1}", table.Name, fkInfo.ReferencedTable.Name))) { this.AddError(table.Name, column.Name, ModelDescriptorError.ForeignKeyNamesMustRespectPattern); this.AddError(table.Name, column.Name, ModelDescriptorError.ReportDocumentationNamings); //this.AddError(table.Name, column.Name, "Try with '{0}_Id{1}' or '{0}_Id{1}Suffix'", table.Name, fkInfo.ReferencedTable.Name); return(false); } string columnNameWithoutTableName = WithoutTableName(table.Name, column.Name); if (columnNameWithoutTableName.Substring(2) == table.Name) { this.AddError(table.Name, column.Name, ModelDescriptorError.ColumnNameNotAllowed); //this.AddError(table.Name, column.Name, "Try with a suffix '{0}Parent'", column.Name); return(false); } if (fkInfo.ReferencedTable.Name == table.Name && !column.Nullable) { this.AddError(table.Name, column.Name, ModelDescriptorError.ForeignKeyMustBeNull); return(false); } } return(true); }
internal void Process(string t4Template, string outputFilePath, ITemplateDefinition definition, ProcessorParameters parameters) { var ttParams = new TextTemplatingParameters( t4Template, outputFilePath, definition.OverrideFileIfExists, definition.AddToProject); string tmpOutputFilePath; try { var state = this.TextTemplatingEngine.Process(ttParams, out tmpOutputFilePath); if (state == ProcessStateEnum.Processed) { // SQL scripts... if (definition.ExecuteSqlScript) { bool canExecuted = true; if (definition is TemplateDefinitions.Database.InsertAllStoredProceduresGeneratedSqlTemplateDefinition && !parameters.WithSqlProcedureIntegration) { canExecuted = false; } if (canExecuted) { this.PublishProcessMessage("Executing {0}...", Path.GetFileName(tmpOutputFilePath)); try { SmoHelper.RunSqlScript(tmpOutputFilePath, this.SmoContext); } catch { // Create a copy of the tmpOutputFilePath file (for debug) because it will be deleted at the end of the whole process... FileHelper.TryCopy(tmpOutputFilePath, string.Concat(tmpOutputFilePath, ".err"), withOverwrite: true); throw; } } } } this.HasErrors |= state == ProcessStateEnum.Failed; } catch (Exception x) { this.PublishErrorMessage("Failed while processing {0} -> {1}", Path.GetFileName(t4Template), x.Message); } foreach (CompilerError error in this.TextTemplatingEngine.Errors) { this.PublishErrorMessage( "Template error: {0}({1},{2}): error {3}: {4}", Path.GetFileName(this.TextTemplatingEngine.Errors.First().FileName), error.Line, error.Column, error.ErrorNumber, error.ErrorText); } }
private bool CheckColumn(Column column) { Table table = (Table)column.Parent; string columnName = WithoutTableName(table.Name, column.Name); if (column.IsForeignKey) // important to have the right error message (FK vs PK) { if (!column.Name.StartsWith(string.Format("{0}_Id", table.Name))) { SmoForeignKeyColumnInfo fkInfo = SmoHelper.GetForeignKeyColumnInfo(column); this.AddError(table.Name, column.Name, ModelDescriptorError.ForeignKeyNamesMustRespectPattern); this.AddError(table.Name, column.Name, ModelDescriptorError.ReportDocumentationNamings); return(false); } } else { if (!column.Name.StartsWith(string.Format("{0}_", table.Name))) { this.AddError(table.Name, column.Name, ModelDescriptorError.ColumnNamesMustRespectPattern); this.AddError(table.Name, column.Name, ModelDescriptorError.ReportDocumentationNamings); return(false); } } if (IsReserved(columnName)) { string alternativeName = string.Format("{0}_{1}{2}", table.Name, columnName[0].ToString().ToUpperInvariant(), columnName.Substring(1)); this.AddError(table.Name, column.Name, ModelDescriptorError.ColumnNameNotAllowedKeywordReserved, columnName); //this.AddError(table.Name, column.Name, "Try with '{0}'.", alternativeName); return(false); } if (column.Name.Equals(string.Format("{0}_State", table.Name))) { this.AddError(table.Name, column.Name, ModelDescriptorError.ColumnNameNotAllowedStateKeywordReserved); return(false); } return(true); }
private static IList <ZeroToManyRelationInfo> GetZeroToManyRelations(Table table) { IList <ZeroToManyRelationInfo> relations = new List <ZeroToManyRelationInfo>(); Database database = (Database)table.Parent; foreach (Table refTable in database.Tables) { /*if (refTable == table) // Entity.generated.cs / IsLoop = true / commented to support hierarchied-entities * continue;*/ foreach (Column refColumn in refTable.Columns) { if (!refColumn.IsForeignKey) { continue; } SmoForeignKeyColumnInfo fkInfo = SmoHelper.GetForeignKeyColumnInfo(refColumn); if (fkInfo.ReferencedTable.Name != table.Name) { continue; } ZeroToManyRelationInfo relation = new ZeroToManyRelationInfo(); relation.TableName = table.Name; relation.ColumnName = refColumn.Name; relation.ReferencedTableName = refTable.Name; relation.ReferencedColumnName = fkInfo.ReferencedColumn.Name; relations.Add(relation); } } return(relations); }
private LanguageColumnInfo GetLanguageColumnInfo(Column column) { Table table = (Table)column.Parent; LanguageColumnInfo info = new LanguageColumnInfo(); int cultureLength = _context.Culture.SupportedCultures[0].Length; if (column.Name.Length < cultureLength + 1) { return(info); } SqlCSharpConvertionTypeInfo typeInfo = new SqlCSharpConvertionTypeInfo(column); if (typeInfo.CSharpType != typeof(string)) { return(info); } bool isLanguageColumn = this.IsCultureSupported(column.Name.Substring(column.Name.Length - cultureLength)); if (!isLanguageColumn) { return(info); } info.IsLanguageColumn = true; info.ColumnNameWithoutCulture = column.Name.Substring(0, column.Name.Length - cultureLength - 1); foreach (Column c in table.Columns) { if (string.Compare(c.Name, info.ColumnNameWithoutCulture, true) == 0) { this.AddError(table.Name, null, ModelDescriptorError.ColumnCannotBeDefined, c.Name); } } foreach (string culture in _context.Culture.SupportedCultures) { bool bColumnFound = false; string cName = string.Format("{0}_{1}", info.ColumnNameWithoutCulture, culture); foreach (Column tColumn in table.Columns) { if (tColumn.Name == cName) { bColumnFound = true; info.LanguageColumnNames.Add(tColumn.Name); string defaultValue = null; bool bHasDefaultValue = SmoHelper.ParseColumnDefaultValue(tColumn, out defaultValue); if (bHasDefaultValue) { info.DefaultValues.Add(culture, defaultValue); } if (tColumn.DataType.Name != column.DataType.Name) { this.AddError(table.Name, column.Name, ModelDescriptorError.DataTypesMismatchDataType, table.Name, column.Name); } if (tColumn.DataType.MaximumLength != column.DataType.MaximumLength) { this.AddError(table.Name, column.Name, ModelDescriptorError.DataTypesMismatchMaximumLength, table.Name, column.Name); } if (tColumn.Nullable != column.Nullable) { this.AddError(table.Name, column.Name, ModelDescriptorError.DataTypesMismatchNullable, table.Name, column.Name); } info.IsNullable = column.Nullable; } } if (!bColumnFound) { this.AddError(table.Name, null, ModelDescriptorError.TableMuseDefineTheColumn, table.Name, cName); } } return(info); }
public string Load(CancellationToken token) { StringBuilder sbContent = new StringBuilder(1024 * 32); this.Errors = new List <ModelDescriptorError>(); sbContent.AppendFormat("<?xml version=\"1.0\" encoding=\"utf-8\" standalone=\"yes\"?>"); sbContent.AppendFormat("<ModelDescriptorSchema>"); sbContent.AppendFormat("<Tables>"); foreach (Table table in _smoContext.GetSmoDatabase().Tables) { this.CurrentTable = table; if (token.IsCancellationRequested) { return(string.Empty); } if (IsReserved(table.Name)) { this.AddError(table.Name, null, ModelDescriptorError.TableNameNotAllowedKeywordReserved, table.Name); } if (IsIgnoredTable(table)) { continue; } #region [ Table ] sbContent.AppendFormat("<Table>"); bool withCodeRef = HasCodeRefColumn(table); sbContent.AppendFormat("<Name>{0}</Name>", table.Name); sbContent.AppendFormat("<HasIdUserColumn>{0}</HasIdUserColumn>", HasIdUserColumn(table).ToString().ToLowerInvariant()); sbContent.AppendFormat("<HasCodeRefColumn>{0}</HasCodeRefColumn>", withCodeRef.ToString().ToLowerInvariant()); sbContent.AppendFormat("<IsOwnership>{0}</IsOwnership>", IsOwnershipTable(table).ToString().ToLowerInvariant()); sbContent.AppendFormat("<Columns>"); #endregion IList <string> languageColumnNames = new List <string>(); foreach (Column column in table.Columns) { this.CurrentColumn = column; if (token.IsCancellationRequested) { return(string.Empty); } if (!CheckColumn(column)) { continue; } if (!CheckIfPrimaryKeyColumn(column)) { continue; } if (!CheckIfForeignKeyColumn(column)) { continue; } if (!CheckIfCodeRefColumn(column)) { continue; } if (languageColumnNames.Contains(column.Name)) { continue; } languageColumnNames.Clear(); LanguageColumnInfo lcInfo = this.GetLanguageColumnInfo(column); languageColumnNames = lcInfo.LanguageColumnNames; SqlCSharpConvertionTypeInfo typeInfo = new SqlCSharpConvertionTypeInfo(column); #region [ Column ] sbContent.AppendFormat("<Column>"); if (lcInfo.IsLanguageColumn) { string csharpPropertyName = GetCSharpPropertyName(table.Name, lcInfo.ColumnNameWithoutCulture); sbContent.AppendFormat("<Name>{0}</Name>", lcInfo.ColumnNameWithoutCulture); sbContent.AppendFormat("<IsNullable>{0}</IsNullable>", lcInfo.IsNullable.ToString().ToLowerInvariant()); sbContent.AppendFormat("<CSharpPropertyName>{0}</CSharpPropertyName>", csharpPropertyName); } else { sbContent.AppendFormat("<Name>{0}</Name>", column.Name); sbContent.AppendFormat("<IsNullable>{0}</IsNullable>", typeInfo.IsNullable.ToString().ToLowerInvariant()); sbContent.AppendFormat("<CSharpPropertyName>{0}</CSharpPropertyName>", GetCSharpPropertyName(column)); } sbContent.AppendFormat("<SqlTypeName>{0}</SqlTypeName>", typeInfo.SqlTypeName); sbContent.AppendFormat("<SqlTypeNameEx>{0}</SqlTypeNameEx>", typeInfo.SqlTypeNameEx); if (typeInfo.CSharpType == typeof(string)) { sbContent.AppendFormat("<MaximumLength>{0}</MaximumLength>", typeInfo.MaximumLength); } if (typeInfo.CSharpType == typeof(decimal) || typeInfo.CSharpType == typeof(decimal?)) { sbContent.AppendFormat("<NumericPrecision>{0}</NumericPrecision>", typeInfo.NumericPrecision); sbContent.AppendFormat("<NumericScale>{0}</NumericScale>", typeInfo.NumericScale); } if (typeInfo.CSharpType == typeof(DateTime?)) { sbContent.AppendFormat("<NumericScale>{0}</NumericScale>", typeInfo.NumericScale); } sbContent.AppendFormat("<CSharpTypeName>{0}</CSharpTypeName>", typeInfo.CSharpTypeName); sbContent.AppendFormat("<CSharpIsTypeNullable>{0}</CSharpIsTypeNullable>", typeInfo.CSharpIsTypeNullable.ToString().ToLowerInvariant()); sbContent.AppendFormat("<IsIdColumn>{0}</IsIdColumn>", IsIdColumn(column).ToString().ToLowerInvariant()); sbContent.AppendFormat("<IsOwnershipColumn>{0}</IsOwnershipColumn>", IsOwnershipColumn(column).ToString().ToLowerInvariant()); #region [ Description ] string description = SmoHelper.GetColumnDescription(column); if (description != null) { sbContent.AppendFormat("<Description><![CDATA[{0}]]></Description>", SmoHelper.GetColumnDescription(column)); } #endregion #region [ LanguageColumns ] sbContent.AppendFormat("<IsLanguageColumn>{0}</IsLanguageColumn>", lcInfo.IsLanguageColumn.ToString().ToLowerInvariant()); if (lcInfo.IsLanguageColumn) { sbContent.AppendFormat("<LanguageColumns>"); foreach (string languageColumnName in lcInfo.LanguageColumnNames) { sbContent.AppendFormat("<LanguageColumn>"); sbContent.AppendFormat("<Name>{0}</Name>", languageColumnName); sbContent.AppendFormat("<Culture>{0}</Culture>", languageColumnName.Substring(languageColumnName.LastIndexOf('_') + 1)); sbContent.AppendFormat("<CSharpPropertyName>{0}</CSharpPropertyName>", GetCSharpPropertyName(table.Name, languageColumnName)); sbContent.AppendFormat("</LanguageColumn>"); } sbContent.AppendFormat("</LanguageColumns>"); } #endregion #region [ ForeignKey ] sbContent.AppendFormat("<IsForeignKey>{0}</IsForeignKey>", column.IsForeignKey.ToString().ToLowerInvariant()); if (column.IsForeignKey) { sbContent.AppendFormat("<ForeignKey>"); SmoForeignKeyColumnInfo fkInfo = SmoHelper.GetForeignKeyColumnInfo(column); sbContent.AppendFormat("<TableName>{0}</TableName>", fkInfo.ReferencedTable.Name); sbContent.AppendFormat("<ColumnName>{0}</ColumnName>", fkInfo.ReferencedColumn.Name); sbContent.AppendFormat("<CSharpPropertyName>{0}</CSharpPropertyName>", GetCSharpPropertyName(table.Name, column.Name).Substring(2)); sbContent.AppendFormat("</ForeignKey>"); } #endregion #region [ DefaultValues ] if (lcInfo.IsLanguageColumn) { sbContent.AppendFormat("<DefaultValues>"); foreach (string culture in _context.Culture.SupportedCultures) { sbContent.AppendFormat("<DefaultValue>"); sbContent.AppendFormat("<Culture>{0}</Culture>", culture); if (lcInfo.DefaultValues.ContainsKey(culture) && lcInfo.DefaultValues[culture] != null) { sbContent.AppendFormat("<Value><![CDATA[{0}]]></Value>", lcInfo.DefaultValues[culture]); } else { sbContent.AppendFormat("<Value><![CDATA[null]]></Value>"); } sbContent.AppendFormat("</DefaultValue>"); } sbContent.AppendFormat("</DefaultValues>"); } else { string defaultValue; bool hasDefaultValue = SmoHelper.ParseColumnDefaultValue(column, out defaultValue); if (hasDefaultValue) { sbContent.AppendFormat("<DefaultValue><![CDATA[{0}]]></DefaultValue>", defaultValue); } } #endregion sbContent.AppendFormat("</Column>"); #endregion } sbContent.AppendFormat("</Columns>"); #region [ CodeRefs ] if (withCodeRef) { sbContent.AppendFormat("<CodeRefs>"); foreach (var codeRef in DatabaseHelper.GetCodeRefs(_smoContext, table.Name)) { sbContent.AppendFormat("<CodeRef><Id>{0}</Id><Value>{1}</Value></CodeRef>", codeRef.Id, codeRef.Value); } sbContent.AppendFormat("</CodeRefs>"); } #endregion #region [ Constraints ] bool hasUniqueConstraints = false; foreach (Index index in table.Indexes) { if (index.IndexKeyType == IndexKeyType.DriUniqueKey) { hasUniqueConstraints = true; break; } } if (hasUniqueConstraints) { sbContent.AppendFormat("<Constraints>"); foreach (Index index in table.Indexes) { if (token.IsCancellationRequested) { return(string.Empty); } if (index.IndexKeyType == IndexKeyType.DriUniqueKey) { sbContent.AppendFormat("<Unique>"); sbContent.AppendFormat("<Columns>"); string idxColumnName = null; foreach (IndexedColumn idxColumn in index.IndexedColumns) { if (idxColumnName == null) { idxColumnName = idxColumn.Name; } else { idxColumnName = string.Format("{0}_{1}", idxColumnName, idxColumn.Name); } string culture; string columnNameWithoutCulture; bool isLanguageColumn = this.IsLanguageColumn(idxColumn.Name, out culture, out columnNameWithoutCulture); sbContent.AppendFormat("<Column>"); sbContent.AppendFormat("<Name>{0}</Name>", idxColumn.Name); sbContent.AppendFormat("<NameWithoutTableName>{0}</NameWithoutTableName>", WithoutTableName(table.Name, idxColumn.Name)); if (isLanguageColumn) { sbContent.AppendFormat("<Culture>{0}</Culture>", culture); sbContent.AppendFormat("<NameWithoutCulture>{0}</NameWithoutCulture>", columnNameWithoutCulture); sbContent.AppendFormat("<NameWithoutTableNameWithoutCulture>{0}</NameWithoutTableNameWithoutCulture>", WithoutTableName(table.Name, columnNameWithoutCulture)); } sbContent.AppendFormat("</Column>"); } sbContent.AppendFormat("</Columns>"); sbContent.AppendFormat("</Unique>"); } } sbContent.AppendFormat("</Constraints>"); } #endregion #region [ Relations ] #region [ ZeroToOne ] IList <ZeroToOneRelationInfo> zeroToOneRelations = GetZeroToOneRelations(table); if (zeroToOneRelations.Count != 0) { sbContent.AppendFormat("<ZeroToOneRelations>"); foreach (var relation in zeroToOneRelations) { try { string csharpPropertyName = GetCSharpPropertyName(relation.TableName, relation.ColumnName).Substring(2); sbContent.AppendFormat("<ZeroToOneRelation>"); sbContent.AppendFormat("<IsLoop>{0}</IsLoop>", relation.IsLoop.ToString().ToLowerInvariant()); sbContent.AppendFormat("<TableName>{0}</TableName>", relation.TableName); sbContent.AppendFormat("<ColumnName>{0}</ColumnName>", relation.ColumnName); sbContent.AppendFormat("<ReferencedTableName>{0}</ReferencedTableName>", relation.ReferencedTableName); sbContent.AppendFormat("<ReferencedColumnName>{0}</ReferencedColumnName>", relation.ReferencedColumnName); sbContent.AppendFormat("<CSharpPropertyName>{0}</CSharpPropertyName>", csharpPropertyName); sbContent.AppendFormat("</ZeroToOneRelation>"); } catch { this.AddError(table.Name, relation.ColumnName, ModelDescriptorError.ForeignKeyNamesMustRespectPattern); this.AddError(table.Name, relation.ColumnName, ModelDescriptorError.ReportDocumentationNamings); break; } } sbContent.AppendFormat("</ZeroToOneRelations>"); } #endregion #region [ ZeroToMany ] IList <ZeroToManyRelationInfo> zeroToManyRelations = GetZeroToManyRelations(table); if (zeroToManyRelations.Count != 0) { sbContent.AppendFormat("<ZeroToManyRelations>"); foreach (var relation in zeroToManyRelations) { try { string csharpPropertyName = GetCSharpPropertyName(relation.ReferencedTableName, relation.ColumnName).Substring(2); sbContent.AppendFormat("<ZeroToManyRelation>"); sbContent.AppendFormat("<IsLoop>{0}</IsLoop>", relation.IsLoop.ToString().ToLowerInvariant()); sbContent.AppendFormat("<TableName>{0}</TableName>", relation.TableName); sbContent.AppendFormat("<ColumnName>{0}</ColumnName>", relation.ColumnName); sbContent.AppendFormat("<ReferencedTableName>{0}</ReferencedTableName>", relation.ReferencedTableName); sbContent.AppendFormat("<ReferencedColumnName>{0}</ReferencedColumnName>", relation.ReferencedColumnName); csharpPropertyName = csharpPropertyName.TrimStart(relation.TableName); csharpPropertyName = string.Concat(relation.ReferencedTableName, csharpPropertyName); sbContent.AppendFormat("<CSharpPropertyName>{0}</CSharpPropertyName>", csharpPropertyName); sbContent.AppendFormat("</ZeroToManyRelation>"); } catch { this.AddError(relation.ReferencedTableName, relation.ColumnName, ModelDescriptorError.ForeignKeyNamesMustRespectPattern); this.AddError(relation.ReferencedTableName, relation.ColumnName, ModelDescriptorError.ReportDocumentationNamings); break; } } sbContent.AppendFormat("</ZeroToManyRelations>"); } #endregion #endregion sbContent.AppendFormat("</Table>"); } sbContent.AppendFormat("</Tables>"); sbContent.AppendFormat("</ModelDescriptorSchema>"); string descriptorFile = Path.Combine(Path.GetTempPath(), "LayerCake Generator", _context.ProjectName, string.Format("{0}.xml", _context.ProjectName)); if (!Directory.Exists(Path.GetDirectoryName(descriptorFile))) { Directory.CreateDirectory(Path.GetDirectoryName(descriptorFile)); } File.WriteAllText(descriptorFile, sbContent.ToString()); this.Load(descriptorFile); return(descriptorFile); }
/// <summary> /// Executes a SQL script using SMO API. /// </summary> /// /// <param name="scriptPath"> /// Path of the script to execute. /// </param> /// /// <param name="smoContext"> /// SmoContext instance. /// </param> public static void RunSqlScript(string scriptPath, SmoContext smoContext) { SmoHelper.RunSqlScript(scriptPath, smoContext.DatabaseHost, smoContext.DatabaseName, smoContext.Username, smoContext.Password); }