protected override void AddCompositeIdGenerator(XmlDocument xmldoc, XmlElement idElement, List<ColumnDetail> compositeKey, ApplicationPreferences applicationPreferences) { foreach (ColumnDetail column in compositeKey) { var keyElement = xmldoc.CreateElement("key-property"); string propertyName = column.ColumnName.GetPreferenceFormattedText(applicationPreferences); if (applicationPreferences.FieldGenerationConvention == FieldGenerationConvention.Property) { idElement.SetAttribute("name", propertyName.MakeFirstCharLowerCase()); } else { if (applicationPreferences.FieldGenerationConvention == FieldGenerationConvention.AutoProperty) { propertyName = column.ColumnName.GetFormattedText(); } keyElement.SetAttribute("name", propertyName); } var mapper = new DataTypeMapper(); Type mapFromDbType = mapper.MapFromDBType(column.DataType, column.DataLength, column.DataPrecision, column.DataScale); keyElement.SetAttribute("type", mapFromDbType.Name); keyElement.SetAttribute("column", column.ColumnName); if (applicationPreferences.FieldGenerationConvention != FieldGenerationConvention.AutoProperty) { keyElement.SetAttribute("access", "field"); } idElement.AppendChild(keyElement); } }
private void CreateFullProperties(CodeGenerationHelper codeGenerationHelper, DataTypeMapper mapper, CodeTypeDeclaration newType) { foreach (var pk in Table.PrimaryKey.Columns) { var mapFromDbType = mapper.MapFromDBType(this.appPrefs.ServerType, pk.DataType, pk.DataLength, pk.DataPrecision, pk.DataScale); newType.Members.Add(codeGenerationHelper.CreateField(mapFromDbType, Formatter.FormatText(pk.Name), true)); newType.Members.Add(codeGenerationHelper.CreateProperty(mapFromDbType, Formatter.FormatText(pk.Name), appPrefs.UseLazy)); } // Note that a foreign key referencing a primary within the same table will end up giving you a foreign key property with the same name as the table. foreach (var fk in Table.ForeignKeys.Where(fk => !string.IsNullOrEmpty(fk.References))) { newType.Members.Add(codeGenerationHelper.CreateField(appPrefs.ClassNamePrefix + Formatter.FormatSingular(fk.References), Formatter.FormatSingular(fk.UniquePropertyName))); newType.Members.Add(codeGenerationHelper.CreateProperty(appPrefs.ClassNamePrefix + Formatter.FormatSingular(fk.References), Formatter.FormatSingular(fk.UniquePropertyName), appPrefs.UseLazy)); } foreach (var column in Table.Columns.Where(x => x.IsPrimaryKey != true)) { if (!appPrefs.IncludeForeignKeys && column.IsForeignKey) { continue; } var mapFromDbType = mapper.MapFromDBType(this.appPrefs.ServerType, column.DataType, column.DataLength, column.DataPrecision, column.DataScale); newType.Members.Add(codeGenerationHelper.CreateField(mapFromDbType, Formatter.FormatText(column.Name), true, column.IsNullable)); newType.Members.Add(codeGenerationHelper.CreateProperty(mapFromDbType, Formatter.FormatText(column.Name), column.IsNullable, appPrefs.UseLazy)); } }
private static string GetTestValue(Column column) { if (DataTypeMapper.IsNumericType(column.MappedDataType)) { return("1"); } if (column.MappedDataType == typeof(string)) { return($"\"{column.Name}\""); } if (column.MappedDataType.IsEnum) { return(Enum.GetValues(column.MappedDataType).GetValue(0).ToString()); } if (column.MappedDataType == typeof(DateTime)) { return("DateTime.Now"); } if (column.MappedDataType == typeof(bool)) { return("true"); } if (column.MappedDataType == typeof(byte)) { return("0"); } return(null); }
public CodeCompileUnit GetCompileUnit(string className) { var codeGenerationHelper = new CodeGenerationHelper(); var compileUnit = codeGenerationHelper.GetCodeCompileUnitWithInheritanceAndInterface(nameSpace, className, appPrefs.InheritenceAndInterfaces); var mapper = new DataTypeMapper(); var newType = compileUnit.Namespaces[0].Types[0]; newType.IsPartial = appPrefs.GeneratePartialClasses; CreateProperties(codeGenerationHelper, mapper, newType); var constructorStatements = new CodeStatementCollection(); foreach (var hasMany in Table.HasManyRelationships) { newType.Members.Add(codeGenerationHelper.CreateAutoProperty(appPrefs.ForeignEntityCollectionType + "<" + appPrefs.ClassNamePrefix + Formatter.FormatSingular(hasMany.Reference) + ">", "Lista" + Formatter.FormatSingular(hasMany.Reference), appPrefs.UseLazy)); //constructorStatements.Add(new CodeSnippetStatement(string.Format(TABS + "{0} = new {1}<{2}{3}>();", Formatter.FormatPlural(hasMany.Reference), codeGenerationHelper.InstatiationObject(appPrefs.ForeignEntityCollectionType), appPrefs.ClassNamePrefix, Formatter.FormatSingular(hasMany.Reference)))); } var constructor = new CodeConstructor { Attributes = MemberAttributes.Public }; constructor.Statements.AddRange(constructorStatements); newType.Members.Add(constructor); return(compileUnit); }
private void CreateFields(CodeGenerationHelper codeGenerationHelper, DataTypeMapper mapper, CodeTypeDeclaration newType) { if (Table.PrimaryKey != null) { foreach (var pk in Table.PrimaryKey.Columns) { var mapFromDbType = mapper.MapFromDBType(this.appPrefs.ServerType, pk.DataType, pk.DataLength, pk.DataPrecision, pk.DataScale); newType.Members.Add(codeGenerationHelper.CreateField(mapFromDbType, Formatter.FormatText(pk.Name), true)); } } if (appPrefs.IncludeForeignKeys) { var pascalCaseTextFormatter = new PascalCaseTextFormatter(); // Note that a foreign key referencing a primary within the same table will end up giving you a foreign key property with the same name as the table. foreach (var fk in Table.ForeignKeys.Where(fk => !string.IsNullOrEmpty(fk.References))) { var fieldName = Formatter.FormatSingular(fk.UniquePropertyName); var typeName = appPrefs.ClassNamePrefix + pascalCaseTextFormatter.FormatSingular(fk.References); newType.Members.Add(codeGenerationHelper.CreateField(typeName, fieldName)); } } foreach (var column in Table.Columns.Where(x => !x.IsPrimaryKey && (!x.IsForeignKey || !appPrefs.IncludeForeignKeys))) { var mapFromDbType = mapper.MapFromDBType(this.appPrefs.ServerType, column.DataType, column.DataLength, column.DataPrecision, column.DataScale); var fieldName = Formatter.FormatText(column.Name); newType.Members.Add(codeGenerationHelper.CreateField(mapFromDbType, fieldName, column.IsNullable)); } }
private static void AssertMappedTypes(ServerType serverType, DataTypeMapper mapper, Type expectedType, params string[] dataTypes) { foreach (string dataType in dataTypes) { Assert.AreEqual(expectedType, mapper.MapFromDBType(serverType, dataType, null, null, null)); } }
private void CreateAutoProperties(CodeGenerationHelper codeGenerationHelper, DataTypeMapper mapper, CodeTypeDeclaration newType) { if (Table.PrimaryKey != null) { foreach (var pk in Table.PrimaryKey.Columns) { if (pk.IsForeignKey && appPrefs.IncludeForeignKeys) { newType.Members.Add(codeGenerationHelper.CreateAutoProperty(Formatter.FormatSingular(pk.ForeignKeyTableName), Formatter.FormatSingular(pk.ForeignKeyTableName), appPrefs.UseLazy)); } else { var mapFromDbType = mapper.MapFromDBType(this.appPrefs.ServerType, pk.DataType, pk.DataLength, pk.DataPrecision, pk.DataScale); var fieldName = FixPropertyWithSameClassName(pk.Name, Table.Name); var pkAlsoFkQty = (from fk in Table.ForeignKeys.Where(fk => fk.UniquePropertyName == pk.Name) select fk).Count(); if (pkAlsoFkQty > 0) { fieldName = fieldName + "Id"; } newType.Members.Add(codeGenerationHelper.CreateAutoProperty(mapFromDbType.ToString(), Formatter.FormatText(fieldName), appPrefs.UseLazy)); } } } if (appPrefs.IncludeForeignKeys) { var pascalCaseTextFormatter = new PascalCaseTextFormatter { PrefixRemovalList = appPrefs.FieldPrefixRemovalList }; // Note that a foreign key referencing a primary within the same table will end up giving you a foreign key property with the same name as the table. string lastOne = null; foreach (var fk in Table.Columns.Where(c => c.IsForeignKey && !c.IsPrimaryKey)) { var typeName = appPrefs.ClassNamePrefix + pascalCaseTextFormatter.FormatSingular(fk.ForeignKeyTableName); var propertyName = Formatter.FormatSingular(fk.ForeignKeyTableName); var fieldName = FixPropertyWithSameClassName(propertyName, Table.Name); if (lastOne != fieldName) { newType.Members.Add(codeGenerationHelper.CreateAutoProperty(typeName, fieldName, appPrefs.UseLazy)); } lastOne = fieldName; } } foreach (var column in Table.Columns.Where(x => !x.IsPrimaryKey && (!x.IsForeignKey || !appPrefs.IncludeForeignKeys))) { var mapFromDbType = mapper.MapFromDBType(this.appPrefs.ServerType, column.DataType, column.DataLength, column.DataPrecision, column.DataScale); var fieldName = FixPropertyWithSameClassName(column.Name, Table.Name); var property = codeGenerationHelper.CreateAutoProperty(mapFromDbType, Formatter.FormatText(fieldName), column.IsNullable, appPrefs.UseLazy); AttachValidatorAttributes(ref property, column); newType.Members.Add(property); } }
public CodeCompileUnit GetCompileUnit(string className) { var codeGenerationHelper = new CodeGenerationHelper(); var compileUnit = codeGenerationHelper.GetCodeCompileUnitWithInheritanceAndInterface(nameSpace, className, appPrefs.InheritenceAndInterfaces); var mapper = new DataTypeMapper(); var newType = compileUnit.Namespaces[0].Types[0]; newType.IsPartial = appPrefs.GeneratePartialClasses; CreateProperties(codeGenerationHelper, mapper, newType); // Generate GetHashCode() and Equals() methods. if (Table.PrimaryKey != null && Table.PrimaryKey.Columns.Count != 0 && Table.PrimaryKey.Type == PrimaryKeyType.CompositeKey) { var pkColsList = Table.PrimaryKey.Columns.Select(s => Formatter.FormatText(s.Name)).ToList(); var equalsCode = CreateCompositeKeyEqualsMethod(pkColsList); var getHashKeyCode = CreateCompositeKeyGetHashKeyMethod(pkColsList); equalsCode.StartDirectives.Add(new CodeRegionDirective(CodeRegionMode.Start, "NHibernate Composite Key Requirements")); newType.Members.Add(equalsCode); newType.Members.Add(getHashKeyCode); getHashKeyCode.EndDirectives.Add(new CodeRegionDirective(CodeRegionMode.End, string.Empty)); } // Dont create a constructor if there are no relationships. if (Table.HasManyRelationships.Count == 0) { return(compileUnit); } var pascalCaseTextFormatter = new PascalCaseTextFormatter { PrefixRemovalList = appPrefs.FieldPrefixRemovalList }; var constructorStatements = new CodeStatementCollection(); foreach (var hasMany in Table.HasManyRelationships) { if (appPrefs.Language == Language.CSharp) { newType.Members.Add(codeGenerationHelper.CreateAutoProperty(string.Format("{0}<{1}{2}>", appPrefs.ForeignEntityCollectionType, appPrefs.ClassNamePrefix, pascalCaseTextFormatter.FormatSingular(hasMany.Reference)), Formatter.FormatPlural(hasMany.Reference), appPrefs.UseLazy)); constructorStatements.Add(new CodeSnippetStatement(string.Format(TABS + "{0} = new {1}<{2}{3}>();", Formatter.FormatPlural(hasMany.Reference), codeGenerationHelper.InstatiationObject(appPrefs.ForeignEntityCollectionType), appPrefs.ClassNamePrefix, pascalCaseTextFormatter.FormatSingular(hasMany.Reference)))); } else if (appPrefs.Language == Language.VB) { newType.Members.Add(codeGenerationHelper.CreateAutoProperty(string.Format("{0}(Of {1}{2})", appPrefs.ForeignEntityCollectionType, appPrefs.ClassNamePrefix, pascalCaseTextFormatter.FormatSingular(hasMany.Reference)), Formatter.FormatPlural(hasMany.Reference), appPrefs.UseLazy)); constructorStatements.Add(new CodeSnippetStatement(string.Format(TABS + "{0} = New {1}(Of {2}{3})()", Formatter.FormatPlural(hasMany.Reference), codeGenerationHelper.InstatiationObject(appPrefs.ForeignEntityCollectionType), appPrefs.ClassNamePrefix, pascalCaseTextFormatter.FormatSingular(hasMany.Reference)))); } } var constructor = new CodeConstructor { Attributes = MemberAttributes.Public }; constructor.Statements.AddRange(constructorStatements); newType.Members.Add(constructor); return(compileUnit); }
public void Can_Map_PropertyEditorAlias_Property() { // Act string column = new DataTypeMapper().Map(new SqlCeSyntaxProvider(), "EditorAlias"); // Assert Assert.That(column, Is.EqualTo($"[{Constants.DatabaseSchema.Tables.DataType}].[propertyEditorAlias]")); }
public void Can_Map_Key_Property() { // Act string column = new DataTypeMapper().Map(new SqlCeSyntaxProvider(), "Key"); // Assert Assert.That(column, Is.EqualTo("[umbracoNode].[uniqueId]")); }
public void Can_Map_Key_Property() { // Act var column = new DataTypeMapper(TestHelper.GetMockSqlContext(), TestHelper.CreateMaps()).Map("Key"); // Assert Assert.That(column, Is.EqualTo("[umbracoNode].[uniqueId]")); }
public void Can_Map_PropertyEditorAlias_Property() { // Act var column = new DataTypeMapper(TestHelper.GetMockSqlContext(), TestHelper.CreateMaps()).Map("EditorAlias"); // Assert Assert.That(column, Is.EqualTo($"[{Constants.DatabaseSchema.Tables.DataType}].[propertyEditorAlias]")); }
private static CodeSnippetStatement GetIdMapCodeSnippetStatement(ApplicationPreferences appPrefs, string pkColumnName, string pkColumnType, ITextFormatter formatter) { var dataTypeMapper = new DataTypeMapper(); bool isPkTypeIntegral = (dataTypeMapper.MapFromDBType(appPrefs.ServerType, pkColumnType, null, null, null)).IsTypeIntegral(); string idGeneratorType = (isPkTypeIntegral ? "GeneratedBy.Identity()" : "GeneratedBy.Assigned()"); return(new CodeSnippetStatement(string.Format(TABS + "Id(x => x.{0}).{1}.Column(\"{2}\");", formatter.FormatText(pkColumnName), idGeneratorType, pkColumnName))); }
public void Can_Map_Id_Property() { // Act string column = new DataTypeMapper(MockSqlContext(), CreateMaps()).Map("Id"); // Assert Assert.That(column, Is.EqualTo("[umbracoNode].[id]")); }
public void Can_Map_DatabaseType_Property() { // Act string column = new DataTypeMapper(MockSqlContext(), CreateMaps()).Map("DatabaseType"); // Assert Assert.That(column, Is.EqualTo($"[{Constants.DatabaseSchema.Tables.DataType}].[dbType]")); }
public ColumnDetail(string columnName, string dataType, int dataLength, int dataPrecision, int dataScale, bool isNullable) { DataLength = dataLength; DataPrecision = dataPrecision; DataScale = dataScale; ColumnName = columnName; DataType = dataType; IsNullable = isNullable; MappedType = new DataTypeMapper().MapFromDBType(DataType, DataLength, DataPrecision, DataScale).Name; }
public ColumnDetail(string columnName, string dataType, int?dataLength, int?dataPrecision, int dataPrecisionRadix, int?dataScale, bool isNullable) { DataLength = dataLength; DataPrecision = dataPrecision; DataPrecisionRadix = dataPrecisionRadix; DataScale = dataScale; ColumnName = columnName; DataType = dataType; IsNullable = isNullable; MappedType = new DataTypeMapper().MapFromDBType(ServerType.SqlServer, DataType, DataLength, DataPrecision, DataScale).Name; }
public CodeCompileUnit GetCompileUnit(string className) { var codeGenerationHelper = new CodeGenerationHelper(); var compileUnit = codeGenerationHelper.GetCodeCompileUnitWithInheritanceAndInterface(nameSpace, className, appPrefs.InheritenceAndInterfaces); var mapper = new DataTypeMapper(); var newType = compileUnit.Namespaces[0].Types[0]; newType.IsPartial = appPrefs.GeneratePartialClasses; CreateProperties(codeGenerationHelper, mapper, newType); // Generate GetHashCode() and Equals() methods. if (Table.PrimaryKey != null && Table.PrimaryKey.Columns.Count != 0 && Table.PrimaryKey.Type == PrimaryKeyType.CompositeKey) { var pkColsList = Table.PrimaryKey.Columns.Select(s => Formatter.FormatText(s.Name)).ToList(); var equalsCode = CreateCompositeKeyEqualsMethod(pkColsList); var getHashKeyCode = CreateCompositeKeyGetHashKeyMethod(pkColsList); equalsCode.StartDirectives.Add(new CodeRegionDirective(CodeRegionMode.Start, "NHibernate Composite Key Requirements")); newType.Members.Add(equalsCode); newType.Members.Add(getHashKeyCode); getHashKeyCode.EndDirectives.Add(new CodeRegionDirective(CodeRegionMode.End, string.Empty)); } // Dont create a constructor if there are no relationships. if (Table.HasManyRelationships.Count == 0) return compileUnit; var pascalCaseTextFormatter = new PascalCaseTextFormatter { PrefixRemovalList = appPrefs.FieldPrefixRemovalList }; var constructorStatements = new CodeStatementCollection(); foreach (var hasMany in Table.HasManyRelationships) { if (appPrefs.Language == Language.CSharp) { newType.Members.Add(codeGenerationHelper.CreateAutoProperty(string.Format("{0}<{1}{2}>", appPrefs.ForeignEntityCollectionType, appPrefs.ClassNamePrefix, pascalCaseTextFormatter.FormatSingular(hasMany.Reference)), Formatter.FormatPlural(hasMany.Reference), appPrefs.UseLazy)); constructorStatements.Add(new CodeSnippetStatement(string.Format(TABS + "{0} = new {1}<{2}{3}>();", Formatter.FormatPlural(hasMany.Reference), codeGenerationHelper.InstatiationObject(appPrefs.ForeignEntityCollectionType), appPrefs.ClassNamePrefix, pascalCaseTextFormatter.FormatSingular(hasMany.Reference)))); } else if (appPrefs.Language == Language.VB) { newType.Members.Add(codeGenerationHelper.CreateAutoProperty(string.Format("{0}(Of {1}{2})", appPrefs.ForeignEntityCollectionType, appPrefs.ClassNamePrefix, pascalCaseTextFormatter.FormatSingular(hasMany.Reference)), Formatter.FormatPlural(hasMany.Reference), appPrefs.UseLazy)); constructorStatements.Add(new CodeSnippetStatement(string.Format(TABS + "{0} = New {1}(Of {2}{3})()", Formatter.FormatPlural(hasMany.Reference), codeGenerationHelper.InstatiationObject(appPrefs.ForeignEntityCollectionType), appPrefs.ClassNamePrefix, pascalCaseTextFormatter.FormatSingular(hasMany.Reference)))); } } var constructor = new CodeConstructor { Attributes = MemberAttributes.Public }; constructor.Statements.AddRange(constructorStatements); newType.Members.Add(constructor); return compileUnit; }
public CodeCompileUnit GetCompileUnit() { var codeGenerationHelper = new CodeGenerationHelper(); // This is where we construct the constructor var compileUnit = codeGenerationHelper.GetCodeCompileUnit(nameSpace, Table.Name.GetFormattedText().MakeSingular(), true); var mapper = new DataTypeMapper(); var newType = compileUnit.Namespaces[0].Types[0]; newType.IsPartial = applicationPreferences.GeneratePartialClasses; if (Table.PrimaryKey != null && Table.PrimaryKey.Columns.Count() != 0) { foreach (var pk in Table.PrimaryKey.Columns) { var mapFromDbType = mapper.MapFromDBType(this.applicationPreferences.ServerType, pk.DataType, pk.DataLength, pk.DataPrecision, pk.DataScale); var declaration = new CodeAttributeDeclaration("PrimaryKey"); declaration.Arguments.Add(new CodeAttributeArgument("Column", new CodePrimitiveExpression(pk.Name))); newType.Members.Add(codeGenerationHelper.CreateAutoProperty(mapFromDbType.ToString(), pk.Name.GetFormattedText(), declaration)); } } foreach (var fk in Table.ForeignKeys) { newType.Members.Add(codeGenerationHelper.CreateAutoProperty(fk.References.GetFormattedText().MakeSingular(), fk.References.GetFormattedText().MakeSingular())); } foreach (var property in Table.Columns.Where(x => x.IsPrimaryKey != true && x.IsForeignKey != true)) { var declaration = new CodeAttributeDeclaration("Property"); declaration.Arguments.Add(new CodeAttributeArgument("Column", new CodePrimitiveExpression(property.Name))); if (property.DataLength.HasValue) { declaration.Arguments.Add(new CodeAttributeArgument("Length", new CodePrimitiveExpression(property.DataLength))); } if (!property.IsNullable) { declaration.Arguments.Add(new CodeAttributeArgument("NotNull", new CodePrimitiveExpression(true))); } var mapFromDbType = mapper.MapFromDBType(this.applicationPreferences.ServerType, property.DataType, property.DataLength, property.DataPrecision, property.DataScale); newType.Members.Add(codeGenerationHelper.CreateAutoProperty(mapFromDbType.ToString(), property.Name.GetFormattedText(), declaration)); } return(compileUnit); }
protected override IList<Column> GetTablesDetails(Table table, string owner) { var columns = new List<Column>(); using (var sqlCon = new SQLiteConnection(_connectionString)) { try { using (var tableDetailsCommand = sqlCon.CreateCommand()) { tableDetailsCommand.CommandText = string.Format("SELECT * FROM {0}", table.Name); sqlCon.Open(); var dr = tableDetailsCommand.ExecuteReader(CommandBehavior.SchemaOnly); var dt = dr.GetSchemaTable(); var m = new DataTypeMapper(); foreach (DataRow row in dt.Rows) { bool isPrimaryKey = (bool)row["IsKey"]; columns.Add( new Column(table) { Name = row["ColumnName"].ToString(), IsNullable = (bool)row["AllowDBNull"], IsPrimaryKey = (bool)row["IsKey"], MappedDataType = m.MapFromDBType(DatabaseServerType.SQLite, row["DataTypeName"].ToString(), (int)row["ColumnSize"], null, null, isPrimaryKey), DataLength = (int)row["ColumnSize"], DataType = row["DataTypeName"].ToString(), IsUnique = (bool)row["IsUnique"] }); dr.Close(); } } table.OwnerSchema = owner; table.Columns = columns; table.PrimaryKey = DeterminePrimaryKeys(table); table.ForeignKeys = new List<ForeignKey>();// DetermineForeignKeyReferences(table); table.HasManyRelationships = new List<HasMany>();// DetermineHasManyRelationships(table); } finally { sqlCon.Close(); } } return columns; }
private static CodeSnippetStatement GetIdMapCodeSnippetStatement(IApplicationSettings appPrefs, Table table, string pkColumnName, string propertyName, string pkColumnType, ITextFormatter formatter) { var dataTypeMapper = new DataTypeMapper(); bool isPkTypeIntegral = (dataTypeMapper.MapFromDBType(appPrefs.ServerType, pkColumnType, null, null, null)).IsTypeIntegral(); string idGeneratorType = (isPkTypeIntegral ? "GeneratedBy.Identity()" : "GeneratedBy.Assigned()"); var fieldName = FixPropertyWithSameClassName(propertyName, table.Name); var pkAlsoFkQty = (from fk in table.ForeignKeys.Where(fk => fk.UniquePropertyName == pkColumnName) select fk).Count(); if (pkAlsoFkQty > 0) { fieldName = fieldName + "Id"; } return(new CodeSnippetStatement(string.Format(TABS + "Id(x => x.{0}).{1}.Column(\"{2}\");", formatter.FormatText(fieldName), idGeneratorType, pkColumnName))); }
public CodeCompileUnit GetCompileUnit() { var codeGenerationHelper = new CodeGenerationHelper(); // This is where we construct the constructor var compileUnit = codeGenerationHelper.GetCodeCompileUnit(nameSpace, Table.Name.GetFormattedText().MakeSingular(),true); var mapper = new DataTypeMapper(); var newType = compileUnit.Namespaces[0].Types[0]; newType.IsPartial = applicationPreferences.GeneratePartialClasses; if (Table.PrimaryKey != null && Table.PrimaryKey.Columns.Count() != 0) { foreach (var pk in Table.PrimaryKey.Columns) { var mapFromDbType = mapper.MapFromDBType(this.applicationPreferences.ServerType, pk.DataType, pk.DataLength, pk.DataPrecision, pk.DataScale); var declaration = new CodeAttributeDeclaration("PrimaryKey"); declaration.Arguments.Add(new CodeAttributeArgument("Column", new CodePrimitiveExpression(pk.Name))); newType.Members.Add(codeGenerationHelper.CreateAutoProperty(mapFromDbType.ToString(), pk.Name.GetFormattedText(), declaration)); } } foreach (var fk in Table.ForeignKeys) { newType.Members.Add(codeGenerationHelper.CreateAutoProperty(fk.References.GetFormattedText().MakeSingular(), fk.References.GetFormattedText().MakeSingular())); } foreach (var property in Table.Columns.Where(x => x.IsPrimaryKey != true && x.IsForeignKey != true)) { var declaration = new CodeAttributeDeclaration("Property"); declaration.Arguments.Add(new CodeAttributeArgument("Column", new CodePrimitiveExpression(property.Name))); if(property.DataLength.HasValue) declaration.Arguments.Add(new CodeAttributeArgument("Length", new CodePrimitiveExpression(property.DataLength))); if (!property.IsNullable) { declaration.Arguments.Add(new CodeAttributeArgument("NotNull", new CodePrimitiveExpression(true))); } var mapFromDbType = mapper.MapFromDBType(this.applicationPreferences.ServerType, property.DataType, property.DataLength, property.DataPrecision, property.DataScale); newType.Members.Add(codeGenerationHelper.CreateAutoProperty(mapFromDbType.ToString(), property.Name.GetFormattedText(), declaration)); } return compileUnit; }
public IList <Column> GetTableDetails(Table table, string owner) { var columns = new List <Column>(); using (var sqlCon = new SQLiteConnection(_connectionStr)) { try { using (var tableDetailsCommand = sqlCon.CreateCommand()) { tableDetailsCommand.CommandText = string.Format("SELECT * FROM {0}", table.Name); sqlCon.Open(); var dr = tableDetailsCommand.ExecuteReader(CommandBehavior.SchemaOnly); var dt = dr.GetSchemaTable(); var m = new DataTypeMapper(); foreach (DataRow row in dt.Rows) { columns.Add( new Column { Name = row["ColumnName"].ToString(), IsNullable = (bool)row["AllowDBNull"], IsPrimaryKey = (bool)row["IsKey"], MappedDataType = m.MapFromDBType(ServerType.SQLite, row["DataTypeName"].ToString(), (int)row["ColumnSize"], null, null).ToString(), DataLength = (int)row["ColumnSize"], DataType = row["DataTypeName"].ToString(), IsUnique = (bool)row["IsUnique"] }); dr.Close(); } } table.Owner = owner; table.Columns = columns; table.PrimaryKey = DeterminePrimaryKeys(table); table.ForeignKeys = new List <ForeignKey>(); // DetermineForeignKeyReferences(table); table.HasManyRelationships = new List <HasMany>(); // DetermineHasManyRelationships(table); } finally { sqlCon.Close(); } } return(columns); }
public CodeCompileUnit GetCompileUnit(string className) { var codeGenerationHelper = new CodeGenerationHelper(); var compileUnit = codeGenerationHelper.GetCodeCompileUnit(nameSpace, className); var mapper = new DataTypeMapper(); var newType = compileUnit.Namespaces[0].Types[0]; var nameArgument = new CodeAttributeArgument("Name", new CodeSnippetExpression("\"" + className + "\" ")); var nameSpaceArgument = new CodeAttributeArgument("Namespace", new CodeSnippetExpression("\"\"")); newType.CustomAttributes = new CodeAttributeDeclarationCollection { new CodeAttributeDeclaration("DataContract", nameArgument, nameSpaceArgument) }; foreach (var column in table.Columns) { if (column.IsPrimaryKey) { if (appPrefs.IncludeHasMany) { foreach (var foreignKeyTable in table.HasManyRelationships) { var fkEntityName = appPrefs.ClassNamePrefix + foreignKeyTable.Reference.MakeSingular().GetPreferenceFormattedText(appPrefs); newType.Members.Add(codeGenerationHelper.CreateAutoPropertyWithDataMemberAttribute("IList<" + fkEntityName + ">", foreignKeyTable.Reference.MakePlural().GetPreferenceFormattedText(appPrefs))); } } var primaryKeyType = mapper.MapFromDBType(this.appPrefs.ServerType, column.DataType, column.DataLength, column.DataPrecision, column.DataScale); newType.Members.Add(codeGenerationHelper.CreateAutoPropertyWithDataMemberAttribute(primaryKeyType.Name, "Id")); continue; } if (column.IsForeignKey) { var fKey = column.ForeignKeyTableName; var typeName = appPrefs.ClassNamePrefix + fKey.MakeSingular().GetPreferenceFormattedText(appPrefs); var codeMemberProperty = codeGenerationHelper.CreateAutoPropertyWithDataMemberAttribute(typeName, fKey.MakeSingular().GetPreferenceFormattedText(appPrefs)); newType.Members.Add(codeMemberProperty); continue; } var propertyName = column.Name.GetPreferenceFormattedText(appPrefs); var mapFromDbType = mapper.MapFromDBType(this.appPrefs.ServerType, column.DataType, column.DataLength, column.DataPrecision, column.DataScale); newType.Members.Add(codeGenerationHelper.CreateAutoPropertyWithDataMemberAttribute(mapFromDbType.Name, propertyName)); } return(compileUnit); }
private void CreateProperties(CodeGenerationHelper codeGenerationHelper, DataTypeMapper mapper, CodeTypeDeclaration newType) { switch (appPrefs.FieldGenerationConvention) { case FieldGenerationConvention.Field: CreateFields(codeGenerationHelper, mapper, newType); break; case FieldGenerationConvention.Property: CreateFullProperties(codeGenerationHelper, mapper, newType); break; case FieldGenerationConvention.AutoProperty: CreateAutoProperties(codeGenerationHelper, mapper, newType); break; } }
public void OracleMap() { var mapper = new DataTypeMapper(); AssertMappedTypes(ServerType.Oracle, mapper, typeof(System.DateTime), "DATE", "TIMESTAMP", "TIMESTAMP WITH TIME ZONE", "TIMESTAMP WITH LOCAL TIME ZONE"); AssertMappedTypes(ServerType.Oracle, mapper, typeof(System.Int64), "LONG", "INTERVAL YEAR TO MONTH"); AssertMappedTypes(ServerType.Oracle, mapper, typeof(byte[]), "BLOB", "BFILE *", "LONG RAW"); AssertMappedTypes(ServerType.Oracle, mapper, typeof(System.Double), "BINARY_DOUBLE"); AssertMappedTypes(ServerType.Oracle, mapper, typeof(System.Single), "BINARY_FLOAT"); AssertMappedTypes(ServerType.Oracle, mapper, typeof(System.Decimal), "REAL", "FLOAT", "BINARY_INTEGER"); Assert.AreEqual(typeof(TimeSpan), mapper.MapFromDBType(ServerType.Oracle, "INTERVAL DAY TO SECOND", null, null, null)); Assert.AreEqual(typeof(Int32), mapper.MapFromDBType(ServerType.Oracle, "NUMBER", null, 9, 0)); Assert.AreEqual(typeof(Int64), mapper.MapFromDBType(ServerType.Oracle, "NUMBER", null, 14, 0)); Assert.AreEqual(typeof(Double), mapper.MapFromDBType(ServerType.Oracle, "NUMBER", null, 11, 6)); Assert.AreEqual(typeof(Decimal), mapper.MapFromDBType(ServerType.Oracle, "NUMBER", null, 24, 10)); }
public void Map() { var mapper = new DataTypeMapper(); AssertMappedTypes(ServerType.SqlServer, mapper, typeof(int), "int"); AssertMappedTypes(ServerType.SqlServer, mapper, typeof(DateTime), "datetime", "smalldatetime", "timestamp"); AssertMappedTypes(ServerType.SqlServer, mapper, typeof(long), "bigint"); AssertMappedTypes(ServerType.SqlServer, mapper, typeof(string), "nchar"); AssertMappedTypes(ServerType.SqlServer, mapper, typeof(float), "float"); AssertMappedTypes(ServerType.SqlServer, mapper, typeof(decimal), "decimal", "money", "smallmoney"); AssertMappedTypes(ServerType.SqlServer, mapper, typeof(byte[]), "binary", "varbinary", "image"); Assert.AreEqual(typeof(Boolean), mapper.MapFromDBType(ServerType.SqlServer, "bit", null, null, null)); Assert.AreEqual(typeof(Single), mapper.MapFromDBType(ServerType.SqlServer, "real", null, null, null)); Assert.AreEqual(typeof(Int16), mapper.MapFromDBType(ServerType.SqlServer, "smallint", null, null, null)); Assert.AreEqual(typeof(Guid), mapper.MapFromDBType(ServerType.SqlServer, "uniqueidentifier", null, null, null)); Assert.AreEqual(typeof(Byte), mapper.MapFromDBType(ServerType.SqlServer, "tinyint", null, null, null)); }
public CodeCompileUnit GetCompileUnit(string className) { var codeGenerationHelper = new CodeGenerationHelper(); var compileUnit = codeGenerationHelper.GetCodeCompileUnit(nameSpace, className); var mapper = new DataTypeMapper(); var newType = compileUnit.Namespaces[0].Types[0]; var nameArgument = new CodeAttributeArgument("Name", new CodeSnippetExpression("\"" + className + "\" ")); var nameSpaceArgument = new CodeAttributeArgument("Namespace", new CodeSnippetExpression("\"\"")); newType.CustomAttributes = new CodeAttributeDeclarationCollection {new CodeAttributeDeclaration("DataContract", nameArgument, nameSpaceArgument)}; foreach (var column in table.Columns) { if(column.IsPrimaryKey) { if(appPrefs.IncludeHasMany) foreach (var foreignKeyTable in table.HasManyRelationships) { var fkEntityName = appPrefs.ClassNamePrefix + foreignKeyTable.Reference.MakeSingular().GetPreferenceFormattedText(appPrefs); newType.Members.Add(codeGenerationHelper.CreateAutoPropertyWithDataMemberAttribute("IList<" + fkEntityName + ">", foreignKeyTable.Reference.MakePlural().GetPreferenceFormattedText(appPrefs))); } var primaryKeyType = mapper.MapFromDBType(this.appPrefs.ServerType, column.DataType, column.DataLength, column.DataPrecision, column.DataScale); newType.Members.Add(codeGenerationHelper.CreateAutoPropertyWithDataMemberAttribute(primaryKeyType.Name, "Id")); continue; } if (column.IsForeignKey) { var fKey = column.ForeignKeyTableName; var typeName = appPrefs.ClassNamePrefix + fKey.MakeSingular().GetPreferenceFormattedText(appPrefs); var codeMemberProperty = codeGenerationHelper.CreateAutoPropertyWithDataMemberAttribute(typeName, fKey.MakeSingular().GetPreferenceFormattedText(appPrefs)); newType.Members.Add(codeMemberProperty); continue; } var propertyName = column.Name.GetPreferenceFormattedText(appPrefs); var mapFromDbType = mapper.MapFromDBType(this.appPrefs.ServerType, column.DataType, column.DataLength, column.DataPrecision, column.DataScale); newType.Members.Add(codeGenerationHelper.CreateAutoPropertyWithDataMemberAttribute(mapFromDbType.Name, propertyName)); } return compileUnit; }
private void CreateFullProperties(CodeGenerationHelper codeGenerationHelper, DataTypeMapper mapper, CodeTypeDeclaration newType) { var camelCaseFormatter = new CamelCaseTextFormatter(); if (Table.PrimaryKey != null) { foreach (var pk in Table.PrimaryKey.Columns) { var mapFromDbType = mapper.MapFromDBType(this.appPrefs.ServerType, pk.DataType, pk.DataLength, pk.DataPrecision, pk.DataScale); newType.Members.Add(codeGenerationHelper.CreateField(mapFromDbType, "_" + camelCaseFormatter.FormatText(pk.Name), true)); newType.Members.Add(codeGenerationHelper.CreateProperty(mapFromDbType, Formatter.FormatText(pk.Name), appPrefs.UseLazy)); } } if (appPrefs.IncludeForeignKeys) { var pascalCaseTextFormatter = new PascalCaseTextFormatter { PrefixRemovalList = appPrefs.FieldPrefixRemovalList }; // Note that a foreign key referencing a primary within the same table will end up giving you a foreign key property with the same name as the table. foreach (var fk in Table.ForeignKeys.Where(fk => !string.IsNullOrEmpty(fk.References))) { var typeName = appPrefs.ClassNamePrefix + pascalCaseTextFormatter.FormatSingular(fk.References); newType.Members.Add(codeGenerationHelper.CreateField(typeName, string.Format("_{0}", camelCaseFormatter.FormatSingular(fk.UniquePropertyName)))); newType.Members.Add(codeGenerationHelper.CreateProperty(typeName, Formatter.FormatSingular(fk.UniquePropertyName), appPrefs.UseLazy)); } } foreach (var column in Table.Columns.Where(x => !x.IsPrimaryKey && (!x.IsForeignKey || !appPrefs.IncludeForeignKeys))) { var mapFromDbType = mapper.MapFromDBType(this.appPrefs.ServerType, column.DataType, column.DataLength, column.DataPrecision, column.DataScale); newType.Members.Add(codeGenerationHelper.CreateField(mapFromDbType, "_" + camelCaseFormatter.FormatText(column.Name), column.IsNullable)); var property = codeGenerationHelper.CreateProperty(mapFromDbType, Formatter.FormatText(column.Name), column.IsNullable, appPrefs.UseLazy); AttachValidatorAttributes(ref property, column); newType.Members.Add(property); } }
/// <summary> /// Creates text for the whole class /// </summary> /// <param name="dt"></param> /// <param name="nameSpace"></param> /// <returns></returns> public static string CreateClass(DataTable dt, string nameSpace) { StringBuilder textForClassCreation = new StringBuilder(); if (dt != null) { textForClassCreation.Append("using ADOCRUD.Attributes;" + Environment.NewLine); textForClassCreation.Append("using System;" + Environment.NewLine); textForClassCreation.Append("using System.Collections.Generic;" + Environment.NewLine); textForClassCreation.Append("using System.Linq;" + Environment.NewLine); textForClassCreation.Append("using System.Text;" + Environment.NewLine); textForClassCreation.Append("using System.Threading.Tasks;" + Environment.NewLine + Environment.NewLine); textForClassCreation.Append("namespace " + nameSpace + Environment.NewLine); textForClassCreation.Append("{" + Environment.NewLine); textForClassCreation.Append("[Table(\"".PadLeft(12, ' ') + dt.TableName + "\", \"" + dt.Prefix + "\")]" + Environment.NewLine); textForClassCreation.Append(("public class " + dt.TableName).PadLeft(+dt.TableName.Length + 17, ' ') + Environment.NewLine); textForClassCreation.Append("{".PadLeft(5, ' ') + Environment.NewLine); foreach (DataColumn column in dt.Columns) { if (dt.PrimaryKey.Contains(column)) { textForClassCreation.Append("[PrimaryKey]".PadLeft(20, ' ') + Environment.NewLine); } textForClassCreation.Append("[Member]".PadLeft(16, ' ') + Environment.NewLine); Type t = column.DataType; SqlDbType dbType = new SqlDbType(); DataTypeMapper.DataTypes().TryGetValue(column.DataType, out dbType); string propertyLine = CreateProperty(dbType, column.AllowDBNull, column.ColumnName); textForClassCreation.Append(propertyLine.PadLeft(propertyLine.Length + 8, ' ') + Environment.NewLine + Environment.NewLine); } textForClassCreation.Append("}".PadLeft(5, ' ') + Environment.NewLine); textForClassCreation.Append("}"); } return(textForClassCreation.ToString()); }
private static CodeSnippetStatement GetIdMapCodeSnippetStatement(ApplicationPreferences appPrefs, Table table, string pkColumnName, string propertyName, string pkColumnType, ITextFormatter formatter) { var dataTypeMapper = new DataTypeMapper(); bool isPkTypeIntegral = (dataTypeMapper.MapFromDBType(appPrefs.ServerType, pkColumnType, null, null, null)).IsTypeIntegral(); string fieldName = FixPropertyWithSameClassName(propertyName, table.Name); int pkAlsoFkQty = (from fk in table.ForeignKeys.Where(fk => fk.UniquePropertyName == pkColumnName) select fk).Count(); if (pkAlsoFkQty > 0) { fieldName = fieldName + "Id"; } string snippet = TABS + $".Property(x => x.{formatter.FormatText(fieldName)}).IsPrimaryKey()"; if (isPkTypeIntegral) { snippet += Environment.NewLine + TABS + $".Property(x => x.{formatter.FormatText(fieldName)}).IsIdentity()"; } return(new CodeSnippetStatement(snippet)); }
public IList<Column> GetTableDetails(Table table, string owner) { var columns = new List<Column>(); var conn = new NpgsqlConnection(connectionStr); conn.Open(); using (conn) { using (NpgsqlCommand tableDetailsCommand = conn.CreateCommand()) { tableDetailsCommand.CommandText = string.Format(@"select c.column_name ,c.data_type ,c.is_nullable ,b.constraint_type as type from information_schema.constraint_column_usage a inner join information_schema.table_constraints b on a.constraint_name=b.constraint_name inner join information_schema.columns c on a.column_name=c.column_name and a.table_name=c.table_name where a.table_schema='{1}' and a.table_name='{0}' and b.constraint_type in ('PRIMARY KEY') union select a.column_name ,a.data_type ,a.is_nullable ,b.constraint_type as type from information_schema.columns a inner join information_schema.table_constraints b on b.constraint_name ='{0}_'||a.column_name||'_fkey' union select a.column_name ,a.data_type ,a.is_nullable ,'' from information_schema.columns a where a.table_schema='{1}' and a.table_name='{0}' and a.column_name not in ( select c.column_name from information_schema.constraint_column_usage a inner join information_schema.table_constraints b on a.constraint_name=b.constraint_name inner join information_schema.columns c on a.column_name=c.column_name and a.table_name=c.table_name where a.table_schema='{1}' and a.table_name='{0}' and b.constraint_type in ('PRIMARY KEY') union select a.column_name from information_schema.columns a inner join information_schema.table_constraints b on b.constraint_name ='{0}_'||a.column_name||'_fkey')", table.Name, owner); using (NpgsqlDataReader sqlDataReader = tableDetailsCommand.ExecuteReader(CommandBehavior.Default)) { while (sqlDataReader.Read()) { string columnName = sqlDataReader.GetString(0); string dataType = sqlDataReader.GetString(1); bool isNullable = sqlDataReader.GetString(2).Equals("YES", StringComparison. CurrentCultureIgnoreCase); bool isPrimaryKey = (!sqlDataReader.IsDBNull(3) ? sqlDataReader.GetString(3).Equals( NpgsqlConstraintType.PrimaryKey.ToString(), StringComparison.CurrentCultureIgnoreCase) : false); bool isForeignKey = (!sqlDataReader.IsDBNull(3) ? sqlDataReader.GetString(3).Equals( NpgsqlConstraintType.ForeignKey.ToString(), StringComparison.CurrentCultureIgnoreCase) : false); var m = new DataTypeMapper(); columns.Add(new Column { Name = columnName, DataType = dataType, IsNullable = isNullable, IsPrimaryKey = isPrimaryKey, //IsPrimaryKey(selectedTableName.Name, columnName) IsForeignKey = isForeignKey, // IsFK() MappedDataType = m.MapFromDBType(ServerType.PostgreSQL, dataType, null, null, null).ToString(), //DataLength = dataLength }); table.Columns = columns; } table.Owner = owner; table.PrimaryKey = DeterminePrimaryKeys(table); // Need to find the table name associated with the FK foreach (var c in table.Columns) { c.ForeignKeyTableName = GetForeignKeyReferenceTableName(table.Name, c.Name); } table.ForeignKeys = DetermineForeignKeyReferences(table); table.HasManyRelationships = DetermineHasManyRelationships(table); } } } return columns; }
public List <Column> GetTableDetails(Table table, string owner) { var columns = new List <Column>(); using (var sqlCon = new OleDbConnection(_connectionStr)) { try { using (var tableDetailsCommand = sqlCon.CreateCommand()) { var sqlText = @"SELECT [default] default_value, c.column_name columnName, d.domain_name DataTypeName, width ColumnSize, scale columnPrecision, convert(bit, CASE WHEN pkey = 'Y' THEN 1 ELSE 0 END) IsKey, convert(bit, CASE WHEN c.[nulls] = 'Y' THEN 1 ELSE 0 END) AllowDBNull, convert(bit, CASE WHEN c.[default] = 'AUTOINCREMENT' THEN 1 ELSE 0 END) IsIdentity, convert(bit, CASE WHEN c.[default] = 'NEWID()' THEN 1 ELSE 0 END) IsGenerated, convert(bit, CASE WHEN fcol.foreign_column_id is null THEN 0 ELSE 1 END) IsForeignKey, ISNULL(fk.[role],'') ConstraintName FROM sys.syscolumn c inner join sys.systable t on t.table_id = c.table_id inner join sys.sysdomain d on c.domain_id = d.domain_id inner join sysobjects o on t.object_id = o.id inner join sys.sysuser u on u.user_id = o.uid left join sysfkcol fcol ON c.table_id = fcol.foreign_table_id and c.column_id = fcol.foreign_column_id left join sysforeignkey fk ON fcol.foreign_table_id = fk.foreign_table_id AND fcol.foreign_key_id = fk.foreign_key_id WHERE t.table_name = '{0}' and u.user_name = '{1}' ORDER BY c.Column_id"; tableDetailsCommand.CommandText = string.Format(sqlText, table.Name, owner); sqlCon.Open(); var dr = tableDetailsCommand.ExecuteReader(CommandBehavior.Default); var m = new DataTypeMapper(); while (dr.Read()) { var name = dr["columnName"].ToString(); var isNullable = (bool)dr["AllowDBNull"]; var isPrimaryKey = dr["IsKey"] as bool?; var isForeignKey = (bool)dr["IsForeignKey"]; var dataType = dr["DataTypeName"].ToString(); var dataLength = Convert.ToInt32(dr["columnSize"]); var dataPrecision = Convert.ToInt32(dr["columnSize"]); var dataScale = Convert.ToInt32(dr["columnPrecision"]); var isIdentity = dr["IsIdentity"] as bool?; var constraintName = dr["ConstraintName"].ToString(); var isUnique = false; //(bool) dr["IsKey"]; var mappedType = m.MapFromDBType(ServerType.Sybase, dataType, dataLength, dataPrecision, dataScale); if (DataTypeMapper.IsNumericType(mappedType)) { dataLength = 0; } else { dataScale = 0; dataPrecision = 0; } columns.Add( new Column { Name = name, IsNullable = isNullable, IsPrimaryKey = isPrimaryKey.GetValueOrDefault(), IsForeignKey = isForeignKey, MappedDataType = mappedType.ToString(), DataLength = dataLength, DataScale = dataScale, DataPrecision = dataPrecision, DataType = dataType, IsUnique = isUnique, IsIdentity = isIdentity.GetValueOrDefault(), ConstraintName = constraintName }); } dr.Close(); } table.Owner = owner; table.Columns = columns; table.PrimaryKey = DeterminePrimaryKeys(table); // Need to find the table name associated with the FK foreach (var c in table.Columns) { c.ForeignKeyTableName = GetForeignKeyReferenceTableName(table.Name, c.Name); } table.ForeignKeys = DetermineForeignKeyReferences(table); table.HasManyRelationships = DetermineHasManyRelationships(table); } catch (Exception ex) { Console.Write(ex.Message); } finally { sqlCon.Close(); } } return(columns); }
public IList <Column> GetTableDetails(Table table, string owner) { var columns = new List <Column>(); var conn = new SqlConnection(connectionStr); conn.Open(); try { using (conn) { using (var tableDetailsCommand = conn.CreateCommand()) { tableDetailsCommand.CommandText = string.Format( @"SELECT distinct c.column_name, c.data_type, c.is_nullable, tc.constraint_type, convert(int,c.numeric_precision) numeric_precision, c.numeric_scale, c.character_maximum_length, c.table_name, c.ordinal_position, tc.constraint_name, columnproperty(object_id(c.table_schema + '.' + c.table_name), c.column_name,'IsIdentity') IsIdentity, (SELECT CASE WHEN count(1) = 0 THEN 0 ELSE 1 END FROM information_schema.table_constraints x INNER JOIN information_schema.constraint_column_usage ccux ON c.table_name = ccux.table_name and c.column_name = ccux.column_name and c.table_schema = ccux.table_schema WHERE x.constraint_type = 'UNIQUE' and x.table_schema = ccux.table_schema and x.constraint_name = ccux.constraint_name) IsUnique from information_schema.columns c left outer join ( information_schema.constraint_column_usage ccu join information_schema.table_constraints tc on ( tc.table_schema = ccu.table_schema and tc.constraint_name = ccu.constraint_name and NOT tc.constraint_type IN ('CHECK','UNIQUE') ) ) on ( c.table_schema = ccu.table_schema and c.table_name = ccu.table_name and c.column_name = ccu.column_name ) where c.table_name = '{0}' and c.table_schema ='{1}' order by c.table_name, c.ordinal_position" , table.Name.Replace("'", "''"), owner); using (var sqlDataReader = tableDetailsCommand.ExecuteReader(CommandBehavior.Default)) { while (sqlDataReader.Read()) { string columnName = sqlDataReader.GetString(0); string dataType = sqlDataReader.GetString(1); bool isNullable = sqlDataReader.GetString(2).Equals("YES", StringComparison.CurrentCultureIgnoreCase); var isIdentity = Convert.ToBoolean(sqlDataReader["IsIdentity"]); var characterMaxLenth = sqlDataReader["character_maximum_length"] as int?; var numericPrecision = sqlDataReader["numeric_precision"] as int?; var numericScale = sqlDataReader["numeric_scale"] as int?; var constraintName = sqlDataReader["constraint_name"].ToString(); var isUnique = Convert.ToBoolean(sqlDataReader["IsUnique"]); bool isPrimaryKey = (!sqlDataReader.IsDBNull(3) && sqlDataReader.GetString(3).Equals(SqlServerConstraintType.PrimaryKey.ToString(), StringComparison.CurrentCultureIgnoreCase)); bool isForeignKey = (!sqlDataReader.IsDBNull(3) && sqlDataReader.GetString(3).Equals(SqlServerConstraintType.ForeignKey.ToString(), StringComparison.CurrentCultureIgnoreCase)); var m = new DataTypeMapper(); columns.Add(new Column { Name = columnName, DataType = dataType, IsNullable = isNullable, IsIdentity = isIdentity, IsPrimaryKey = isPrimaryKey, IsForeignKey = isForeignKey, IsUnique = isUnique, MappedDataType = m.MapFromDBType(ServerType.SqlServer, dataType, characterMaxLenth, numericPrecision, numericScale).ToString(), DataLength = characterMaxLenth, DataScale = numericScale, DataPrecision = numericPrecision, ConstraintName = constraintName }); table.Columns = columns; } table.Owner = owner; table.PrimaryKey = DeterminePrimaryKeys(table); // Need to find the table name associated with the FK foreach (var c in table.Columns) { if (c.IsForeignKey) { string referencedTableName; string referencedColumnName; GetForeignKeyReferenceDetails(c.ConstraintName, out referencedTableName, out referencedColumnName); c.ForeignKeyTableName = referencedTableName; c.ForeignKeyColumnName = referencedColumnName; } } table.ForeignKeys = DetermineForeignKeyReferences(table); table.HasManyRelationships = DetermineHasManyRelationships(table); } } } } finally { conn.Close(); } return(columns); }
private static CodeSnippetStatement GetIdMapCodeSnippetStatement(ApplicationPreferences appPrefs, string pkColumnName, string pkColumnType, ITextFormatter formatter) { var dataTypeMapper = new DataTypeMapper(); bool isPkTypeIntegral = (dataTypeMapper.MapFromDBType(appPrefs.ServerType, pkColumnType, null, null, null)).IsTypeIntegral(); string idGeneratorType = (isPkTypeIntegral ? "GeneratedBy.Identity()" : "GeneratedBy.Assigned()"); return new CodeSnippetStatement(string.Format(TABS + "Id(x => x.{0}).{1}.Column(\"{2}\");", formatter.FormatText(pkColumnName), idGeneratorType, pkColumnName)); }
public IList<Column> GetTableDetails(Table table, string owner) { var columns = new List<Column>(); var conn = new SqlConnection(connectionStr); conn.Open(); try { using (conn) { using (var tableDetailsCommand = conn.CreateCommand()) { tableDetailsCommand.CommandText = string.Format( @"SELECT distinct c.column_name, c.data_type, c.is_nullable, tc.constraint_type, convert(int,c.numeric_precision) numeric_precision, c.numeric_scale, c.character_maximum_length, c.table_name, c.ordinal_position, tc.constraint_name, columnproperty(object_id(c.table_schema + '.' + c.table_name), c.column_name,'IsIdentity') IsIdentity, (SELECT CASE WHEN count(1) = 0 THEN 0 ELSE 1 END FROM information_schema.table_constraints x INNER JOIN information_schema.constraint_column_usage ccux ON c.table_name = ccux.table_name and c.column_name = ccux.column_name and c.table_schema = ccux.table_schema WHERE x.constraint_type = 'UNIQUE' and x.table_schema = ccux.table_schema and x.constraint_name = ccux.constraint_name) IsUnique from information_schema.columns c left outer join ( information_schema.constraint_column_usage ccu join information_schema.table_constraints tc on ( tc.table_schema = ccu.table_schema and tc.constraint_name = ccu.constraint_name and NOT tc.constraint_type IN ('CHECK','UNIQUE') ) ) on ( c.table_schema = ccu.table_schema and c.table_name = ccu.table_name and c.column_name = ccu.column_name ) where c.table_name = '{0}' and c.table_schema ='{1}' order by c.table_name, c.ordinal_position", table.Name.Replace("'", "''"), owner); using (var sqlDataReader = tableDetailsCommand.ExecuteReader(CommandBehavior.Default)) { while (sqlDataReader.Read()) { string columnName = sqlDataReader.GetString(0); string dataType = sqlDataReader.GetString(1); bool isNullable = sqlDataReader.GetString(2).Equals("YES", StringComparison.CurrentCultureIgnoreCase); var isIdentity = Convert.ToBoolean(sqlDataReader["IsIdentity"]); var characterMaxLenth = sqlDataReader["character_maximum_length"] as int?; var numericPrecision = sqlDataReader["numeric_precision"] as int?; var numericScale = sqlDataReader["numeric_scale"] as int?; var constraintName = sqlDataReader["constraint_name"].ToString(); var isUnique = Convert.ToBoolean(sqlDataReader["IsUnique"]); bool isPrimaryKey = (!sqlDataReader.IsDBNull(3) && sqlDataReader.GetString(3).Equals(SqlServerConstraintType.PrimaryKey.ToString(), StringComparison.CurrentCultureIgnoreCase)); bool isForeignKey = (!sqlDataReader.IsDBNull(3) && sqlDataReader.GetString(3).Equals(SqlServerConstraintType.ForeignKey.ToString(), StringComparison.CurrentCultureIgnoreCase)); var m = new DataTypeMapper(); columns.Add(new Column { Name = columnName, DataType = dataType, IsNullable = isNullable, IsIdentity = isIdentity, IsPrimaryKey = isPrimaryKey, IsForeignKey = isForeignKey, IsUnique = isUnique, MappedDataType = m.MapFromDBType(ServerType.SqlServer, dataType, characterMaxLenth, numericPrecision, numericScale).ToString(), DataLength = characterMaxLenth, DataScale = numericScale, DataPrecision = numericPrecision, ConstraintName = constraintName }); table.Columns = columns; } table.Owner = owner; table.PrimaryKey = DeterminePrimaryKeys(table); // Need to find the table name associated with the FK foreach (var c in table.Columns) { if (c.IsForeignKey) { string referencedTableName; string referencedColumnName; GetForeignKeyReferenceDetails(c.ConstraintName, out referencedTableName, out referencedColumnName); c.ForeignKeyTableName = referencedTableName; c.ForeignKeyColumnName = referencedColumnName; } } table.ForeignKeys = DetermineForeignKeyReferences(table); table.HasManyRelationships = DetermineHasManyRelationships(table); } } } } finally { conn.Close(); } return columns; }
public IList<Column> GetTableDetails(Table table, string owner) { var columns = new List<Column>(); var conn = new MySqlConnection(connectionStr); conn.Open(); try { using (conn) { using (MySqlCommand tableDetailsCommand = conn.CreateCommand()) { tableDetailsCommand.CommandText = string.Format(@"DESCRIBE {0}.{1}", owner, table); using (MySqlDataReader sqlDataReader = tableDetailsCommand.ExecuteReader(CommandBehavior.Default)) { while (sqlDataReader.Read()) { string columnName = sqlDataReader.GetString(0); string dataType = sqlDataReader.GetString(1); bool isNullable = sqlDataReader.GetString(2).Equals("YES", StringComparison. CurrentCultureIgnoreCase); bool isPrimaryKey = (!sqlDataReader.IsDBNull(3) ? sqlDataReader.GetString(3).Equals( MysqlConstraintType.PrimaryKey.ToString(), StringComparison.CurrentCultureIgnoreCase) : false); bool isForeignKey = (!sqlDataReader.IsDBNull(3) ? sqlDataReader.GetString(3).Equals( MysqlConstraintType.ForeignKey.ToString(), StringComparison.CurrentCultureIgnoreCase) : false); var m = new DataTypeMapper(); columns.Add(new Column { Name = columnName, DataType = dataType, IsNullable = isNullable, IsPrimaryKey = isPrimaryKey, //IsPrimaryKey(selectedTableName.Name, columnName) IsForeignKey = isForeignKey, // IsFK() MappedDataType = m.MapFromDBType(ServerType.MySQL, dataType, null, null, null).ToString(), //DataLength = dataLength }); table.Columns = columns; } table.Owner = owner; table.PrimaryKey = DeterminePrimaryKeys(table); // Need to find the table name associated with the FK foreach (var c in table.Columns) { c.ForeignKeyTableName = GetForeignKeyReferenceTableName(table.Name, c.Name); } table.ForeignKeys = DetermineForeignKeyReferences(table); table.HasManyRelationships = DetermineHasManyRelationships(table); } } } } finally { conn.Close(); } return columns; }
private void CreateAutoProperties(CodeGenerationHelper codeGenerationHelper, DataTypeMapper mapper, CodeTypeDeclaration newType) { if (Table.PrimaryKey != null) { foreach (var pk in Table.PrimaryKey.Columns) { var mapFromDbType = mapper.MapFromDBType(this.appPrefs.ServerType, pk.DataType, pk.DataLength, pk.DataPrecision, pk.DataScale); newType.Members.Add(codeGenerationHelper.CreateAutoProperty(mapFromDbType.ToString(), Formatter.FormatText(pk.Name), appPrefs.UseLazy)); } } if (appPrefs.IncludeForeignKeys) { var pascalCaseTextFormatter = new PascalCaseTextFormatter { PrefixRemovalList = appPrefs.FieldPrefixRemovalList }; // Note that a foreign key referencing a primary within the same table will end up giving you a foreign key property with the same name as the table. foreach (var fk in Table.ForeignKeys.Where(fk => !string.IsNullOrEmpty(fk.References))) { var typeName = appPrefs.ClassNamePrefix + pascalCaseTextFormatter.FormatSingular(fk.References); newType.Members.Add(codeGenerationHelper.CreateAutoProperty(typeName, Formatter.FormatSingular(fk.UniquePropertyName), appPrefs.UseLazy)); } } foreach (var column in Table.Columns.Where(x => !x.IsPrimaryKey && (!x.IsForeignKey || !appPrefs.IncludeForeignKeys))) { var mapFromDbType = mapper.MapFromDBType(this.appPrefs.ServerType, column.DataType, column.DataLength, column.DataPrecision, column.DataScale); var property = codeGenerationHelper.CreateAutoProperty(mapFromDbType, Formatter.FormatText(column.Name), column.IsNullable, appPrefs.UseLazy); AttachValidatorAttributes(ref property, column); newType.Members.Add(property); } }
public IList<Column> GetTableDetails(Table table, string owner) { var columns = new List<Column>(); using (var sqlCon = new OleDbConnection(_connectionStr)) { try { using (var tableDetailsCommand = sqlCon.CreateCommand()) { var sqlText = @"SELECT [default] default_value, c.column_name columnName, d.domain_name DataTypeName, width ColumnSize, scale columnPrecision, convert(bit, CASE WHEN pkey = 'Y' THEN 1 ELSE 0 END) IsKey, convert(bit, CASE WHEN c.[nulls] = 'Y' THEN 1 ELSE 0 END) AllowDBNull, convert(bit, CASE WHEN c.[default] = 'AUTOINCREMENT' THEN 1 ELSE 0 END) IsIdentity, convert(bit, CASE WHEN c.[default] = 'NEWID()' THEN 1 ELSE 0 END) IsGenerated, convert(bit, CASE WHEN fcol.foreign_column_id is null THEN 0 ELSE 1 END) IsForeignKey, ISNULL(fk.[role],'') ConstraintName FROM sys.syscolumn c inner join sys.systable t on t.table_id = c.table_id inner join sys.sysdomain d on c.domain_id = d.domain_id inner join sysobjects o on t.object_id = o.id inner join sys.sysuser u on u.user_id = o.uid left join sysfkcol fcol ON c.table_id = fcol.foreign_table_id and c.column_id = fcol.foreign_column_id left join sysforeignkey fk ON fcol.foreign_table_id = fk.foreign_table_id AND fcol.foreign_key_id = fk.foreign_key_id WHERE t.table_name = '{0}' and u.user_name = '{1}' ORDER BY c.Column_id"; tableDetailsCommand.CommandText = string.Format(sqlText,table.Name, owner); sqlCon.Open(); var dr = tableDetailsCommand.ExecuteReader(CommandBehavior.Default); var m = new DataTypeMapper(); while (dr.Read()) { var name = dr["columnName"].ToString(); var isNullable = (bool) dr["AllowDBNull"]; var isPrimaryKey = dr["IsKey"] as bool?; var isForeignKey = (bool)dr["IsForeignKey"]; var dataType = dr["DataTypeName"].ToString(); var dataLength = Convert.ToInt32(dr["columnSize"]); var dataPrecision = Convert.ToInt32(dr["columnSize"]); var dataScale = Convert.ToInt32(dr["columnPrecision"]); var isIdentity = dr["IsIdentity"] as bool?; var constraintName = dr["ConstraintName"].ToString(); var isUnique = false; //(bool) dr["IsKey"]; var mappedType = m.MapFromDBType(ServerType.Sybase, dataType, dataLength, dataPrecision, dataScale); if (DataTypeMapper.IsNumericType(mappedType)) { dataLength = 0; } else { dataScale = 0; dataPrecision = 0; } columns.Add( new Column { Name = name, IsNullable = isNullable, IsPrimaryKey = isPrimaryKey.GetValueOrDefault(), IsForeignKey = isForeignKey, MappedDataType = mappedType.ToString(), DataLength = dataLength, DataScale = dataScale, DataPrecision = dataPrecision, DataType = dataType, IsUnique = isUnique, IsIdentity = isIdentity.GetValueOrDefault(), ConstraintName = constraintName }); } dr.Close(); } table.Owner = owner; table.Columns = columns; table.PrimaryKey = DeterminePrimaryKeys(table); // Need to find the table name associated with the FK foreach (var c in table.Columns) { c.ForeignKeyTableName = GetForeignKeyReferenceTableName(table.Name, c.Name); } table.ForeignKeys = DetermineForeignKeyReferences(table); table.HasManyRelationships = DetermineHasManyRelationships(table); } catch (Exception ex) { Console.Write(ex.Message); } finally { sqlCon.Close(); } } return columns; }
/// <summary> /// Generates sql command for execution for insert, update, and remove /// </summary> /// <typeparam name="T"></typeparam> /// <param name="item">Model Property</param> /// <param name="query">Sql Statement</param> /// <param name="modelProperties">Properties of the model</param> /// <param name="primaryKeyProperties">Properties of the model that are associated with the primary key</param> /// <param name="isUpdate">Is the sql an update query</param> /// <returns></returns> internal SqlCommand GenerateSqlCommand <T>(T item, string query, PropertyInfo[] modelProperties, PropertyInfo[] primaryKeyProperties, ADOCRUDEnums.Action action, string suffix) { // Initializes sql command SqlCommand cmd = new SqlCommand(query.ToString(), sqlConnection as SqlConnection, sqlTransaction as SqlTransaction); if (modelProperties != null && modelProperties.Count() > 0) { // Adds model parameters to sql command for (int i = 0; i < modelProperties.Count(); i++) { // Checks to see if the data type is in the list of handled data types if (DataTypeMapper.DataTypes().ContainsKey(modelProperties[i].PropertyType)) { SqlDbType dbType; // Grabs value from property and checks if its null // If its not null, the pass value into sqlcommand parameter // Otherwise pass in DBNull.Value as the sql parameter DataTypeMapper.DataTypes().TryGetValue(modelProperties[i].PropertyType, out dbType); object dbValue = modelProperties[i].GetValue(item, null); if (dbValue != null) { cmd.Parameters.Add(modelProperties[i].Name + suffix, dbType).Value = modelProperties[i].GetValue(item, null); } else { cmd.Parameters.Add(modelProperties[i].Name + suffix, dbType).Value = DBNull.Value; } } else { throw new Exception("Property of type " + modelProperties[i].PropertyType.Name + " does not have a corresponding sql data type"); } } } if (action == ADOCRUDEnums.Action.Insert) { // Grabs identity generated on insert cmd.Parameters.Add("primaryKey", SqlDbType.Int).Direction = ParameterDirection.Output; } else if (action == ADOCRUDEnums.Action.Update || action == ADOCRUDEnums.Action.Remove) { // Add primary key parameters to sql command for (int i = 0; i < primaryKeyProperties.Count(); i++) { // Don't add parameter if it already exist in the sql command if (!cmd.Parameters.Contains(primaryKeyProperties[i].Name + suffix)) { if (primaryKeyProperties[i].PropertyType == typeof(int)) { cmd.Parameters.Add(primaryKeyProperties[i].Name + suffix, SqlDbType.Int).Value = primaryKeyProperties[i].GetValue(item, null); } else if (primaryKeyProperties[0].PropertyType == typeof(Guid)) { cmd.Parameters.Add(primaryKeyProperties[i].Name + suffix, SqlDbType.UniqueIdentifier).Value = primaryKeyProperties[i].GetValue(item, null); } else { throw new Exception("Primary key must be an integer or GUID"); } } } } return(cmd); }
private void CreateFields(CodeGenerationHelper codeGenerationHelper, DataTypeMapper mapper, CodeTypeDeclaration newType) { if (Table.PrimaryKey != null) { foreach (var pk in Table.PrimaryKey.Columns) { var mapFromDbType = mapper.MapFromDBType(appPrefs.ServerType, pk.DataType, pk.DataLength, pk.DataPrecision, pk.DataScale); var propertyName = Formatter.FormatText(pk.Name); var fieldName = FixPropertyWithSameClassName(propertyName, Table.Name); var pkAlsoFkQty = (from fk in Table.ForeignKeys.Where(fk => fk.UniquePropertyName == pk.Name) select fk).Count(); if (pkAlsoFkQty > 0) fieldName = fieldName + "Id"; newType.Members.Add(codeGenerationHelper.CreateField(mapFromDbType, fieldName, true)); } } if (appPrefs.IncludeForeignKeys) { var pascalCaseTextFormatter = new PascalCaseTextFormatter(); // Note that a foreign key referencing a primary within the same table will end up giving you a foreign key property with the same name as the table. foreach (var fk in Table.ForeignKeys.Where(fk => !string.IsNullOrEmpty(fk.References))) { var propertyName = fk.UniquePropertyName; propertyName = Formatter.FormatSingular(propertyName); var fieldName = FixPropertyWithSameClassName(propertyName, Table.Name); var typeName = appPrefs.ClassNamePrefix + pascalCaseTextFormatter.FormatSingular(fk.References); newType.Members.Add(codeGenerationHelper.CreateField(typeName, fieldName)); } } foreach (var column in Table.Columns.Where(x => !x.IsPrimaryKey && (!x.IsForeignKey || !appPrefs.IncludeForeignKeys))) { var mapFromDbType = mapper.MapFromDBType(appPrefs.ServerType, column.DataType, column.DataLength, column.DataPrecision, column.DataScale); var propertyName = Formatter.FormatText(column.Name); var fieldName = FixPropertyWithSameClassName(propertyName, Table.Name); newType.Members.Add(codeGenerationHelper.CreateField(mapFromDbType, fieldName, column.IsNullable)); } }
private void CreateFullProperties(CodeGenerationHelper codeGenerationHelper, DataTypeMapper mapper, CodeTypeDeclaration newType) { var camelCaseFormatter = new CamelCaseTextFormatter(); if (Table.PrimaryKey != null) { foreach (var pk in Table.PrimaryKey.Columns) { if (pk.IsForeignKey && appPrefs.IncludeForeignKeys) { newType.Members.Add(codeGenerationHelper.CreateField(Formatter.FormatSingular(pk.ForeignKeyTableName), "_" + camelCaseFormatter.FormatSingular(pk.ForeignKeyTableName))); newType.Members.Add(codeGenerationHelper.CreateProperty(Formatter.FormatSingular(pk.ForeignKeyTableName), Formatter.FormatSingular(pk.ForeignKeyTableName), appPrefs.UseLazy)); } else { var mapFromDbType = mapper.MapFromDBType(appPrefs.ServerType, pk.DataType, pk.DataLength, pk.DataPrecision, pk.DataScale); var pkAlsoFkQty = (from fk in Table.ForeignKeys.Where(fk => fk.UniquePropertyName == pk.Name) select fk).Count(); var fieldName = FixPropertyWithSameClassName(pk.Name, Table.Name); if (pkAlsoFkQty > 0) { fieldName = fieldName + "Id"; } newType.Members.Add(codeGenerationHelper.CreateField(mapFromDbType, "_" + camelCaseFormatter.FormatText(fieldName), true)); newType.Members.Add(codeGenerationHelper.CreateProperty(mapFromDbType, Formatter.FormatText(fieldName), appPrefs.UseLazy)); } } } if (appPrefs.IncludeForeignKeys) { var pascalCaseTextFormatter = new PascalCaseTextFormatter { PrefixRemovalList = appPrefs.FieldPrefixRemovalList }; // Note that a foreign key referencing a primary within the same table will end up giving you a foreign key property with the same name as the table. foreach (var fk in Table.Columns.Where(c => c.IsForeignKey && !c.IsPrimaryKey)) { var typeName = appPrefs.ClassNamePrefix + pascalCaseTextFormatter.FormatSingular(fk.ForeignKeyTableName); var propertyName = fk.ForeignKeyTableName; var fieldName = FixPropertyWithSameClassName(propertyName, Table.Name); newType.Members.Add(codeGenerationHelper.CreateField(typeName, string.Format("_{0}", camelCaseFormatter.FormatSingular(fieldName)))); newType.Members.Add(codeGenerationHelper.CreateProperty(typeName, Formatter.FormatSingular(fieldName), appPrefs.UseLazy)); } } foreach (var column in Table.Columns.Where(x => !x.IsPrimaryKey && (!x.IsForeignKey || !appPrefs.IncludeForeignKeys))) { var mapFromDbType = mapper.MapFromDBType(appPrefs.ServerType, column.DataType, column.DataLength, column.DataPrecision, column.DataScale); var fieldName = FixPropertyWithSameClassName(column.Name, Table.Name); newType.Members.Add(codeGenerationHelper.CreateField(mapFromDbType, "_" + camelCaseFormatter.FormatText(fieldName), column.IsNullable)); var property = codeGenerationHelper.CreateProperty(mapFromDbType, Formatter.FormatText(fieldName), column.IsNullable, appPrefs.UseLazy); AttachValidatorAttributes(ref property, column); newType.Members.Add(property); } }
/// <summary> /// Return all table details based on table and owner. /// </summary> /// <param name="table"></param> /// <param name="owner"></param> /// <returns></returns> public IList<Column> GetTableDetails(Table table, string owner) { var columns = new List<Column>(); using (var conn = new OracleConnection(connectionStr)) { conn.Open(); using (OracleCommand tableCommand = conn.CreateCommand()) { tableCommand.CommandText = @"select column_name, data_type, nullable, sum(constraint_type) constraint_type, data_length, data_precision, data_scale from ( SELECT tc.column_name AS column_name, tc.data_type AS data_type, tc.nullable AS NULLABLE, decode(c.constraint_type, 'P', 1, 'R', 2, 'U', 4, 'C', 8, 16) AS constraint_type, data_length, data_precision, data_scale, column_id from all_tab_columns tc left outer join ( all_cons_columns cc join all_constraints c on ( c.owner=cc.owner and c.constraint_name = cc.constraint_name ) ) on ( tc.owner = cc.owner and tc.table_name = cc.table_name and tc.column_name = cc.column_name ) where tc.table_name = :table_name and tc.owner = :owner order by tc.table_name, cc.position nulls last, tc.column_id) group by column_name, data_type, nullable, data_length, data_precision, data_scale, column_id order by column_id"; tableCommand.Parameters.Add("table_name", table.Name); tableCommand.Parameters.Add("owner", owner); using (OracleDataReader oracleDataReader = tableCommand.ExecuteReader(CommandBehavior.Default)) { var m = new DataTypeMapper(); while (oracleDataReader.Read()) { var constraintType = Convert.ToInt32(oracleDataReader.GetOracleNumber(3).Value); int? dataLength = oracleDataReader.IsDBNull(4) ? (int?)null : Convert.ToInt32(oracleDataReader.GetOracleNumber(4).Value); int? dataPrecision = oracleDataReader.IsDBNull(5) ? (int?)null : Convert.ToInt32(oracleDataReader.GetOracleNumber(5).Value); int? dataScale = oracleDataReader.IsDBNull(6) ? (int?)null : Convert.ToInt32(oracleDataReader.GetOracleNumber(6).Value); columns.Add(new Column { Name = oracleDataReader.GetOracleString(0).Value, DataType = oracleDataReader.GetOracleString(1).Value, IsNullable = string.Equals(oracleDataReader.GetOracleString(2).Value, "Y", StringComparison.OrdinalIgnoreCase), IsPrimaryKey = ConstraintTypeResolver.IsPrimaryKey(constraintType), IsForeignKey = ConstraintTypeResolver.IsForeignKey(constraintType), IsUnique = ConstraintTypeResolver.IsUnique(constraintType), MappedDataType = m.MapFromDBType(ServerType.Oracle, oracleDataReader.GetOracleString(1).Value, dataLength, dataPrecision, dataScale).ToString(), DataLength = dataLength, DataPrecision = dataPrecision, DataScale = dataScale }); } table.Owner = owner; table.Columns = columns; table.PrimaryKey = DeterminePrimaryKeys(table); // Need to find the table name associated with the FK foreach (var c in table.Columns.Where(c => c.IsForeignKey)) { var foreignInfo = GetForeignKeyReferenceTableName(table.Name, c.Name); c.ForeignKeyTableName = foreignInfo.Item1; c.ForeignKeyColumnName = foreignInfo.Item2; } table.ForeignKeys = DetermineForeignKeyReferences(table); table.HasManyRelationships = DetermineHasManyRelationships(table); } } conn.Close(); } return columns; }
public XmlDocument CreateMappingDocument() { string realTableName = GlobalCache.Instance.ReplaceShortWords(tableName.ToUpper()); var xmldoc = new XmlDocument(); var xmlDeclaration = xmldoc.CreateXmlDeclaration("1.0", string.Empty, string.Empty); xmldoc.AppendChild(xmlDeclaration); var root = xmldoc.CreateElement("hibernate-mapping", "urn:nhibernate-mapping-2.2"); root.SetAttribute("assembly", assemblyName); root.SetAttribute("namespace", nameSpace); xmldoc.AppendChild(root); var classElement = xmldoc.CreateElement("class"); //classElement.SetAttribute("name", nameSpace + "." + realTableName.GetFormattedText() + ", " + assemblyName); classElement.SetAttribute("name", realTableName.GetFormattedText()); classElement.SetAttribute("table", tableName); //classElement.SetAttribute("lazy", "true"); root.AppendChild(classElement); var primaryKeyColumns = columnDetails.FindAll(detail => detail.IsPrimaryKey); if (primaryKeyColumns.Count > 0) { if (primaryKeyColumns.Count == 1) { var primaryKeyColumn = primaryKeyColumns[0]; var idElement = xmldoc.CreateElement("id"); string propertyName = primaryKeyColumn.ColumnName.GetPreferenceFormattedText(applicationPreferences); if (applicationPreferences.FieldGenerationConvention == FieldGenerationConvention.Property) { idElement.SetAttribute("name", propertyName.MakeFirstCharLowerCase()); } else { if(applicationPreferences.FieldGenerationConvention == FieldGenerationConvention.AutoProperty) { propertyName = primaryKeyColumn.ColumnName.GetFormattedText(); } idElement.SetAttribute("name", propertyName); } var mapper = new DataTypeMapper(); Type mapFromDbType = mapper.MapFromDBType(primaryKeyColumn.DataType, primaryKeyColumn.DataLength, primaryKeyColumn.DataPrecision, primaryKeyColumn.DataScale); idElement.SetAttribute("type", mapFromDbType.Name); idElement.SetAttribute("column", primaryKeyColumn.ColumnName); if (applicationPreferences.FieldGenerationConvention != FieldGenerationConvention.AutoProperty) { idElement.SetAttribute("access", "field"); } classElement.AppendChild(idElement); AddIdGenerator(xmldoc, idElement); } else // composite key { var primaryKeyColumn = primaryKeyColumns[0]; var idElement = xmldoc.CreateElement("composite-id"); string pkName = tableName.GetPreferenceFormattedText(applicationPreferences) + "PK"; if (applicationPreferences.FieldGenerationConvention == FieldGenerationConvention.Property) { idElement.SetAttribute("name", pkName.MakeFirstCharLowerCase()); idElement.SetAttribute("class", realTableName.GetFormattedText() + "PK"); } else { if (applicationPreferences.FieldGenerationConvention == FieldGenerationConvention.AutoProperty) { pkName = GlobalCache.Instance.ReplaceShortWords(tableName.ToUpper()); pkName = pkName.GetFormattedText() + "PK"; } idElement.SetAttribute("name", pkName); idElement.SetAttribute("class", pkName); } classElement.AppendChild(idElement); AddCompositeIdGenerator(xmldoc, idElement, primaryKeyColumns, applicationPreferences); } } AddAllProperties(xmldoc, classElement); var tableReferences = applicationPreferences.TableReferences; if(tableReferences!= null && tableReferences.Count > 0) { foreach (KeyValuePair<string, TableReference> pair in tableReferences) { TableReference reference = pair.Value; switch(reference.ReferenceType) { case ReferenceType.OneToMany: AddOneToManyProperty(xmldoc, classElement, reference); break; case ReferenceType.ManyToOne: AddManyToOneProperty(xmldoc, classElement, reference); break; } } } return xmldoc; }
private static CodeSnippetStatement GetIdMapCodeSnippetStatement(ApplicationPreferences appPrefs, Table table, string pkColumnName, string propertyName, string pkColumnType, ITextFormatter formatter) { var dataTypeMapper = new DataTypeMapper(); bool isPkTypeIntegral = (dataTypeMapper.MapFromDBType(appPrefs.ServerType, pkColumnType, null, null, null)).IsTypeIntegral(); string idGeneratorType = (isPkTypeIntegral ? "GeneratedBy.Identity()" : "GeneratedBy.Assigned()"); var fieldName = FixPropertyWithSameClassName(propertyName, table.Name); var pkAlsoFkQty = (from fk in table.ForeignKeys.Where(fk => fk.UniquePropertyName == pkColumnName) select fk).Count(); if (pkAlsoFkQty > 0) fieldName = fieldName + "Id"; return new CodeSnippetStatement(string.Format(TABS + "Id(x => x.{0}).{1}.Column(\"{2}\");", formatter.FormatText(fieldName), idGeneratorType, pkColumnName)); }
public CodeCompileUnit GetCompileUnit(out CodeCompileUnit pkClass) { var codeGenerationHelper = new CodeGenerationHelper(); var compileUnit = codeGenerationHelper.GetCodeCompileUnit(nameSpace, tableName.GetFormattedText()); CodeCompileUnit pkCompileUnit = null; var mapper = new DataTypeMapper(); var newType = compileUnit.Namespaces[0].Types[0]; List<ColumnDetail> pkColumns = columnDetails.FindAll(col => col.IsPrimaryKey); List<ColumnDetail> normalColumns = columnDetails.FindAll(col => col.IsPrimaryKey == false); // data contract count int dataContractCount = 1; // create pk columns if(pkColumns.Count > 0) { if(pkColumns.Count == 1) { var columnDetail = pkColumns[0]; string propertyName = columnDetail.ColumnName.GetPreferenceFormattedText(applicationPreferences); Type mapFromDbType = mapper.MapFromDBType(columnDetail.DataType, columnDetail.DataLength, columnDetail.DataPrecision, columnDetail.DataScale); switch (applicationPreferences.FieldGenerationConvention) { case FieldGenerationConvention.Property: newType.Members.Add(codeGenerationHelper.CreateProperty(mapFromDbType, propertyName.MakeFirstCharUpperCase())); newType.Members.Add(codeGenerationHelper.CreateField(mapFromDbType, propertyName.MakeFirstCharLowerCase())); break; case FieldGenerationConvention.AutoProperty: propertyName = columnDetail.ColumnName.GetFormattedText(); var codeMemberProperty = codeGenerationHelper.CreateAutoProperty(mapFromDbType, propertyName); newType.Members.Add(codeMemberProperty); break; default: newType.Members.Add(codeGenerationHelper.CreateField(mapFromDbType, propertyName)); break; } } else // composite key { string pkClassName = tableName.GetFormattedText() + "PK"; string pkRefProperty = pkClassName; pkCompileUnit = codeGenerationHelper.GetCodeCompileUnit(nameSpace, pkClassName); var newPKType = pkCompileUnit.Namespaces[0].Types[0]; // create composite member switch (applicationPreferences.FieldGenerationConvention) { case FieldGenerationConvention.Property: newType.Members.Add(codeGenerationHelper.CreateProperty(pkClassName, pkRefProperty.MakeFirstCharUpperCase())); newType.Members.Add(codeGenerationHelper.CreateField(pkClassName, pkRefProperty.MakeFirstCharLowerCase())); break; case FieldGenerationConvention.AutoProperty: //pkPropertyName = columnDetail.ColumnName.GetFormattedText(); var codeMemberProperty = codeGenerationHelper.CreateAutoProperty(pkClassName, pkRefProperty); newType.Members.Add(codeMemberProperty); break; default: newType.Members.Add(codeGenerationHelper.CreateField(pkClassName, pkRefProperty)); break; } // create pk columns foreach (var columnDetail in pkColumns) { string pkPropertyName = columnDetail.ColumnName.GetPreferenceFormattedText(applicationPreferences); Type pkMapFromDbType = mapper.MapFromDBType(columnDetail.DataType, columnDetail.DataLength, columnDetail.DataPrecision, columnDetail.DataScale); // get compile unit of compile class switch (applicationPreferences.FieldGenerationConvention) { case FieldGenerationConvention.Property: newPKType.Members.Add(codeGenerationHelper.CreateProperty(pkMapFromDbType, pkPropertyName.MakeFirstCharUpperCase())); newPKType.Members.Add(codeGenerationHelper.CreateField(pkMapFromDbType, pkPropertyName.MakeFirstCharLowerCase())); break; case FieldGenerationConvention.AutoProperty: pkPropertyName = columnDetail.ColumnName.GetFormattedText(); var codeMemberProperty = codeGenerationHelper.CreateAutoProperty(pkMapFromDbType, pkPropertyName); newPKType.Members.Add(codeMemberProperty); break; default: newPKType.Members.Add(codeGenerationHelper.CreateField(pkMapFromDbType, pkPropertyName)); break; } } newPKType.CustomAttributes.Add(new CodeAttributeDeclaration("Serializable")); newPKType.CustomAttributes.Add(new CodeAttributeDeclaration("Validate")); newPKType.CustomAttributes.Add(new CodeAttributeDeclaration("DataContract")); foreach (var member in newPKType.Members) { if (member is CodeMemberProperty) { CodeMemberProperty property = (CodeMemberProperty)member; CodeAttributeArgument[] arguments = new CodeAttributeArgument[] { new CodeAttributeArgument("Name",new CodePrimitiveExpression(dataContractCount.ToString())), new CodeAttributeArgument("Order",new CodePrimitiveExpression(dataContractCount++)) }; property.CustomAttributes.Add(new CodeAttributeDeclaration("DataMember", arguments)); } } } } // create normal columns foreach (var columnDetail in normalColumns) { string propertyName = columnDetail.ColumnName.GetPreferenceFormattedText(applicationPreferences); Type mapFromDbType = mapper.MapFromDBType(columnDetail.DataType, columnDetail.DataLength, columnDetail.DataPrecision, columnDetail.DataScale); if(FiendInTableReference(columnDetail)) continue; switch (applicationPreferences.FieldGenerationConvention) { case FieldGenerationConvention.Property: newType.Members.Add(codeGenerationHelper.CreateProperty(mapFromDbType, propertyName.MakeFirstCharUpperCase())); newType.Members.Add(codeGenerationHelper.CreateField(mapFromDbType, propertyName.MakeFirstCharLowerCase())); break; case FieldGenerationConvention.AutoProperty: propertyName = columnDetail.ColumnName.GetFormattedText(); var codeMemberProperty = codeGenerationHelper.CreateAutoProperty(mapFromDbType, propertyName); newType.Members.Add(codeMemberProperty); break; default: newType.Members.Add(codeGenerationHelper.CreateField(mapFromDbType, propertyName)); break; } } // create detail member if exist if(tableReferences != null && tableReferences.Count > 0) { foreach (KeyValuePair<string, TableReference> pair in tableReferences) { TableReference reference = pair.Value; string refTable = GlobalCache.Instance.ReplaceShortWords(reference.ReferenceTable); switch(reference.ReferenceType) { case ReferenceType.OneToMany: refTable = refTable.GetFormattedText(); var detailListMemberProperty = codeGenerationHelper.CreateAutoProperty("IList<" + refTable + ">", refTable + "s"); newType.Members.Add(detailListMemberProperty); break; case ReferenceType.ManyToOne: refTable = refTable.GetFormattedText(); var masterMemberProperty = codeGenerationHelper.CreateAutoProperty(refTable, refTable); newType.Members.Add(masterMemberProperty); break; } } } var constructor = new CodeConstructor {Attributes = MemberAttributes.Public}; newType.Members.Add(constructor); newType.CustomAttributes.Add(new CodeAttributeDeclaration("Serializable")); newType.CustomAttributes.Add(new CodeAttributeDeclaration("Validate")); newType.CustomAttributes.Add(new CodeAttributeDeclaration("DataContract")); foreach (var member in newType.Members) { if(member is CodeMemberProperty) { CodeMemberProperty property = (CodeMemberProperty) member; CodeAttributeArgument[] arguments = new CodeAttributeArgument[] { new CodeAttributeArgument("Name",new CodePrimitiveExpression(dataContractCount.ToString())), new CodeAttributeArgument("Order",new CodePrimitiveExpression(dataContractCount++)) }; property.CustomAttributes.Add(new CodeAttributeDeclaration("DataMember",arguments)); } } pkClass = pkCompileUnit; return compileUnit; }
protected override IList<Column> GetTablesDetails(Table table, string owner) { var columns = new List<Column>(); var conn = new NpgsqlConnection(_connectionString); conn.Open(); using (conn) { using (NpgsqlCommand tableDetailsCommand = conn.CreateCommand()) { tableDetailsCommand.CommandText = String.Format( @" SELECT c.column_name, c.data_type, c.is_nullable, b.constraint_type as type, a.constraint_name FROM information_schema.constraint_column_usage a INNER JOIN information_schema.table_constraints b ON a.constraint_name=b.constraint_name INNER JOIN information_schema.columns c ON a.column_name=c.column_name AND a.table_name=c.table_name WHERE a.table_schema = '{1}' AND a.table_name='{0}' AND b.constraint_type IN ('PRIMARY KEY') UNION SELECT a.column_name, a.data_type, a.is_nullable, b.constraint_type as type, b.constraint_name FROM information_schema.columns a INNER JOIN information_schema.table_constraints b ON b.constraint_name ='{0}_'||a.column_name||'_fkey' UNION SELECT a.column_name, a.data_type, a.is_nullable, '', '' FROM information_schema.columns a WHERE a.table_schema = '{1}' AND a.table_name = '{0}' AND a.column_name NOT IN ( SELECT c.column_name FROM information_schema.constraint_column_usage a INNER JOIN information_schema.table_constraints b ON a.constraint_name=b.constraint_name INNER JOIN information_schema.columns c ON a.column_name=c.column_name AND a.table_name=c.table_name WHERE a.table_schema = '{1}' AND a.table_name = '{0}' AND b.constraint_type IN ('PRIMARY KEY') UNION SELECT a.column_name FROM information_schema.columns a INNER JOIN information_schema.table_constraints b ON b.constraint_name ='{0}_'||a.column_name||'_fkey' )", table.Name, owner); using (NpgsqlDataReader sqlDataReader = tableDetailsCommand.ExecuteReader(CommandBehavior.Default)) { while (sqlDataReader.Read()) { string columnName = sqlDataReader.GetString(0); string dataType = sqlDataReader.GetString(1); bool isNullable = sqlDataReader.GetString(2).Equals("YES", StringComparison. CurrentCultureIgnoreCase); bool isPrimaryKey = (!sqlDataReader.IsDBNull(3) ? sqlDataReader.GetString(3).Equals( NpgsqlConstraintType.PrimaryKey.ToString(), StringComparison.CurrentCultureIgnoreCase) : false); bool isForeignKey = (!sqlDataReader.IsDBNull(3) ? sqlDataReader.GetString(3).Equals( NpgsqlConstraintType.ForeignKey.ToString(), StringComparison.CurrentCultureIgnoreCase) : false); string constraintName = sqlDataReader.GetString(4); var m = new DataTypeMapper(); columns.Add(new Column(table) { Name = columnName, DataType = dataType, IsNullable = isNullable, IsPrimaryKey = isPrimaryKey, IsForeignKey = isForeignKey, ConstraintName = constraintName, MappedDataType = m.MapFromDBType(DatabaseServerType.PostgreSQL, dataType, null, null, null, isPrimaryKey), //DataLength = dataLength }); } table.Columns = columns; table.OwnerSchema = owner; table.PrimaryKey = DeterminePrimaryKeys(table); // Need to find the table name associated with the FK foreach (var c in table.Columns) { c.ForeignKeyTableName = GetForeignKeyReferenceTableName(table.Name, c.Name); } table.ForeignKeys = DetermineForeignKeyReferences(table); table.HasManyRelationships = DetermineHasManyRelationships(table); } } } return columns; }
/// <summary> /// Return all table details based on table and owner. /// </summary> /// <param name="table"></param> /// <param name="owner"></param> /// <returns></returns> public IList <Column> GetTableDetails(Table table, string owner) { var columns = new List <Column>(); using (var conn = new OracleConnection(connectionStr)) { conn.Open(); using (OracleCommand tableCommand = conn.CreateCommand()) { tableCommand.CommandText = @"SELECT tc.column_name AS column_name, tc.data_type AS data_type, tc.nullable AS NULLABLE, nvl(c.constraint_type,'CHANGE THIS IN CODE') AS constraint_type, data_length, data_precision, data_scale from all_tab_columns tc left outer join ( all_cons_columns cc join all_constraints c on ( c.owner=cc.owner and c.constraint_name = cc.constraint_name and c.constraint_type <> 'C' ) ) on ( tc.owner = cc.owner and tc.table_name = cc.table_name and tc.column_name = cc.column_name ) where tc.table_name = :table_name and tc.owner = :owner order by tc.table_name, cc.position nulls last, tc.column_id"; tableCommand.Parameters.Add("table_name", table.Name); tableCommand.Parameters.Add("owner", owner); using (OracleDataReader oracleDataReader = tableCommand.ExecuteReader(CommandBehavior.Default)) { var m = new DataTypeMapper(); while (oracleDataReader.Read()) { var constraintType = oracleDataReader.GetOracleString(3).Value; int?dataLength = oracleDataReader.IsDBNull(4) ? (int?)null : Convert.ToInt32(oracleDataReader.GetOracleNumber(4).Value); int?dataPrecision = oracleDataReader.IsDBNull(5) ? (int?)null : Convert.ToInt32(oracleDataReader.GetOracleNumber(5).Value); int?dataScale = oracleDataReader.IsDBNull(6) ? (int?)null : Convert.ToInt32(oracleDataReader.GetOracleNumber(6).Value); columns.Add(new Column { Name = oracleDataReader.GetOracleString(0).Value, DataType = oracleDataReader.GetOracleString(1).Value, IsNullable = string.Equals(oracleDataReader.GetOracleString(2).Value, "Y", StringComparison.OrdinalIgnoreCase), IsPrimaryKey = ConstraintTypeResolver.IsPrimaryKey(constraintType), IsForeignKey = ConstraintTypeResolver.IsForeignKey(constraintType), IsUnique = ConstraintTypeResolver.IsUnique(constraintType), MappedDataType = m.MapFromDBType(ServerType.Oracle, oracleDataReader.GetOracleString(1).Value, dataLength, dataPrecision, dataScale).ToString(), DataLength = dataLength, DataPrecision = dataPrecision, DataScale = dataScale }); } table.Columns = columns; table.PrimaryKey = DeterminePrimaryKeys(table); table.ForeignKeys = DetermineForeignKeyReferences(table); table.HasManyRelationships = DetermineHasManyRelationships(table); } } conn.Close(); } return(columns); }
private void CreateAutoProperties(CodeGenerationHelper codeGenerationHelper, DataTypeMapper mapper, CodeTypeDeclaration newType) { if (Table.PrimaryKey != null) { foreach (var pk in Table.PrimaryKey.Columns) { if (pk.IsForeignKey && appPrefs.IncludeForeignKeys) { newType.Members.Add(codeGenerationHelper.CreateAutoProperty(Formatter.FormatSingular(pk.ForeignKeyTableName), Formatter.FormatSingular(pk.ForeignKeyTableName), appPrefs.UseLazy)); } else { var mapFromDbType = mapper.MapFromDBType(this.appPrefs.ServerType, pk.DataType, pk.DataLength, pk.DataPrecision, pk.DataScale); var fieldName = FixPropertyWithSameClassName(pk.Name, Table.Name); var pkAlsoFkQty = (from fk in Table.ForeignKeys.Where(fk => fk.UniquePropertyName == pk.Name) select fk).Count(); if (pkAlsoFkQty > 0) fieldName = fieldName + "Id"; newType.Members.Add(codeGenerationHelper.CreateAutoProperty(mapFromDbType.ToString(), Formatter.FormatText(fieldName), appPrefs.UseLazy)); } } } if (appPrefs.IncludeForeignKeys) { var pascalCaseTextFormatter = new PascalCaseTextFormatter { PrefixRemovalList = appPrefs.FieldPrefixRemovalList }; // Note that a foreign key referencing a primary within the same table will end up giving you a foreign key property with the same name as the table. string lastOne = null; foreach (var fk in Table.Columns.Where(c => c.IsForeignKey && !c.IsPrimaryKey)) { var typeName = appPrefs.ClassNamePrefix + pascalCaseTextFormatter.FormatSingular(fk.ForeignKeyTableName); if (String.IsNullOrEmpty(typeName)) { System.Diagnostics.Trace.WriteLine(String.Format("Skipping null ForeignKeyTableName for field {0}", fk.Name)); continue; } var propertyName = Formatter.FormatSingular(fk.ForeignKeyTableName); var fieldName = FixPropertyWithSameClassName(propertyName, Table.Name); if (lastOne != fieldName) newType.Members.Add(codeGenerationHelper.CreateAutoProperty(typeName, fieldName, appPrefs.UseLazy)); lastOne = fieldName; } } foreach (var column in Table.Columns.Where(x => !x.IsPrimaryKey && (!x.IsForeignKey || !appPrefs.IncludeForeignKeys))) { var mapFromDbType = mapper.MapFromDBType(this.appPrefs.ServerType, column.DataType, column.DataLength, column.DataPrecision, column.DataScale); var fieldName = FixPropertyWithSameClassName(column.Name, Table.Name); var property = codeGenerationHelper.CreateAutoProperty(mapFromDbType, Formatter.FormatText(fieldName), column.IsNullable, appPrefs.UseLazy); AttachValidatorAttributes(ref property, column); newType.Members.Add(property); } }
protected override IList<Column> GetTablesDetails(Table table, string owner) { table.OwnerSchema = owner; var columns = new List<Column>(); var conn = new IngresConnection(_connectionString); conn.Open(); try { using (conn) { using (var tableDetailsCommand = conn.CreateCommand()) { tableDetailsCommand.CommandText = string.Format("SELECT" + " column_name," + " column_datatype," + " column_nulls," + " column_length," + " column_scale " + "FROM iicolumns " + "WHERE table_owner = '{0}' " + "AND table_name = '{1}' " + "ORDER BY column_sequence", owner, table.Name); using (var sqlDataReader = tableDetailsCommand.ExecuteReader(CommandBehavior.Default)) { while (sqlDataReader.Read()) { string columnName = sqlDataReader.GetString(0).TrimEnd(); string dataType = sqlDataReader.GetString(1).TrimEnd(); bool isNullable = sqlDataReader.GetString(2).Equals("Y", StringComparison.CurrentCultureIgnoreCase); int characterMaxLenth = sqlDataReader.GetInt32(3); int numericPrecision = sqlDataReader.GetInt32(3); int numericScale = sqlDataReader.GetInt32(4); var m = new DataTypeMapper(); bool isPrimaryKey = IsPrimaryKey(owner, table.Name, columnName); columns.Add(new Column(table) { Name = columnName, DataType = dataType, IsNullable = isNullable, IsPrimaryKey = isPrimaryKey, IsForeignKey = IsForeignKey(owner, table.Name, columnName), MappedDataType = m.MapFromDBType(DatabaseServerType.Ingres, dataType, characterMaxLenth, numericPrecision, numericScale, isPrimaryKey), DataLength = characterMaxLenth, ConstraintName = GetConstraintName(owner, table.Name, columnName), DataPrecision = numericPrecision, DataScale = numericScale }); table.Columns = columns; } table.PrimaryKey = DeterminePrimaryKeys(table); table.ForeignKeys = DetermineForeignKeyReferences(table); table.HasManyRelationships = DetermineHasManyRelationships(table); } } } } finally { conn.Close(); } return columns; }
public Task <IList <Column> > GetTableDetails(Table table, string owner) { table.Owner = owner; IList <Column> columns = new List <Column>(); var conn = new IngresConnection(_connectionString); conn.Open(); try { using (conn) { using (var tableDetailsCommand = conn.CreateCommand()) { tableDetailsCommand.CommandText = string.Format("SELECT" + " column_name," + " column_datatype," + " column_nulls," + " column_length," + " column_scale " + "FROM iicolumns " + "WHERE table_owner = '{0}' " + "AND table_name = '{1}' " + "ORDER BY column_sequence", owner, table.Name); using (var sqlDataReader = tableDetailsCommand.ExecuteReader(CommandBehavior.Default)) { while (sqlDataReader.Read()) { string columnName = sqlDataReader.GetString(0).TrimEnd(); string dataType = sqlDataReader.GetString(1).TrimEnd(); bool isNullable = sqlDataReader.GetString(2).Equals("Y", StringComparison.CurrentCultureIgnoreCase); int characterMaxLenth = sqlDataReader.GetInt32(3); int numericPrecision = sqlDataReader.GetInt32(3); int numericScale = sqlDataReader.GetInt32(4); var m = new DataTypeMapper(); columns.Add(new Column { Name = columnName, DataType = dataType, IsNullable = isNullable, IsPrimaryKey = IsPrimaryKey(owner, table.Name, columnName), IsForeignKey = IsForeignKey(owner, table.Name, columnName), MappedDataType = m.MapFromDBType(ServerType.Ingres, dataType, characterMaxLenth, numericPrecision, numericScale), DataLength = characterMaxLenth, ConstraintName = GetConstraintName(owner, table.Name, columnName), DataPrecision = numericPrecision, DataScale = numericScale }); table.Columns = columns; } table.PrimaryKey = DeterminePrimaryKeys(table); table.ForeignKeys = DetermineForeignKeyReferences(table); table.HasManyRelationships = DetermineHasManyRelationships(table); } } } } finally { conn.Close(); } return(Task.FromResult(columns)); }
public IList<Column> GetTableDetails(Table table, string owner) { var columns = new List<Column>(); var conn = new CUBRIDConnection(connectionStr); conn.Open(); try { using (conn) { var schema = new CUBRIDSchemaProvider(conn); DataTable dt_fk = schema.GetForeignKeys(new[] { table.Name.ToLower() }); string sqlInfo = String.Format("select * from [{0}] limit 1", table.Name.ToLower()); var adapter = new CUBRIDDataAdapter(sqlInfo, conn); var tableInfo = new DataTable(); adapter.FillSchema(tableInfo, SchemaType.Source); using (var reader = new DataTableReader(tableInfo)) { DataTable schemaTable = reader.GetSchemaTable(); for (var k = 0; k < schemaTable.Rows.Count; k++) { string columnName = schemaTable.Rows[k]["ColumnName"].ToString().ToLower(); var isUnique = (bool)schemaTable.Rows[k]["IsUnique"]; var isNullable = (bool)schemaTable.Rows[k]["AllowDBNull"]; var isPrimaryKey = (bool)schemaTable.Rows[k]["IsKey"]; var isIdentity = (bool)schemaTable.Rows[k]["IsAutoIncrement"]; var dataLength = (int)schemaTable.Rows[k]["ColumnSize"]; int dataPrecision = 0; if (schemaTable.Rows[k]["NumericPrecision"].ToString() != String.Empty) { dataPrecision = (int)schemaTable.Rows[k]["NumericPrecision"]; } int dataScale = 0; if (schemaTable.Rows[k]["NumericScale"].ToString() != String.Empty) { dataScale = (int)schemaTable.Rows[k]["NumericScale"]; } bool isForeignKey = false; string fkTableName = ""; string constraintName = ""; for (var i_fk = 0; i_fk < dt_fk.Rows.Count; i_fk++) { if (dt_fk.Rows[i_fk]["FKCOLUMN_NAME"].ToString().ToLower() == columnName) { isForeignKey = true; fkTableName = dt_fk.Rows[i_fk]["PKTABLE_NAME"].ToString(); constraintName = dt_fk.Rows[i_fk]["FK_NAME"].ToString(); break; } } string dataType; using (var cmd = new CUBRIDCommand(sqlInfo, conn)) { using (var CUBRIDReader = (CUBRIDDataReader)cmd.ExecuteReader()) { CUBRIDReader.Read(); dataType = CUBRIDReader.GetColumnTypeName(k); } } var m = new DataTypeMapper(); columns.Add(new Column { Name = columnName, DataType = dataType, IsNullable = isNullable, IsUnique = isUnique, IsPrimaryKey = isPrimaryKey, IsForeignKey = isForeignKey, IsIdentity = isIdentity, DataLength = dataLength, DataPrecision = dataPrecision, DataScale = dataScale, ForeignKeyTableName = fkTableName, ConstraintName = constraintName, MappedDataType = m.MapFromDBType(ServerType.CUBRID, dataType, null, null, null).ToString(), }); } } } table.Columns = columns; table.Owner = owner; table.PrimaryKey = DeterminePrimaryKeys(table); table.HasManyRelationships = DetermineHasManyRelationships(table); } finally { conn.Close(); } return columns; }