Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP

Loading…

Contrib T4 some fixes #338

Merged
merged 18 commits into from

2 participants

@spaccabit

Soame t4 fixes

spaccabit added some commits
@spaccabit spaccabit [Contrib][T4][SQL Server] Fix ForeignKey order definition b6cb12d
@spaccabit spaccabit [Contrib][T4] Add missing float datatype mapping 3af22b5
@spaccabit spaccabit [Contrib][T4][SQL Server] Fix retrive index definition when table dei…
…nfinition has more index

When you have table with this schema
CREATE TABLE [Test Issue](
[ID_Primary] [int] IDENTITY(1,1) NOT NULL,
[Description] [nvarchar](50) NULL,
[ID_Nation] [int] NOT NULL,
CONSTRAINT [PK_Test Issue] PRIMARY KEY CLUSTERED
(
[ID_Primary] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY =
OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]

GO

ALTER TABLE [Test Issue] ADD  CONSTRAINT [DF_Test Issue_ID_Nation]
DEFAULT ((0)) FOR [ID_Nation]
GO

the T4 template generated the following incorrect migration:

[Migration(20121120061957)]
public class CreateInitialDB : Migration
{
public override void Up()
{
//For Test Issue
Create.Table("Test Issue").InSchema("dbo")

.WithColumn("ID_Primary").AsInt32().PrimaryKey().Identity().NotNullable()
.WithColumn("Description").AsString().Nullable()
.WithColumn("ID_Nation").AsInt32().NotNullable();

Create.Index("IX_Nation").OnTable("Test Issue").InSchema("dbo")
.OnColumn("ID_Nation").Ascending()
.OnColumn("ID_Primary").Ascending();
}

public override void Down()
{

Delete.Index("IX_Nation");

Delete.Table("Test Issue");
}
}
b5bd428
@spaccabit spaccabit [Contrib][T4][Tests] Ignore generated class ffef436
@spaccabit spaccabit [Contrib][T4][Tests] Fix project reference 9cec840
@spaccabit spaccabit [Contrib][T4] Change type of Column.PropertyType from string to Syste…
…m.Data.DbType?
8fac7f8
@spaccabit spaccabit [Contrib][T4] Column CustomType e5b0b6a
@spaccabit spaccabit [Contrib][T4][SQl Server] Missing DefaultValue 546536f
@spaccabit spaccabit [Contrib][T4] Add DataReader Get<T> extension method ed40874
@spaccabit spaccabit [Contrib][T4][SQL Server] Fix retrive column size and precision 9d836bc
@spaccabit spaccabit [Contrib][T4] Fix T4 template drop ForeignKey and Index 571ef31
@spaccabit spaccabit [Contrib][T4] Fix detection of Guid DefaultValue 8defc3c
@spaccabit spaccabit [Contrib][T4] Fix detection of Byte DefaultValue 759debf
@spaccabit spaccabit [Contrib][T4] Remove unnecessary Bracket from DefaultValue 77a0fcd
@spaccabit spaccabit Merge branch 'master' of https://github.com/schambers/fluentmigrator 618660c
@spaccabit spaccabit [Contrib][T4] Add support at ForeignKey UpdateRule and DeleteRule 4fb41b3
@spaccabit spaccabit [Contrib][T4][SQL Server] ForeignKey UpdateRule and DeleteRule 23e14f8
@spaccabit spaccabit [Contrib][T4] Fix Binary(MAX) beb24f1
@daniellee
Collaborator

Thanks for the Pull Request and sorry about the delay. I'll test this out during the week.

@daniellee
Collaborator

Great work, this is starting to be usable! Especially when running against Sql Server 2008 or 2012.

@daniellee daniellee merged commit 0b66351 into from
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Commits on Nov 19, 2012
  1. @spaccabit
  2. @spaccabit
Commits on Nov 20, 2012
  1. @spaccabit

    [Contrib][T4][SQL Server] Fix retrive index definition when table dei…

    spaccabit authored
    …nfinition has more index
    
    When you have table with this schema
    CREATE TABLE [Test Issue](
    [ID_Primary] [int] IDENTITY(1,1) NOT NULL,
    [Description] [nvarchar](50) NULL,
    [ID_Nation] [int] NOT NULL,
    CONSTRAINT [PK_Test Issue] PRIMARY KEY CLUSTERED
    (
    [ID_Primary] ASC
    )WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY =
    OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
    ) ON [PRIMARY]
    
    GO
    
    ALTER TABLE [Test Issue] ADD  CONSTRAINT [DF_Test Issue_ID_Nation]
    DEFAULT ((0)) FOR [ID_Nation]
    GO
    
    the T4 template generated the following incorrect migration:
    
    [Migration(20121120061957)]
    public class CreateInitialDB : Migration
    {
    public override void Up()
    {
    //For Test Issue
    Create.Table("Test Issue").InSchema("dbo")
    
    .WithColumn("ID_Primary").AsInt32().PrimaryKey().Identity().NotNullable()
    .WithColumn("Description").AsString().Nullable()
    .WithColumn("ID_Nation").AsInt32().NotNullable();
    
    Create.Index("IX_Nation").OnTable("Test Issue").InSchema("dbo")
    .OnColumn("ID_Nation").Ascending()
    .OnColumn("ID_Primary").Ascending();
    }
    
    public override void Down()
    {
    
    Delete.Index("IX_Nation");
    
    Delete.Table("Test Issue");
    }
    }
  2. @spaccabit
  3. @spaccabit
Commits on Nov 29, 2012
  1. @spaccabit
  2. @spaccabit
Commits on Nov 30, 2012
  1. @spaccabit
  2. @spaccabit
  3. @spaccabit
  4. @spaccabit
Commits on Dec 1, 2012
  1. @spaccabit
  2. @spaccabit
  3. @spaccabit
Commits on Dec 2, 2012
  1. @spaccabit
Commits on Dec 3, 2012
  1. @spaccabit
  2. @spaccabit
  3. @spaccabit
This page is out of date. Refresh to see the latest.
View
1  .gitignore
@@ -28,3 +28,4 @@ examplecommand.txt
*.ncrunchproject
*.ncrunchsolution
*.crunchsolution.cache
+src/FluentMigrator.T4.Tests/IntialMigrationCode.cs
View
7 src/FluentMigrator.T4.Tests/FluentMigrator.T4.Tests.csproj
@@ -44,11 +44,16 @@
</ItemGroup>
<ItemGroup>
<Compile Include="GeneratorTests.cs" />
+ <Compile Include="IntialMigrationCode.cs">
+ <AutoGen>True</AutoGen>
+ <DesignTime>True</DesignTime>
+ <DependentUpon>IntialMigrationCode.tt</DependentUpon>
+ </Compile>
<Compile Include="Properties\AssemblyInfo.cs" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\FluentMigrator.T4\FluentMigrator.T4.csproj">
- <Project>{b08e4c78-29dd-4367-8a84-35cd76971d73}</Project>
+ <Project>{B08E4C78-29DD-4367-8A84-35CD76971D73}</Project>
<Name>FluentMigrator.T4</Name>
</ProjectReference>
<ProjectReference Include="..\FluentMigrator\FluentMigrator.csproj">
View
8 src/FluentMigrator.T4.Tests/IntialMigrationCode.tt
@@ -74,7 +74,7 @@ foreach(Column col in ColumnList)
{
#>
- .WithColumn("<#=col.Name#>").<#=generator.GetMigrationTypeFunctionForType(col.PropertyType,col.Size,col.Precision)
+ .WithColumn("<#=col.Name#>").<#=generator.GetMigrationTypeFunctionForType(col)
#><#if (col.IsPrimaryKey){#>.PrimaryKey()<#}#><#if (col.IsAutoIncrement){#>.Identity()<#}#><#if (col.IsNullable){#>.Nullable()<#} else {#>.NotNullable()<#}#><#if (col.DefaultValue != null){#>.WithDefaultValue(<#= generator.GetColumnDefaultValue(col) #>)<#}#>
<#
}
@@ -120,7 +120,7 @@ foreach(ForeignKey fkey in FKeyList)
if(!string.IsNullOrEmpty(fkey.Name))
{
#>ForeignKey("<#=fkey.Name#>")<#
- } #>.FromTable("<#=tbl.Name#>").InSchema("<#=fkey.ForeignTableSchema#>").ForeignColumns(<#=Join(fkey.ForeignColumns)#>).ToTable("<#=fkey.PrimaryTable#>").InSchema("<#=fkey.PrimaryTableSchema#>").PrimaryColumns(<#=Join(fkey.PrimaryColumns)#>);
+ } #>.FromTable("<#=tbl.Name#>").InSchema("<#=fkey.ForeignTableSchema#>").ForeignColumns(<#=Join(fkey.ForeignColumns)#>).ToTable("<#=fkey.PrimaryTable#>").InSchema("<#=fkey.PrimaryTableSchema#>").PrimaryColumns(<#=Join(fkey.PrimaryColumns)#>)<#=generator.GetUpdateDeleteRule(fkey)#>;
<#
}
}
@@ -137,7 +137,7 @@ foreach(Table tbl in from t in tables where !t.Ignore select t)
{
if(!string.IsNullOrEmpty(fkey.Name)){
#>
- Delete.ForeignKey("<#=fkey.Name#>");
+ Delete.ForeignKey("<#=fkey.Name#>").OnTable("<#=tbl.Name#>")<#if (string.IsNullOrEmpty(tbl.Schema) == false ){#>.InSchema("<#=tbl.Schema#>")<#}#>;
<#
} else {
#>
@@ -154,7 +154,7 @@ foreach(Table tbl in from t in tables where !t.Ignore select t)
foreach(TableIndex idx in from i in tbl.Indexes select i)
{
#>
- Delete.Index("<#=idx.Name#>");
+ Delete.Index("<#=idx.Name#>").OnTable("<#=tbl.Name#>")<#if (string.IsNullOrEmpty(tbl.Schema) == false ){#>.InSchema("<#=tbl.Schema#>")<#}#>;
<#
}
}
View
151 src/FluentMigrator.T4/CodeGenerator.cs
@@ -33,20 +33,6 @@ public CodeGenerator(string connectionString, string providerName, TextWriter wr
private bool includeViews = false;
- public bool IsTypeConvertedToLong(string columnType)
- {
- return ((columnType == "long") || (columnType == "ulong") || (columnType == "int") || (columnType == "uint"));
- }
-
- public string CheckNullable(Column col)
- {
- string result = "";
- if (col.IsNullable && col.PropertyType != "byte[]" && col.PropertyType != "string" && col.PropertyType != "Microsoft.SqlServer.Types.SqlGeography" && col.PropertyType != "Microsoft.SqlServer.Types.SqlGeometry")
- {
- result = "?";
- }
- return result;
- }
private static string ZapPassword(string connectionString)
{
@@ -62,31 +48,50 @@ public string GetCurrentTimeStamp()
public string GetColumnDefaultValue(Column col)
{
string sysType = string.Format("\"{0}\"", col.DefaultValue);
- switch (col.PropertyType.ToLower())
+ var guid = Guid.Empty;
+ switch (col.PropertyType)
{
- case "long":
- case "int":
- case "double":
- case "decimal":
- case "bool":
- sysType = col.DefaultValue.Replace("'", "").Replace("\"", "");
- break;
- case "guid":
- sysType = string.Format("\"{0}\"", col.DefaultValue);
+ case System.Data.DbType.Byte:
+ case System.Data.DbType.Currency:
+ case System.Data.DbType.Decimal:
+ case System.Data.DbType.Double:
+ case System.Data.DbType.Boolean:
+ case System.Data.DbType.Int16:
+ case System.Data.DbType.Int32:
+ case System.Data.DbType.Int64:
+ case System.Data.DbType.Single:
+ case System.Data.DbType.UInt16:
+ case System.Data.DbType.UInt32:
+ case System.Data.DbType.UInt64:
+ sysType = col.DefaultValue.Replace("'", "").Replace("\"", "").CleanBracket();
break;
- case "datetime":
+ case System.Data.DbType.Guid:
+ if (col.DefaultValue.IsGuid(out guid))
{
- if (col.DefaultValue.ToLower() == "current_time" || col.DefaultValue.ToLower() == "current_date" || col.DefaultValue.ToLower() == "current_timestamp")
- {
- sysType = "SystemMethods.CurrentDateTime";
- }
+ if (guid == Guid.Empty)
+ sysType = "Guid.Empty";
else
- {
- sysType = "\"" + col.DefaultValue + "\"";
- }
- break;
+ sysType = string.Format("new System.Guid(\"{0}\")", guid);
+ }
+ break;
+ case System.Data.DbType.DateTime:
+ case System.Data.DbType.DateTime2:
+ case System.Data.DbType.Date:
+ if (col.DefaultValue.ToLower() == "current_time"
+ || col.DefaultValue.ToLower() == "current_date"
+ || col.DefaultValue.ToLower() == "current_timestamp")
+ {
+ sysType = "SystemMethods.CurrentDateTime";
}
+ else
+ {
+ sysType = "\"" + col.DefaultValue.CleanBracket() + "\"";
+ }
+ break;
+ default:
+ break;
}
+
return sysType;
}
@@ -241,39 +246,87 @@ public Table GetTableFromListByName(string tableName, Tables tbls)
return null;
}
- public string GetMigrationTypeFunctionForType(string type, int size, int precision)
+ public string GetMigrationTypeFunctionForType(Column col)
{
+ var size = col.Size;
+ var precision = col.Precision;
string sizeStr = ((size == -1) ? "" : size.ToString());
string precisionStr = ((precision == -1) ? "" : "," + precision.ToString());
string sysType = "AsString(" + sizeStr + ")";
- switch (type.ToLower())
+ switch (col.PropertyType)
{
- case "long":
- sysType = "AsInt64()";
+ case System.Data.DbType.AnsiString:
+ sysType = string.Format("AsAnsiString({0})", sizeStr);
break;
- case "int":
- sysType = "AsInt32()";
+ case System.Data.DbType.AnsiStringFixedLength:
+ sysType = string.Format("AsFixedLengthAnsiString({0})", sizeStr);
break;
- case "guid":
- sysType = "AsGuid()";
+ case System.Data.DbType.Binary:
+ sysType = string.Format("AsBinary({0})", size == -1 ? "Int32.MaxValue" : sizeStr);
+ break;
+ case System.Data.DbType.Boolean:
+ sysType = "AsBoolean()";
+ break;
+ case System.Data.DbType.Byte:
+ sysType = "AsByte()";
+ break;
+ case System.Data.DbType.Currency:
+ sysType = "AsCurrency()";
break;
- case "datetime":
+ case System.Data.DbType.Date:
+ sysType = "AsDate()";
+ break;
+ case System.Data.DbType.DateTime:
sysType = "AsDateTime()";
break;
- case "double":
+ case System.Data.DbType.Decimal:
+ sysType = string.Format("AsDecimal({0})", sizeStr + precisionStr);
+ break;
+ case System.Data.DbType.Double:
sysType = "AsDouble()";
break;
- case "decimal":
- sysType = "AsDecimal(" + sizeStr + precisionStr + ")";
+ case System.Data.DbType.Guid:
+ sysType = "AsGuid()";
break;
- case "bool":
- sysType = "AsBoolean()";
+ case System.Data.DbType.Int16:
+ case System.Data.DbType.UInt16:
+ sysType = "AsInt16()";
+ break;
+ case System.Data.DbType.Int32:
+ case System.Data.DbType.UInt32:
+ sysType = "AsInt32()";
+ break;
+ case System.Data.DbType.Int64:
+ case System.Data.DbType.UInt64:
+ sysType = "AsInt64()";
+ break;
+ case System.Data.DbType.Single:
+ sysType = "AsFloat()";
+ break;
+ case System.Data.DbType.String:
+ sysType = string.Format("AsString({0})", sizeStr);
+ break;
+ case System.Data.DbType.StringFixedLength:
+ sysType = string.Format("AsFixedLengthString({0})", sizeStr);
break;
- case "byte[]":
- sysType = "AsBinary(" + sizeStr + ")";
+ case null:
+ sysType = string.Format("AsCustom({0})", col.CustomType);
+ break;
+ default:
break;
}
+
return sysType;
}
+
+ public string GetUpdateDeleteRule(ForeignKey fk)
+ {
+ var sb = new System.Text.StringBuilder();
+ if (fk.UpdateRule!=System.Data.Rule.None)
+ sb.AppendFormat(".OnUpdate(System.Data.Rule.{0})", fk.UpdateRule);
+ if (fk.DeleteRule != System.Data.Rule.None)
+ sb.AppendFormat(".OnDelete(System.Data.Rule.{0})", fk.DeleteRule);
+ return sb.ToString();
+ }
}
}
View
25 src/FluentMigrator.T4/Extensions/DataReaderExtension.cs
@@ -0,0 +1,25 @@
+
+namespace System.Data
+{
+ static class DataReaderExtension
+ {
+
+ public static T Get<T>(this IDataReader reader, string columnName)
+ {
+ return reader.Get(columnName, default(T));
+ }
+
+ public static T Get<T>(this IDataReader reader, string columnName, T defaultValue)
+ {
+ if (reader == null)
+ throw new ArgumentNullException("reader");
+ if (string.IsNullOrEmpty(columnName))
+ throw new ArgumentNullException("columnName");
+ T value = defaultValue;
+ var ordinal = reader.GetOrdinal(columnName);
+ if (reader.IsDBNull(ordinal) == false)
+ value = (T)reader.GetValue(ordinal);
+ return value;
+ }
+ }
+}
View
136 src/FluentMigrator.T4/Extensions/StringExtension.cs
@@ -0,0 +1,136 @@
+using System;
+using System.Collections.Generic;
+using System.Linq;
+using System.Text;
+using System.Text.RegularExpressions;
+
+namespace System
+{
+ static class StringExtension
+ {
+ // using System.Text.RegularExpressions;
+
+ /// <summary>
+ /// Regular expression built for C# on: sab, dic 1, 2012, 11.00.55
+ /// Using Expresso Version: 3.0.3634, http://www.ultrapico.com
+ ///
+ /// check guid
+ ///
+ /// A description of the regular expression:
+ ///
+ /// Match expression but don't capture it. [\'], between 0 and 1 repetitions
+ /// Literal '
+ /// [1]: A numbered capture group. [[0-9a-fA-F]{8}\-[0-9a-fA-F]{4}\-[0-9a-fA-F]{4}\-[0-9a-fA-F]{4}\-[0-9a-fA-F]{12}]
+ /// [0-9a-fA-F]{8}\-[0-9a-fA-F]{4}\-[0-9a-fA-F]{4}\-[0-9a-fA-F]{4}\-[0-9a-fA-F]{12}
+ /// Any character in this class: [0-9a-fA-F], exactly 8 repetitions
+ /// Literal -
+ /// Any character in this class: [0-9a-fA-F], exactly 4 repetitions
+ /// Literal -
+ /// Any character in this class: [0-9a-fA-F], exactly 4 repetitions
+ /// Literal -
+ /// Any character in this class: [0-9a-fA-F], exactly 4 repetitions
+ /// Literal -
+ /// Any character in this class: [0-9a-fA-F], exactly 12 repetitions
+ /// Match expression but don't capture it. [\'], between 0 and 1 repetitions
+ /// Literal '
+ ///
+ ///
+ /// </summary>
+ public static Regex isGuid = new Regex(
+ "(?:\\'){0,1}([0-9a-fA-F]{8}\\-[0-9a-fA-F]{4}\\-[0-9a-fA-F]{4" +
+ "}\\-[0-9a-fA-F]{4}\\-[0-9a-fA-F]{12})(?:\\'){0,1}",
+ RegexOptions.Multiline
+ | RegexOptions.Compiled
+ );
+
+
+
+ //// Replace the matched text in the InputText using the replacement pattern
+ // string result = isGuid.Replace(InputText,isGuidReplace);
+
+ //// Split the InputText wherever the regex matches
+ // string[] results = isGuid.Split(InputText);
+
+ //// Capture the first Match, if any, in the InputText
+ // Match m = isGuid.Match(InputText);
+
+ //// Capture all Matches in the InputText
+ // MatchCollection ms = isGuid.Matches(InputText);
+
+ //// Test to see if there is a match in the InputText
+ // bool IsMatch = isGuid.IsMatch(InputText);
+
+ //// Get the names of all the named and numbered capture groups
+ // string[] GroupNames = isGuid.GetGroupNames();
+
+ //// Get the numbers of all the named and numbered capture groups
+ // int[] GroupNumbers = isGuid.GetGroupNumbers();
+
+
+
+
+
+ internal static bool IsGuid(this string candidate, out Guid output)
+ {
+ output = Guid.Empty;
+ if (string.IsNullOrEmpty(candidate))
+ return false;
+
+ bool isValid = false;
+
+ if (candidate != null)
+ {
+
+
+ var m = isGuid.Match(candidate);
+ if (m != null && m.Success)
+ {
+
+ output = new Guid(string.Format("{{{0}}}", m.Groups[1].Value));
+ isValid = true;
+
+ }
+
+ }
+
+ return isValid;
+
+ }
+
+ static internal string Clean(this string source, char start)
+ {
+ return source.Clean(start, start);
+ }
+
+ static internal string Clean(this string source, char start, char end)
+ {
+ if (string.IsNullOrEmpty(source) == false)
+ {
+ source = source.Trim();
+ if (source.Length > 0)
+ {
+ var trimStart = -1;
+ var trimEnd = -1;
+ var chars = source.ToCharArray();
+ var i = 0;
+ var y = chars.Length - 1;
+ while (chars[i++] == start && chars[y--] == end)
+ {
+ trimStart = i;
+ trimEnd = y;
+ }
+ var trimSize = trimEnd - trimStart + 1;
+ if (trimStart > -1 && trimSize > 0)
+ source = source.Substring(trimStart, trimSize);
+ }
+ }
+ return source;
+ }
+
+
+ static internal string CleanBracket(this string source)
+ {
+ return source.Clean('(', ')');
+ }
+ }
+}
View
261 src/FluentMigrator.T4/Extensions/SwitchExtensions.cs
@@ -0,0 +1,261 @@
+using System;
+using System.Collections.Generic;
+using System.Linq;
+using System.Text;
+
+namespace System
+{
+
+
+ /// <summary>
+ ///
+ /// </summary>
+ /// <typeparam name="T"></typeparam>
+ class Switch<T>
+ {
+ /// <summary>
+ /// Initializes a new instance of the <see cref="Switch{T}" /> class.
+ /// </summary>
+ /// <param name="o">The o.</param>
+ public Switch(T o)
+ {
+ Object = o;
+ }
+
+ /// <summary>
+ /// Gets the object.
+ /// </summary>
+ /// <value>
+ /// The object.
+ /// </value>
+ public T Object { get; private set; }
+ }
+
+ /// <summary>
+ ///
+ /// </summary>
+ /// <typeparam name="T"></typeparam>
+ /// <typeparam name="R"></typeparam>
+ class Switch<T, R> : Switch<T>
+ {
+ public Switch(T o) :
+ base(o)
+ {
+ }
+ /// <summary>
+ /// Gets a value indicating whether this instance has value.
+ /// </summary>
+ /// <value>
+ /// <c>true</c> if this instance has value; otherwise, <c>false</c>.
+ /// </value>
+ public bool HasValue { get; private set; }
+ /// <summary>
+ /// Gets the value.
+ /// </summary>
+ /// <value>
+ /// The value.
+ /// </value>
+ public R Value { get; private set; }
+
+ /// <summary>
+ /// Sets the specified value.
+ /// </summary>
+ /// <param name="value">The value.</param>
+ public void Set(R value)
+ {
+ Value = value;
+ HasValue = true;
+ }
+
+ //public static operator implicit R (Switch<T, R> @switch)
+ //{
+ // return @switch.Value;
+ //}
+
+ internal object Case(string p, Func<string, Data.Rule> func)
+ {
+ throw new NotImplementedException();
+ }
+ }
+
+ /// <summary>
+ ///
+ /// </summary>
+ static class SwitchExtensions
+ {
+ /// <summary>
+ /// Cases the specified switch.
+ /// </summary>
+ /// <typeparam name="T"></typeparam>
+ /// <param name="switch">The switch.</param>
+ /// <param name="case">The case.</param>
+ /// <param name="do">The do.</param>
+ /// <returns></returns>
+ public static Switch<T> Case<T>(this Switch<T> @switch, T @case, Action<T> @do)
+ {
+ return Case(@switch, @case, @do, false);
+ }
+
+ /// <summary>
+ /// Cases the specified switch.
+ /// </summary>
+ /// <typeparam name="T"></typeparam>
+ /// <param name="switch">The switch.</param>
+ /// <param name="case">The case.</param>
+ /// <param name="do">The do.</param>
+ /// <param name="fallThrough">if set to <c>true</c> [fall through].</param>
+ /// <returns></returns>
+ public static Switch<T> Case<T>(this Switch<T> @switch, T @case, Action<T> @do, bool fallThrough)
+ {
+ return Case(@switch, x => EqualityComparer<T>.Default.Equals(x, @case), @do, fallThrough);
+ }
+
+ /// <summary>
+ /// Cases the specified switch.
+ /// </summary>
+ /// <typeparam name="T"></typeparam>
+ /// <param name="switch">The switch.</param>
+ /// <param name="case">The case.</param>
+ /// <param name="do">The do.</param>
+ /// <returns></returns>
+ public static Switch<T> Case<T>(this Switch<T> @switch, Func<T, bool> @case, Action<T> @do)
+ {
+ return Case(@switch, @case, @do, false);
+ }
+
+ /// <summary>
+ /// Cases the specified switch.
+ /// </summary>
+ /// <typeparam name="T"></typeparam>
+ /// <param name="switch">The switch.</param>
+ /// <param name="case">The case.</param>
+ /// <param name="do">The do.</param>
+ /// <param name="fallThrough">if set to <c>true</c> [fall through].</param>
+ /// <returns></returns>
+ public static Switch<T> Case<T>(this Switch<T> @switch, Func<T, bool> @case, Action<T> @do, bool fallThrough)
+ {
+ if (@switch == null)
+ {
+ return null;
+ }
+ else if (@case(@switch.Object))
+ {
+ @do(@switch.Object);
+ return fallThrough ? @switch : null;
+ }
+
+ return @switch;
+ }
+
+ /// <summary>
+ /// Defaults the specified switch.
+ /// </summary>
+ /// <typeparam name="T"></typeparam>
+ /// <param name="switch">The switch.</param>
+ /// <param name="do">The do.</param>
+ public static void Default<T>(this Switch<T> @switch, Action<T> @do)
+ {
+ if (@switch != null)
+ {
+ @do(@switch.Object);
+ }
+ }
+
+ /// <summary>
+ /// Cases the specified switch.
+ /// </summary>
+ /// <typeparam name="T"></typeparam>
+ /// <typeparam name="R"></typeparam>
+ /// <param name="switch">The switch.</param>
+ /// <param name="case">The case.</param>
+ /// <param name="do">The do.</param>
+ /// <returns></returns>
+ public static Switch<T, R> Case<T, R>(this Switch<T, R> @switch, T @case, R result)
+ {
+ return Case<T, R>(@switch, x => EqualityComparer<T>.Default.Equals(x, @case), r => result);
+ }
+
+
+ /// <summary>
+ /// Cases the specified switch.
+ /// </summary>
+ /// <typeparam name="T"></typeparam>
+ /// <typeparam name="R"></typeparam>
+ /// <param name="switch">The switch.</param>
+ /// <param name="case">The case.</param>
+ /// <param name="do">The do.</param>
+ /// <returns></returns>
+ public static Switch<T, R> Case<T, R>(this Switch<T, R> @switch, T @case, Func<T, R> @do)
+ {
+ return Case<T, R>(@switch, x => EqualityComparer<T>.Default.Equals(x, @case), @do);
+ }
+
+ /// <summary>
+ /// Cases the specified switch.
+ /// </summary>
+ /// <typeparam name="T"></typeparam>
+ /// <typeparam name="R"></typeparam>
+ /// <param name="switch">The switch.</param>
+ /// <param name="case">The case.</param>
+ /// <param name="do">The do.</param>
+ /// <returns></returns>
+ public static Switch<T, R> Case<T, R>(this Switch<T, R> @switch, Func<T, bool> @case, Func<T, R> @do)
+ {
+ if (!@switch.HasValue && @case(@switch.Object))
+ {
+ @switch.Set(@do(@switch.Object));
+ }
+
+ return @switch;
+ }
+
+ /// <summary>
+ /// Defaults the specified switch.
+ /// </summary>
+ /// <typeparam name="T"></typeparam>
+ /// <typeparam name="R"></typeparam>
+ /// <param name="switch">The switch.</param>
+ /// <param name="do">The do.</param>
+ /// <returns></returns>
+ public static R Default<T, R>(this Switch<T, R> @switch, Func<T, R> @do)
+ {
+ if (!@switch.HasValue)
+ {
+ @switch.Set(@do(@switch.Object));
+ }
+
+ return @switch.Value;
+ }
+
+
+ /// <summary>
+ /// Defaults the specified switch.
+ /// </summary>
+ /// <typeparam name="T"></typeparam>
+ /// <typeparam name="R"></typeparam>
+ /// <param name="switch">The switch.</param>
+ /// <param name="do">The do.</param>
+ /// <returns></returns>
+ public static R Default<T, R>(this Switch<T, R> @switch, Func<R> @do)
+ {
+ if (!@switch.HasValue)
+ @switch.Set(@do());
+ return @switch.Value;
+ }
+
+ /// <summary>
+ /// Defaults the specified switch.
+ /// </summary>
+ /// <typeparam name="T"></typeparam>
+ /// <typeparam name="R"></typeparam>
+ /// <param name="switch">The switch.</param>
+ /// <param name="result">The result.</param>
+ /// <returns></returns>
+ public static R Default<T, R>(this Switch<T, R> @switch, R result)
+ {
+ if (!@switch.HasValue)
+ @switch.Set(result);
+ return @switch.Value;
+ }
+ }
+}
View
4 src/FluentMigrator.T4/FluentMigrator.T4.csproj
@@ -42,6 +42,9 @@
</ItemGroup>
<ItemGroup>
<Compile Include="DelegateTextWriter.cs" />
+ <Compile Include="Extensions\DataReaderExtension.cs" />
+ <Compile Include="Extensions\StringExtension.cs" />
+ <Compile Include="Extensions\SwitchExtensions.cs" />
<Compile Include="Models\Column.cs" />
<Compile Include="Models\ForeignKey.cs" />
<Compile Include="Models\IndexColumn.cs" />
@@ -71,6 +74,7 @@
<Name>FluentMigrator</Name>
</ProjectReference>
</ItemGroup>
+ <ItemGroup />
<Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
<!-- To modify your build process, add your task inside one of the targets below and uncomment it.
Other similar extension points exist, see Microsoft.Common.targets.
View
3  src/FluentMigrator.T4/Models/Column.cs
@@ -7,7 +7,8 @@ public class Column
{
public string Name;
public string PropertyName;
- public string PropertyType;
+ public System.Data.DbType? PropertyType;
+ public string CustomType { get; set; }
public bool IsPrimaryKey;
public bool IsNullable;
public bool IsAutoIncrement;
View
3  src/FluentMigrator.T4/Models/ForeignKey.cs
@@ -23,5 +23,8 @@ public ForeignKey()
public ICollection<string> ForeignColumns { get; set; }
public string PrimaryClass { get; set; }
+
+ public System.Data.Rule UpdateRule { get; set; }
+ public System.Data.Rule DeleteRule { get; set; }
}
}
View
173 src/FluentMigrator.T4/SchemaReaders/MySqlSchemaReader.cs
@@ -11,119 +11,124 @@ public class MySqlSchemaReader : SchemaReader
// SchemaReader.ReadSchema
public override Tables ReadSchema(DbConnection connection, DbProviderFactory factory)
{
- var result=new Tables();
-
+ var result = new Tables();
- var cmd=factory.CreateCommand();
- cmd.Connection=connection;
- cmd.CommandText=TABLE_SQL;
+
+ var cmd = factory.CreateCommand();
+ cmd.Connection = connection;
+ cmd.CommandText = TABLE_SQL;
//pull the tables in a reader
- using(cmd)
+ using (cmd)
{
- using (var rdr=cmd.ExecuteReader())
+ using (var rdr = cmd.ExecuteReader())
{
- while(rdr.Read())
+ while (rdr.Read())
{
- Table tbl=new Table();
- tbl.Name=rdr["TABLE_NAME"].ToString();
- tbl.Schema=rdr["TABLE_SCHEMA"].ToString();
- tbl.IsView=String.Compare(rdr["TABLE_TYPE"].ToString(), "View", true)==0;
- tbl.CleanName=CleanUp(tbl.Name);
- tbl.ClassName=Inflector.MakeSingular(tbl.CleanName);
+ Table tbl = new Table();
+ tbl.Name = rdr["TABLE_NAME"].ToString();
+ tbl.Schema = rdr["TABLE_SCHEMA"].ToString();
+ tbl.IsView = String.Compare(rdr["TABLE_TYPE"].ToString(), "View", true) == 0;
+ tbl.CleanName = CleanUp(tbl.Name);
+ tbl.ClassName = Inflector.MakeSingular(tbl.CleanName);
result.Add(tbl);
}
}
}
//this will return everything for the DB
- var schema = connection.GetSchema("COLUMNS");
+ var schema = connection.GetSchema("COLUMNS");
//loop again - but this time pull by table name
- foreach (var item in result)
+ foreach (var item in result)
{
- item.Columns=new List<Column>();
+ item.Columns = new List<Column>();
//pull the columns from the schema
var columns = schema.Select("TABLE_NAME='" + item.Name + "'");
- foreach (var row in columns)
+ foreach (var row in columns)
{
- Column col=new Column();
- col.Name=row["COLUMN_NAME"].ToString();
- col.PropertyName=CleanUp(col.Name);
- col.PropertyType=GetPropertyType(row);
- col.Size=GetDatatypeSize(row["DATA_TYPE"].ToString());
- col.Precision=GetDatatypePrecision(row["DATA_TYPE"].ToString());
- col.IsNullable=row["IS_NULLABLE"].ToString()=="YES";
- col.IsPrimaryKey=row["COLUMN_KEY"].ToString()=="PRI";
- col.IsAutoIncrement=row["extra"].ToString().ToLower().IndexOf("auto_increment")>=0;
+ var type = GetPropertyType(row);
+ Column col = new Column();
+ col.Name = row["COLUMN_NAME"].ToString();
+ col.PropertyName = CleanUp(col.Name);
+ col.PropertyType = type;
+ col.CustomType = type == null
+ ? row["DATA_TYPE"].ToString().ToLowerInvariant()
+ : null;
+ col.Size = GetDatatypeSize(row["DATA_TYPE"].ToString());
+ col.Precision = GetDatatypePrecision(row["DATA_TYPE"].ToString());
+ col.IsNullable = row["IS_NULLABLE"].ToString() == "YES";
+ col.IsPrimaryKey = row["COLUMN_KEY"].ToString() == "PRI";
+ col.IsAutoIncrement = row["extra"].ToString().ToLower().IndexOf("auto_increment") >= 0;
item.Columns.Add(col);
}
}
-
+
return result;
-
+
}
- static string GetPropertyType(DataRow row)
- {
- bool bUnsigned = row["COLUMN_TYPE"].ToString().IndexOf("unsigned")>=0;
- string propType="string";
- switch (row["DATA_TYPE"].ToString())
+ private static readonly IDictionary<string, DbType?> _typeMap =
+ new Dictionary<string, DbType?>()
{
- case "bigint":
- propType= bUnsigned ? "ulong" : "long";
- break;
- case "int":
- propType= bUnsigned ? "uint" : "int";
- break;
- case "smallint":
- propType= bUnsigned ? "ushort" : "short";
- break;
- case "guid":
- propType= "Guid";
- break;
- case "smalldatetime":
- case "date":
- case "datetime":
- case "timestamp":
- propType= "DateTime";
- break;
- case "float":
- propType="float";
- break;
- case "double":
- propType="double";
- break;
- case "numeric":
- case "smallmoney":
- case "decimal":
- case "money":
- propType= "decimal";
- break;
- case "bit":
- case "bool":
- case "boolean":
- propType= "bool";
- break;
- case "tinyint":
- propType = bUnsigned ? "byte" : "sbyte";
- break;
- case "image":
- case "binary":
- case "blob":
- case "mediumblob":
- case "longblob":
- case "varbinary":
- propType= "byte[]";
- break;
-
- }
- return propType;
+ {"bigint", DbType.Int64}
+ ,{"ubigint", DbType.UInt64}
+ ,{"smallint",DbType.Int16}
+ ,{"usmallint",DbType.UInt16}
+ ,{"int",DbType.Int32}
+ ,{"uint",DbType.UInt32}
+ ,{"guid",DbType.Guid}
+ ,{"smalldatetime",DbType.DateTime}
+ ,{"datetime",DbType.DateTime}
+ ,{"datetime2",DbType.DateTime2}
+ ,{"date",DbType.Date}
+ ,{"time",DbType.Time}
+ ,{"timestamp",DbType.Byte}//TODO: CHECK
+ ,{"float",DbType.Double}
+ ,{"double",DbType.Double}
+ ,{"numeric",DbType.Decimal}
+ ,{"smallmoney",DbType.Decimal}
+ ,{"decimal",DbType.Decimal}
+ ,{"money",DbType.Currency}
+ ,{"binary",DbType.Binary}
+ ,{"bit",DbType.Boolean}
+ ,{"bool",DbType.Boolean}
+ ,{"boolean",DbType.Boolean}
+ ,{"tinyint",DbType.Byte}
+ ,{"utinyint",DbType.SByte}
+ ,{"image",DbType.Binary}
+ ,{"binary",DbType.Binary}
+ ,{"blob",DbType.Binary}
+ ,{"mediumblob",DbType.Binary}
+ ,{"longblob",DbType.Binary}
+ ,{"varbinary",DbType.Binary}
+ ,{"char",DbType.AnsiStringFixedLength}
+ ,{"varchar",DbType.AnsiString}
+ ,{"text",DbType.AnsiString}
+ ,{"nchar",DbType.StringFixedLength}
+ ,{"nvarchar",DbType.String}
+ ,{"ntext",DbType.String}
+
+ };
+ static DbType? GetPropertyType(string sqlType)
+ {
+ var sysType = default(DbType?);
+ _typeMap.TryGetValue(sqlType, out sysType);
+ return sysType;
+ }
+
+ static DbType? GetPropertyType(DataRow row)
+ {
+ var sing = row["COLUMN_TYPE"].ToString().IndexOf("unsigned") >= 0 ? "u" : string.Empty;
+ var typeName = sing + row["DATA_TYPE"].ToString().ToLowerInvariant();
+ var type = default(DbType?);
+ _typeMap.TryGetValue(typeName, out type);
+ return type;
}
- const string TABLE_SQL=@"
+ const string TABLE_SQL = @"
SELECT *
FROM information_schema.tables
WHERE ((table_type='BASE TABLE' OR table_type='VIEW') AND table_schema <> 'mysql')
View
40 src/FluentMigrator.T4/SchemaReaders/OracleSchemaReader.cs
@@ -80,10 +80,14 @@ List<Column> LoadColumns(Table tbl)
{
while(rdr.Read())
{
+ var type = this.GetPropertyType(rdr["DataType"].ToString(), (rdr["DataType"] == DBNull.Value ? null : rdr["DataType"].ToString()));
Column col=new Column();
col.Name=rdr["ColumnName"].ToString();
- col.PropertyName=CleanUp(col.Name);
- col.PropertyType=this.GetPropertyType(rdr["DataType"].ToString(), (rdr["DataType"] == DBNull.Value ? null : rdr["DataType"].ToString()));
+ col.PropertyName = CleanUp(col.Name);
+ col.PropertyType = type;
+ col.CustomType = type == null
+ ? rdr["DataType"].ToString().ToLowerInvariant()
+ : null;
col.Size=GetDatatypeSize(rdr["DataType"].ToString());
col.Precision=GetDatatypePrecision(rdr["DataType"].ToString());
col.IsNullable=rdr["IsNullable"].ToString()=="YES";
@@ -136,55 +140,57 @@ List<ForeignKey> LoadFKeys(string tblName)
return "";
}
- string GetPropertyType(string sqlType, string dataScale)
+ System.Data.DbType? GetPropertyType(string sqlType, string dataScale)
{
- string sysType="string";
+ var sysType=System.Data.DbType.String;
switch (sqlType.ToLower())
{
case "bigint":
- sysType = "long";
+ sysType = System.Data.DbType.Int64;
break;
case "smallint":
- sysType= "short";
+ sysType = System.Data.DbType.Int16;
break;
case "int":
- sysType= "int";
+ sysType = System.Data.DbType.Int32;
break;
case "uniqueidentifier":
- sysType= "Guid";
+ sysType = System.Data.DbType.Guid;
break;
case "smalldatetime":
case "datetime":
case "date":
- sysType= "DateTime";
+ sysType = System.Data.DbType.DateTime;
break;
case "float":
- sysType="double";
+ sysType = System.Data.DbType.Double;
break;
case "real":
case "numeric":
- case "smallmoney":
case "decimal":
- case "money":
case "number":
- sysType= "decimal";
+ sysType= System.Data.DbType.Decimal;
+ break;
+ case "money":
+ case "smallmoney":
+ sysType = System.Data.DbType.Currency;
break;
case "tinyint":
- sysType = "byte";
+ sysType = System.Data.DbType.Byte;
break;
case "bit":
- sysType= "bool";
+ sysType= System.Data.DbType.Boolean;
break;
case "image":
case "binary":
case "varbinary":
case "timestamp":
- sysType= "byte[]";
+ sysType = System.Data.DbType.Binary;
break;
}
if (sqlType == "number" && dataScale == "0")
- return "long";
+ return System.Data.DbType.Int64;
return sysType;
}
View
46 src/FluentMigrator.T4/SchemaReaders/PostGreSqlSchemaReader.cs
@@ -77,10 +77,14 @@ List<Column> LoadColumns(Table tbl)
{
while(rdr.Read())
{
+ var type = GetPropertyType(rdr["udt_name"].ToString());
Column col=new Column();
col.Name=rdr["column_name"].ToString();
col.PropertyName=CleanUp(col.Name);
- col.PropertyType=this.GetPropertyType(rdr["udt_name"].ToString());
+ col.PropertyType = type;
+ col.CustomType = type == null
+ ? rdr["udt_name"].ToString().ToLowerInvariant()
+ : null;
col.Size=GetDatatypeSize(rdr["udt_name"].ToString());
col.Precision=GetDatatypePrecision(rdr["udt_name"].ToString());
col.IsNullable=rdr["is_nullable"].ToString()=="YES";
@@ -133,48 +137,48 @@ List<ForeignKey> LoadFKeys(string tblName)
return "";
}
- string GetPropertyType(string sqlType)
+ static DbType? GetPropertyType(string sqlType)
{
switch (sqlType)
{
case "int8":
- case "serial8":
- return "long";
+ case "serial8":
+ return DbType.Int64;
- case "bool":
- return "bool";
+ case "bool":
+ return DbType.Boolean;
- case "bytea ":
- return "byte[]";
+ case "bytea ":
+ return DbType.Binary;
- case "float8":
- return "double";
+ case "float8":
+ return DbType.Double;
case "int4":
- case "serial4":
- return "int";
+ case "serial4":
+ return DbType.Int32;
- case "money ":
- return "decimal";
+ case "money ":
+ return DbType.Currency;
- case "numeric":
- return "decimal";
+ case "numeric":
+ return DbType.Decimal;
- case "float4":
- return "float";
+ case "float4":
+ return DbType.Decimal;
case "int2":
- return "short";
+ return DbType.Int16;
case "time":
case "timetz":
case "timestamp":
case "timestamptz":
case "date":
- return "DateTime";
+ return DbType.DateTime;
default:
- return "string";
+ return DbType.String;
}
}
View
91 src/FluentMigrator.T4/SchemaReaders/SqlServerCeSchemaReader.cs
@@ -77,10 +77,14 @@ List<Column> LoadColumns(Table tbl)
{
while(rdr.Read())
{
+ var type = GetPropertyType(rdr["DataType"].ToString());
Column col=new Column();
col.Name=rdr["ColumnName"].ToString();
col.PropertyName=CleanUp(col.Name);
- col.PropertyType=this.GetPropertyType(rdr["DataType"].ToString());
+ col.PropertyType=type;
+ col.CustomType = type == null
+ ? rdr["DataType"].ToString().ToLowerInvariant()
+ : null;
col.Size=GetDatatypeSize(rdr["DataType"].ToString());
col.Precision=GetDatatypePrecision(rdr["DataType"].ToString());
col.IsNullable=rdr["IsNullable"].ToString()=="YES";
@@ -132,55 +136,44 @@ List<ForeignKey> LoadFKeys(string tblName)
return "";
}
-
- string GetPropertyType(string sqlType)
- {
- string sysType="string";
- switch (sqlType)
+
+ private static readonly IDictionary<string, DbType?> _typeMap =
+ new Dictionary<string, DbType?>()
{
- case "bigint":
- sysType = "long";
- break;
- case "smallint":
- sysType= "short";
- break;
- case "int":
- sysType= "int";
- break;
- case "uniqueidentifier":
- sysType= "Guid";
- break;
- case "smalldatetime":
- case "datetime":
- case "date":
- case "time":
- sysType= "DateTime";
- break;
- case "float":
- sysType="double";
- break;
- case "real":
- sysType="float";
- break;
- case "numeric":
- case "smallmoney":
- case "decimal":
- case "money":
- sysType= "decimal";
- break;
- case "tinyint":
- sysType = "byte";
- break;
- case "bit":
- sysType= "bool";
- break;
- case "image":
- case "binary":
- case "varbinary":
- case "timestamp":
- sysType= "byte[]";
- break;
- }
+ {"bigint", DbType.Int64}
+ ,{"smallint",DbType.Int16}
+ ,{"int",DbType.Int32}
+ ,{"uniqueidentifier",DbType.Guid}
+ ,{"smalldatetime",DbType.DateTime}
+ ,{"datetime",DbType.DateTime}
+ ,{"datetime2",DbType.DateTime2}
+ ,{"date",DbType.Date}
+ ,{"time",DbType.Time}
+ ,{"float",DbType.Double}
+ ,{"real",DbType.Single}
+ ,{"numeric",DbType.Decimal}
+ ,{"smallmoney",DbType.Decimal}
+ ,{"decimal",DbType.Decimal}
+ ,{"money",DbType.Currency}
+ ,{"tinyint",DbType.Byte}
+ ,{"image",DbType.Binary}
+ ,{"binary",DbType.Binary}
+ ,{"varbinary",DbType.Binary}
+ ,{"bit",DbType.Boolean}
+ ,{"datetimeoffset",DbType.DateTimeOffset}
+ ,{"tinyint",DbType.Byte}
+ ,{"char",DbType.AnsiStringFixedLength}
+ ,{"varchar",DbType.AnsiString}
+ ,{"text",DbType.AnsiString}
+ ,{"nchar",DbType.StringFixedLength}
+ ,{"nvarchar",DbType.String}
+ ,{"ntext",DbType.String}
+
+ };
+ static DbType? GetPropertyType(string sqlType)
+ {
+ var sysType = default(DbType?);
+ _typeMap.TryGetValue(sqlType, out sysType);
return sysType;
}
View
256 src/FluentMigrator.T4/SchemaReaders/SqlServerSchemaReader.cs
@@ -11,8 +11,8 @@ class SqlServerSchemaReader : SchemaReader
// SchemaReader.ReadSchema
public override Tables ReadSchema(DbConnection connection, DbProviderFactory factory)
{
- var result=new Tables();
-
+ var result = new Tables();
+
this._connection = connection;
this._factory = factory;
@@ -22,14 +22,14 @@ public override Tables ReadSchema(DbConnection connection, DbProviderFactory fac
cmd.Connection = connection;
cmd.CommandText = TableSql;
- using (var rdr=cmd.ExecuteReader())
+ using (var rdr = cmd.ExecuteReader())
{
- while(rdr.Read())
+ while (rdr.Read())
{
Table tbl = new Table();
tbl.Name = rdr["TABLE_NAME"].ToString();
tbl.Schema = rdr["TABLE_SCHEMA"].ToString();
- tbl.IsView = String.Compare(rdr["TABLE_TYPE"].ToString(), "View", true)==0;
+ tbl.IsView = String.Compare(rdr["TABLE_TYPE"].ToString(), "View", true) == 0;
tbl.CleanName = CleanUp(tbl.Name);
tbl.ClassName = Inflector.MakeSingular(tbl.CleanName);
@@ -42,55 +42,60 @@ public override Tables ReadSchema(DbConnection connection, DbProviderFactory fac
{
tbl.Columns = this.LoadColumns(tbl);
tbl.Indexes = this.LoadIndices(tbl);
- tbl.ForeignKeys = this.LoadForeignKeys(tbl);
-
+ tbl.ForeignKeys = this.LoadForeignKeys(tbl);
+
// Mark the primary key
- var primaryKey = this.GetPrimaryKey(tbl.Name).Select(c=>c.ToLowerInvariant());
+ var primaryKey = this.GetPrimaryKey(tbl.Name).Select(c => c.ToLowerInvariant());
var primaryKeyColumns = tbl.Columns.Where(c => primaryKey.Contains(c.Name.ToLowerInvariant()));
foreach (var column in primaryKeyColumns)
column.IsPrimaryKey = true;
}
-
+
return result;
}
-
+
DbConnection _connection;
DbProviderFactory _factory;
-
+
List<Column> LoadColumns(Table tbl)
{
-
- using (var cmd=this._factory.CreateCommand())
+
+ using (var cmd = this._factory.CreateCommand())
{
- cmd.Connection=this._connection;
- cmd.CommandText=ColumnSql;
+ cmd.Connection = this._connection;
+ cmd.CommandText = ColumnSql;
var p = cmd.CreateParameter();
p.ParameterName = "@tableName";
- p.Value=tbl.Name;
+ p.Value = tbl.Name;
cmd.Parameters.Add(p);
p = cmd.CreateParameter();
p.ParameterName = "@schemaName";
- p.Value=tbl.Schema;
+ p.Value = tbl.Schema;
cmd.Parameters.Add(p);
- var result=new List<Column>();
- using (IDataReader rdr=cmd.ExecuteReader())
+ var result = new List<Column>();
+ using (IDataReader rdr = cmd.ExecuteReader())
{
- while(rdr.Read())
+ while (rdr.Read())
{
- Column col=new Column();
- col.Name=rdr["ColumnName"].ToString();
- col.PropertyName=CleanUp(col.Name);
- col.PropertyType=GetPropertyType(rdr["DataType"].ToString());
- col.Size=GetDatatypeSize(rdr["DataType"].ToString());
- col.Precision=GetDatatypePrecision(rdr["DataType"].ToString());
- col.IsNullable=rdr["IsNullable"].ToString()=="YES";
- col.IsAutoIncrement=((int)rdr["IsIdentity"])==1;
+ var type = GetPropertyType(rdr["DataType"].ToString());
+ Column col = new Column();
+ col.Name = rdr["ColumnName"].ToString();
+ col.PropertyName = CleanUp(col.Name);
+ col.PropertyType = type;
+ col.CustomType = type == null
+ ? rdr["DataType"].ToString().ToLowerInvariant()
+ : null;
+ col.Size = rdr.Get("MaxLength", -1);
+ col.Precision = rdr.Get("Precision", -1);
+ col.IsNullable = rdr["IsNullable"].ToString() == "YES";
+ col.IsAutoIncrement = ((int)rdr["IsIdentity"]) == 1;
+ col.DefaultValue = rdr.IsDBNull(5) ? null : rdr["DefaultSetting"].ToString();
result.Add(col);
}
}
@@ -107,55 +112,57 @@ List<TableIndex> LoadIndices(Table tbl)
I.[is_unique_constraint], I.[fill_factor], I.[is_padded], I.[is_disabled], I.[is_hypothetical],
I.[allow_row_locks], I.[allow_page_locks], IC.[is_descending_key], IC.[is_included_column]
FROM sys.[tables] AS T
- INNER JOIN sys.[indexes] I ON T.[object_id] = I.[object_id]
- INNER JOIN sys.[index_columns] IC ON I.[object_id] = IC.[object_id]
+ INNER JOIN sys.[indexes] I ON T.[object_id] = I.[object_id]
+ INNER JOIN sys.[index_columns] IC ON I.[object_id] = IC.[object_id] AND I.index_id = IC.index_id
INNER JOIN sys.[all_columns] AC ON T.[object_id] = AC.[object_id] AND IC.[column_id] = AC.[column_id]
WHERE T.[is_ms_shipped] = 0 AND I.[type_desc] <> 'HEAP'
AND I.is_primary_key = 0 AND T.[name] = @tableName and OBJECT_SCHEMA_NAME(T.[object_id],DB_ID()) = @schemaName";
- using (var cmd=this._factory.CreateCommand())
+ using (var cmd = this._factory.CreateCommand())
{
- cmd.Connection=this._connection;
- cmd.CommandText=sql;
+ cmd.Connection = this._connection;
+ cmd.CommandText = sql;
var p = cmd.CreateParameter();
p.ParameterName = "@tableName";
- p.Value=tbl.Name;
+ p.Value = tbl.Name;
cmd.Parameters.Add(p);
p = cmd.CreateParameter();
p.ParameterName = "@schemaName";
- p.Value=tbl.Schema;
+ p.Value = tbl.Schema;
cmd.Parameters.Add(p);
- var result=new List<TableIndex>();
+ var result = new List<TableIndex>();
- using (IDataReader rdr=cmd.ExecuteReader())
+ using (IDataReader rdr = cmd.ExecuteReader())
{
- while(rdr.Read()){
-
- string thisTable=rdr["table_name"].ToString();
-
- if(tbl.Name.ToLower()==thisTable.ToLower()){
+ while (rdr.Read())
+ {
+
+ string thisTable = rdr["table_name"].ToString();
+
+ if (tbl.Name.ToLower() == thisTable.ToLower())
+ {
var indexName = rdr["index_name"].ToString();
- if(!result.Exists(i => i.Name == indexName))
+ if (!result.Exists(i => i.Name == indexName))
{
- TableIndex index=new TableIndex();
- index.Name= indexName;
- index.IsUnique=rdr.GetBoolean(rdr.GetOrdinal("is_unique"));
+ TableIndex index = new TableIndex();
+ index.Name = indexName;
+ index.IsUnique = rdr.GetBoolean(rdr.GetOrdinal("is_unique"));
index.IndexColumns = new List<IndexColumn>();
- index.IndexColumns.Add(new IndexColumn { Name = rdr["column_name"].ToString(), IsAsc = !rdr.GetBoolean(rdr.GetOrdinal("is_descending_key"))});
+ index.IndexColumns.Add(new IndexColumn { Name = rdr["column_name"].ToString(), IsAsc = !rdr.GetBoolean(rdr.GetOrdinal("is_descending_key")) });
result.Add(index);
}
else
{
- result.Single(i => i.Name == indexName).IndexColumns.Add(new IndexColumn { Name = rdr["column_name"].ToString(), IsAsc = !rdr.GetBoolean(rdr.GetOrdinal("is_descending_key"))});
+ result.Single(i => i.Name == indexName).IndexColumns.Add(new IndexColumn { Name = rdr["column_name"].ToString(), IsAsc = !rdr.GetBoolean(rdr.GetOrdinal("is_descending_key")) });
}
}
-
+
}
}
- return result;
+ return result;
}
}
@@ -176,20 +183,22 @@ List<ForeignKey> LoadForeignKeys(Table tbl)
p.Value = tbl.Schema;
cmd.Parameters.Add(p);
- var keys = cmd.Select(reader => new {
+ var keys = cmd.Select(reader => new
+ {
ForeignConstraintName = reader["ForeignConstraintName"].ToString(),
- ForeignTableSchema = reader["ForeignTableSchema"].ToString(),
- ForeignTable = reader["ForeignTable"].ToString(),
- ForeignColumn = reader["ForeignColumn"].ToString(),
+ ForeignTableSchema = reader["ForeignTableSchema"].ToString(),
+ ForeignTable = reader["ForeignTable"].ToString(),
+ ForeignColumn = reader["ForeignColumn"].ToString(),
PrimaryConstraintName = reader["PrimaryConstraintName"].ToString(),
- PrimaryTableSchema = reader["PrimaryTableSchema"].ToString(),
- PrimaryTable = reader["PrimaryTable"].ToString(),
- PrimaryColumn = reader["PrimaryColumn"].ToString(),
- UpdateRule = reader["UpdateRule"].ToString(),
- DeleteRule = reader["DeleteRule"].ToString(),
+ PrimaryTableSchema = reader["PrimaryTableSchema"].ToString(),
+ PrimaryTable = reader["PrimaryTable"].ToString(),
+ PrimaryColumn = reader["PrimaryColumn"].ToString(),
+ UpdateRule = DecodeRule(reader.Get<string>("UpdateRule")),
+ DeleteRule = DecodeRule(reader.Get<string>("DeleteRule")),
});
- return keys.GroupBy(key => new {
+ return keys.GroupBy(key => new
+ {
key.ForeignConstraintName,
key.ForeignTableSchema,
key.ForeignTable,
@@ -197,7 +206,8 @@ List<ForeignKey> LoadForeignKeys(Table tbl)
key.PrimaryTable,
key.UpdateRule,
key.DeleteRule
- }).Select(foreignKeyGrouping => new ForeignKey {
+ }).Select(foreignKeyGrouping => new ForeignKey
+ {
Name = foreignKeyGrouping.Key.ForeignConstraintName,
ForeignTable = foreignKeyGrouping.Key.ForeignTable,
ForeignTableSchema = foreignKeyGrouping.Key.ForeignTableSchema,
@@ -205,11 +215,13 @@ List<ForeignKey> LoadForeignKeys(Table tbl)
PrimaryTable = foreignKeyGrouping.Key.PrimaryTable,
PrimaryTableSchema = foreignKeyGrouping.Key.PrimaryTableSchema,
PrimaryColumns = foreignKeyGrouping.Select(f => f.PrimaryColumn).ToList(),
- PrimaryClass = Inflector.MakeSingular(CleanUp(foreignKeyGrouping.Key.PrimaryTable))
+ PrimaryClass = Inflector.MakeSingular(CleanUp(foreignKeyGrouping.Key.PrimaryTable)),
+ UpdateRule = foreignKeyGrouping.Key.UpdateRule,
+ DeleteRule = foreignKeyGrouping.Key.DeleteRule
}).ToList();
- }
+ }
}
-
+
IEnumerable<string> GetPrimaryKey(string table)
{
using (var cmd = this._factory.CreateCommand())
@@ -226,63 +238,54 @@ IEnumerable<string> GetPrimaryKey(string table)
}
}
- static string GetPropertyType(string sqlType)
- {
- string sysType="string";
- switch (sqlType)
+ private static readonly IDictionary<string, DbType?> _typeMap =
+ new Dictionary<string, DbType?>()
{
- case "bigint":
- sysType = "long";
- break;
- case "smallint":
- sysType= "short";
- break;
- case "int":
- sysType= "int";
- break;
- case "uniqueidentifier":
- sysType= "Guid";
- break;
- case "smalldatetime":
- case "datetime":
- case "date":
- case "time":
- sysType= "DateTime";
- break;
- case "float":
- sysType="double";
- break;
- case "real":
- sysType="float";
- break;
- case "numeric":
- case "smallmoney":
- case "decimal":
- case "money":
- sysType= "decimal";
- break;
- case "tinyint":
- sysType = "byte";
- break;
- case "bit":
- sysType= "bool";
- break;
- case "image":
- case "binary":
- case "varbinary":
- case "timestamp":
- sysType= "byte[]";
- break;
- case "geography":
- sysType = "Microsoft.SqlServer.Types.SqlGeography";
- break;
- case "geometry":
- sysType = "Microsoft.SqlServer.Types.SqlGeometry";
- break;
- }
+ {"bigint", DbType.Int64}
+ ,{"smallint",DbType.Int16}
+ ,{"int",DbType.Int32}
+ ,{"uniqueidentifier",DbType.Guid}
+ ,{"smalldatetime",DbType.DateTime}
+ ,{"datetime",DbType.DateTime}
+ ,{"datetime2",DbType.DateTime2}
+ ,{"date",DbType.Date}
+ ,{"time",DbType.Time}
+ ,{"float",DbType.Double}
+ ,{"real",DbType.Single}
+ ,{"numeric",DbType.Decimal}
+ ,{"smallmoney",DbType.Currency}
+ ,{"money",DbType.Currency}
+ ,{"decimal",DbType.Decimal}
+ ,{"tinyint",DbType.Byte}
+ ,{"image",DbType.Binary}
+ ,{"binary",DbType.Binary}
+ ,{"varbinary",DbType.Binary}
+ ,{"bit",DbType.Boolean}
+ ,{"datetimeoffset",DbType.DateTimeOffset}
+ ,{"char",DbType.AnsiStringFixedLength}
+ ,{"varchar",DbType.AnsiString}
+ ,{"text",DbType.AnsiString}
+ ,{"nchar",DbType.StringFixedLength}
+ ,{"nvarchar",DbType.String}
+ ,{"ntext",DbType.String}
+
+ };
+ static DbType? GetPropertyType(string sqlType)
+ {
+ var sysType = default(DbType?);
+ _typeMap.TryGetValue(sqlType, out sysType);
return sysType;
}
+ private static System.Data.Rule DecodeRule(string rule)
+ {
+ return new Switch<string, System.Data.Rule>(rule)
+ .Case("CASCADE", System.Data.Rule.Cascade)
+ .Case("SET NULL",System.Data.Rule.SetDefault)
+ .Case("SET DEFAULT", System.Data.Rule.SetNull)
+ .Default(System.Data.Rule.None);
+ }
+
const string PrimaryKeySql = @"SELECT c.name AS ColumnName
FROM sys.indexes AS i
INNER JOIN sys.index_columns AS ic ON i.object_id = ic.object_id AND i.index_id = ic.index_id
@@ -290,11 +293,11 @@ static string GetPropertyType(string sqlType)
LEFT OUTER JOIN sys.columns AS c ON ic.object_id = c.object_id AND c.column_id = ic.column_id
WHERE (i.type = 1) AND (o.name = @tableName)";
- const string TableSql=@"SELECT *
+ const string TableSql = @"SELECT *
FROM INFORMATION_SCHEMA.TABLES
WHERE TABLE_TYPE='BASE TABLE' OR TABLE_TYPE='VIEW'";
- const string ColumnSql=@"SELECT
+ const string ColumnSql = @"SELECT
TABLE_CATALOG AS [Database],
TABLE_SCHEMA AS Owner,
TABLE_NAME AS TableName,
@@ -302,8 +305,8 @@ FROM INFORMATION_SCHEMA.TABLES
ORDINAL_POSITION AS OrdinalPosition,
COLUMN_DEFAULT AS DefaultSetting,
IS_NULLABLE AS IsNullable, DATA_TYPE AS DataType,
- CHARACTER_MAXIMUM_LENGTH AS MaxLength,
- DATETIME_PRECISION AS DatePrecision,
+ ISNULL(CHARACTER_MAXIMUM_LENGTH,CAST(NUMERIC_PRECISION as Int)) AS MaxLength,
+ NUMERIC_SCALE AS Precision,
COLUMNPROPERTY(object_id('[' + TABLE_SCHEMA + '].[' + TABLE_NAME + ']'), COLUMN_NAME, 'IsIdentity') AS IsIdentity,
COLUMNPROPERTY(object_id('[' + TABLE_SCHEMA + '].[' + TABLE_NAME + ']'), COLUMN_NAME, 'IsComputed') as IsComputed
FROM INFORMATION_SCHEMA.COLUMNS
@@ -335,11 +338,12 @@ FROM INFORMATION_SCHEMA.COLUMNS
WHERE
(FK.CONSTRAINT_TYPE = 'FOREIGN KEY')
AND (FK.TABLE_NAME=@tableName)
- AND (FK.TABLE_SCHEMA=@schemaName)";
+ AND (FK.TABLE_SCHEMA=@schemaName)
+ ORDER BY ForeignConstraintName, ForeignTableSchema, ForeignTable, FKC.ORDINAL_POSITION";
}
- public static class DbDataReaderExtensions
- {
+ public static class DbDataReaderExtensions
+ {
public static IEnumerable<T> Select<T>(this DbDataReader reader, Func<DbDataReader, T> selector)
{
while (reader.Read())
@@ -349,7 +353,7 @@ public static IEnumerable<T> Select<T>(this DbDataReader reader, Func<DbDataRead
public static IEnumerable<T> Select<T>(this DbCommand command, Func<DbDataReader, T> selector)
{
using (var reader = command.ExecuteReader())
- return reader.Select(selector).ToList();
- }
+ return reader.Select(selector).ToList();
+ }
}
}
View
41 src/FluentMigrator.T4/SchemaReaders/SqliteSchemaReader.cs
@@ -60,10 +60,14 @@ List<Column> LoadColumns(Table tbl)
{
while(rdr.Read())
{
+ var type=this.GetPropertyType(rdr["type"].ToString(), (rdr["type"] == DBNull.Value ? null : rdr["type"].ToString()));
Column col=new Column();
col.Name=rdr["name"].ToString();
col.PropertyName=CleanUp(col.Name);
- col.PropertyType=this.GetPropertyType(rdr["type"].ToString(), (rdr["type"] == DBNull.Value ? null : rdr["type"].ToString()));
+ col.PropertyType= type;
+ col.CustomType = type == null
+ ? rdr["type"].ToString().ToLowerInvariant()
+ : null;
col.Size=GetDatatypeSize(rdr["type"].ToString());
col.Precision=GetDatatypePrecision(rdr["type"].ToString());
col.IsNullable=rdr["notnull"].ToString()=="0";
@@ -142,10 +146,11 @@ List<ForeignKey> LoadForeignKeys(string tblName)
}
}
+
- string GetPropertyType(string sqlType, string dataScale)
+ DbType? GetPropertyType(string sqlType, string dataScale)
{
- string sysType="string";
+ var sysType=default(DbType?);
switch (sqlType.ToLower())
{
case "integer":
@@ -154,48 +159,48 @@ string GetPropertyType(string sqlType, string dataScale)
case "smallint":
case "mediumint":
case "int2":
- case "int8":
- sysType= "long";
+ case "int8":
+ sysType = DbType.Int64;
break;
case "bigint":
case "unsigned big int":
- sysType= "long";
+ sysType= DbType.UInt64;
break;
case "uniqueidentifier":
- sysType= "Guid";
+ sysType = DbType.Guid;
break;
case "smalldatetime":
case "datetime":
case "date":
- sysType= "DateTime";
+ sysType= DbType.DateTime;
break;
case "float":
case "double precision":
case "double":
- sysType="double";
+ sysType = DbType.Double;
break;
case "real":
case "numeric":
- case "smallmoney":
case "decimal":
- case "money":
case "number":
- sysType= "decimal";
+ sysType = DbType.Single;
+ break;
+ case "smallmoney":
+ case "money":
+ sysType = DbType.Currency;
break;
case "bit":
- sysType= "bool";
+ sysType = DbType.Boolean;
break;
case "image":
case "binary":
case "varbinary":
case "timestamp":
- sysType= "byte[]";
+ sysType= DbType.Binary;
break;
- }
-
+ }
if (sqlType == "number" && dataScale == "0")
- return "long";
-
+ return DbType.Int64;
return sysType;
}
Something went wrong with that request. Please try again.