Skip to content

Instantly share code, notes, and snippets.

@pauldbau
Created March 17, 2012 20:25
Show Gist options
  • Save pauldbau/2064942 to your computer and use it in GitHub Desktop.
Save pauldbau/2064942 to your computer and use it in GitHub Desktop.
Quick and dirty VARCHAR(MAX) implementation for Ormlite's SQL Server provider. Any property marked with [StringLength(<value>)] is created as a VARCHAR(MAX) column when <value> exceeds 8000
public class MySqlServerOrmLiteDialectProvider :
SqlServerOrmLiteDialectProvider
{
public static new MySqlServerOrmLiteDialectProvider Instance = new MySqlServerOrmLiteDialectProvider();
public override string GetColumnDefinition(string fieldName, Type fieldType, bool isPrimaryKey, bool autoIncrement, bool isNullable, int? fieldLength, int? scale, string defaultValue)
{
string fieldDefinition;
// Begin: Override edit
if (fieldType == typeof(string))
{
string colLength = null;
var intVal = fieldLength.GetValueOrDefault(DefaultStringLength);
// SQL Server max int value for varchar datatype is 8000.
// So move up to the MAX option if > 8000
if (intVal > 8000)
colLength = "MAX";
else
colLength = intVal.ToString();
fieldDefinition = string.Format(StringLengthColumnDefinitionFormat, colLength);
}
// End: Override edit
else
{
if (!DbTypes.ColumnTypeMap.TryGetValue(fieldType, out fieldDefinition))
{
fieldDefinition = this.GetUndefinedColumnDefinition(fieldType, fieldLength);
}
}
var sql = new StringBuilder();
sql.AppendFormat("{0} {1}", GetQuotedColumnName(fieldName), fieldDefinition);
if (isPrimaryKey)
{
sql.Append(" PRIMARY KEY");
if (autoIncrement)
{
sql.Append(" ").Append(AutoIncrementDefinition);
}
}
else
{
if (isNullable)
{
sql.Append(" NULL");
}
else
{
sql.Append(" NOT NULL");
}
}
if (!string.IsNullOrEmpty(defaultValue))
{
sql.AppendFormat(DefaultValueFormat, defaultValue);
}
return sql.ToString();
}
}
@dotnetchris
Copy link

That's really confusing to see MySql! Had to read this like 8 times to realize it was indeed SqlServer.

Shorter implementation is:

public override string GetColumnDefinition(string fieldName, Type fieldType, bool isPrimaryKey,
    bool autoIncrement, bool isNullable, int? fieldLength, int? scale, string defaultValue)
{
    var fieldDefinition = base.GetColumnDefinition(fieldName, fieldType, isPrimaryKey, 
                                  autoIncrement, isNullable, fieldLength, scale, defaultValue);

    if (fieldType == typeof (string) && fieldLength > 8000)
    {
        var orig = string.Format(StringLengthColumnDefinitionFormat, fieldLength);
        var max = string.Format(StringLengthColumnDefinitionFormat, "MAX");

        fieldDefinition = fieldDefinition.Replace(orig, max);
    }

    return fieldDefinition;
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment