Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

user defined types #16

Merged
merged 3 commits into from
May 19, 2016
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
22 changes: 0 additions & 22 deletions console/Create.cs
Original file line number Diff line number Diff line change
Expand Up @@ -16,28 +16,6 @@ public Create()
public override int Run(string[] remainingArguments) {
_logger = new Logger(Verbose);

if (!Directory.Exists(ScriptDir))
{
_logger.Log(TraceLevel.Error, string.Format("Snapshot dir {0} does not exist.", ScriptDir));
return 1;
}

if (!Overwrite)
{
_logger.Log(TraceLevel.Verbose, "Checking if database already exists...");
if (DBHelper.DbExists(ConnectionString))
{
var question = string.Format("{0} {1} already exists - do you want to drop it",
Server, DbName);
if (!ConsoleQuestion.AskYN(question))
{
Console.WriteLine("Create command cancelled.");
return 1;
}
Overwrite = true;
}
}

var createCommand = new CreateCommand
{
ConnectionString = ConnectionString,
Expand Down
45 changes: 43 additions & 2 deletions model/Models/Database.cs
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,8 @@
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Xml.Schema;
using Microsoft.SqlServer.Server;

namespace SchemaZen.Library.Models {
public class Database {
Expand Down Expand Up @@ -76,6 +78,7 @@ public Database(string name, IList<string> filteredTypes = null)
public List<Synonym> Synonyms = new List<Synonym>();
public List<Table> TableTypes = new List<Table>();
public List<Table> Tables = new List<Table>();
public List<UserDefinedType> UserDefinedTypes = new List<UserDefinedType>();
public List<Role> Roles = new List<Role>();
public List<SqlUser> Users = new List<SqlUser>();
public List<Constraint> ViewIndexes = new List<Constraint>();
Expand Down Expand Up @@ -128,7 +131,8 @@ public List<Table> FindTablesRegEx(string pattern) {

private static HashSet<string> _dirs = new HashSet<string> {
"tables", "foreign_keys", "assemblies", "functions", "procedures", "triggers",
"views", "xmlschemacollections", "data", "roles", "users", "synonyms", "table_types"
"views", "xmlschemacollections", "data", "roles", "users", "synonyms", "table_types",
"user_defined_types"
};

public static HashSet<string> Dirs
Expand Down Expand Up @@ -173,6 +177,7 @@ public void Load() {
LoadProps(cm);
LoadSchemas(cm);
LoadTables(cm);
LoadUserDefinedTypes(cm);
LoadColumns(cm);
LoadColumnIdentities(cm);
LoadColumnDefaults(cm);
Expand Down Expand Up @@ -857,7 +862,42 @@ from sys.table_types tt
}
}

private static void LoadTablesBase(SqlDataReader dr, bool areTableTypes, List<Table> tables) {

private void LoadUserDefinedTypes(SqlCommand cm) {
//get types
cm.CommandText = @"
select
s.name as 'Type_Schema',
t.name as 'Type_Name',
tt.name as 'Base_Type_Name',
t.max_length as 'Max_Length',
t.is_nullable as 'Nullable'
from sys.types t
inner join sys.schemas s on s.schema_id = t.schema_id
inner join sys.types tt on t.system_type_id = tt.user_type_id
where
t.is_user_defined = 1
and t.is_table_type = 0";

using (var dr = cm.ExecuteReader()) {
LoadUserDefinedTypesBase(dr, UserDefinedTypes);
}
}

private void LoadUserDefinedTypesBase(SqlDataReader dr,
List<UserDefinedType> userDefinedTypes) {

while (dr.Read()) {
userDefinedTypes.Add(new UserDefinedType(owner: (string) dr["Type_Schema"],
name: (string) dr["Type_Name"],
baseTypeName: (string) dr["Base_Type_Name"],
maxLength: Convert.ToInt16(dr["Max_Length"]),
nullable: (bool) dr["Nullable"]));
}

}

private static void LoadTablesBase(SqlDataReader dr, bool areTableTypes, List<Table> tables) {
while (dr.Read()) {
tables.Add(new Table((string) dr["TABLE_SCHEMA"], (string) dr["TABLE_NAME"]) {IsType = areTableTypes});
}
Expand Down Expand Up @@ -1188,6 +1228,7 @@ public void ScriptToDir(string tableHint = null, Action<TraceLevel, string> log
WriteSchemaScript(log);
WriteScriptDir("tables", Tables.ToArray(), log);
WriteScriptDir("table_types", TableTypes.ToArray(), log);
WriteScriptDir("user_defined_types", UserDefinedTypes.ToArray(), log);
WriteScriptDir("foreign_keys", ForeignKeys.ToArray(), log);
foreach (var routineType in Routines.GroupBy(x => x.RoutineType)) {
var dir = routineType.Key.ToString().ToLower() + "s";
Expand Down
102 changes: 102 additions & 0 deletions model/Models/UserDefinedType.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,102 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace SchemaZen.Library.Models {

public class UserDefinedType : INameable, IHasOwner, IScriptable {

public string Name { get; set; }

public string Owner { get; set; }

public string BaseTypeName { get; set; }

public string MaxLength {
get {
switch (BaseTypeName) {
case "nvarchar":
return _maxLength == -1 ? "max" : ((short) (_maxLength / 2)).ToString();
case "varchar":
case "binary":
case "char":
case "nchar":
case "varbinary":
return _maxLength == -1 ? "max" : _maxLength.ToString();
default:
return _maxLength.ToString();
}
}
}
private short _maxLength;

private bool HasMaxLength() {
switch (BaseTypeName) {
case "bigint":
case "bit":
case "date":
case "datetime":
case "datetime2":
case "datetimeoffset":
case "float":
case "hierarchyid":
case "image":
case "int":
case "money":
case "ntext":
case "real":
case "smalldatetime":
case "smallint":
case "smallmoney":
case "sql_variant":
case "text":
case "time":
case "timestamp":
case "tinyint":
case "uniqueidentifier":
case "geography":
case "xml":
case "sysname":
return false;
case "decimal":
case "numberic":
throw new Exception("Precision and Scale not handled yet.");
default:
return true;
}
}

public string Nullable { get { return _nullable ? "NULL" : "NOT NULL"; } }
private readonly bool _nullable;

public UserDefinedType(string owner,
string name,
string baseTypeName,
short maxLength,
bool nullable) {
Owner = owner;
Name = name;
BaseTypeName = baseTypeName;
_maxLength = maxLength;
_nullable = nullable;
}

public string ScriptCreate() {
var text = new StringBuilder();

text.AppendFormat("CREATE TYPE [{0}].[{1}] FROM [{2}]",
Owner, Name, BaseTypeName);

if (HasMaxLength()) {
text.AppendFormat(" ({0})", MaxLength);
}

text.AppendFormat(" {0}", Nullable);

return text.ToString();
}

}

}
1 change: 1 addition & 0 deletions model/Schemazen.Library.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -73,6 +73,7 @@
<Compile Include="Models\ForeignKey.cs" />
<Compile Include="Models\Identity.cs" />
<Compile Include="Models\Interfaces.cs" />
<Compile Include="Models\UserDefinedType.cs" />
<Compile Include="Properties\AssemblyInfo.cs" />
<Compile Include="Models\Role.cs" />
<Compile Include="Models\Routine.cs" />
Expand Down