Skip to content

Commit

Permalink
auto generated comment
Browse files Browse the repository at this point in the history
  • Loading branch information
douglas-wong-zocdoc authored and marcio-santos-zocdoc committed Aug 31, 2016
1 parent 15d8a97 commit 99ec5be
Show file tree
Hide file tree
Showing 5 changed files with 196 additions and 11 deletions.
6 changes: 3 additions & 3 deletions model/DBHelper.cs
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@

namespace SchemaZen.Library {
public class DBHelper {
public static bool EchoSql = false;
public static bool EchoSql = false;

public static void ExecSql(string conn, string sql) {
if (EchoSql) Console.WriteLine(sql);
Expand Down Expand Up @@ -39,7 +39,7 @@ public static void ExecBatchSql(string conn, string sql) {
}
}

public static void DropDb(string conn) {
public static void DropDb(string conn) {
var cnBuilder = new SqlConnectionStringBuilder(conn);
var initialCatalog = cnBuilder.InitialCatalog;

Expand All @@ -55,7 +55,7 @@ public static void DropDb(string conn) {
}
}

public static void CreateDb(string connection, string databaseFilesPath = null) {
public static void CreateDb(string connection, string databaseFilesPath = null) {
var cnBuilder = new SqlConnectionStringBuilder(connection);
var dbName = cnBuilder.InitialCatalog;
cnBuilder.InitialCatalog = "master";
Expand Down
32 changes: 26 additions & 6 deletions model/Models/Database.cs
Original file line number Diff line number Diff line change
Expand Up @@ -7,8 +7,6 @@
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 @@ -59,13 +57,25 @@ public Database(string name, IList<string> filteredTypes = null)
public const string SqlWhitespaceOrCommentRegex = @"(?>(?:\s+|--.*?(?:\r|\n)|/\*.*?\*/))";
public const string SqlEnclosedIdentifierRegex = @"\[.+?\]";
public const string SqlQuotedIdentifierRegex = "\".+?\"";

public const string SqlRegularIdentifierRegex = @"(?!\d)[\w@$#]+";
// see rules for regular identifiers here https://msdn.microsoft.com/en-us/library/ms175874.aspx

#region " Properties "
public static readonly string AutoGenerateComment = String.Format(
@"/*----------------------------------------------------------------------------
<auto-generated>
This file was generated by schemazen.
Date: {0}
Changes to this file may cause incorrect behavior and will be lost if
the code is regenerated.
</auto-generated>
----------------------------------------------------------------------------*/
", DateTime.Today.ToString("MM-dd-yyyy"));

public List<SqlAssembly> Assemblies = new List<SqlAssembly>();
#region " Properties "

public List<SqlAssembly> Assemblies = new List<SqlAssembly>();
public string Connection = "";
public List<Table> DataTables = new List<Table>();
public string Dir = "";
Expand Down Expand Up @@ -134,6 +144,8 @@ public List<Table> FindTablesRegEx(string pattern) {
"views", "xmlschemacollections", "data", "roles", "users", "synonyms", "table_types"
};

private Dictionary<string, string> _seenPaths = new Dictionary<string, string>();

public static HashSet<string> Dirs
{
get { return _dirs; }
Expand Down Expand Up @@ -1245,6 +1257,7 @@ public void ScriptToDir(string tableHint = null, Action<TraceLevel, string> log
private void WritePropsScript(Action<TraceLevel, string> log) {
log(TraceLevel.Verbose, "Scripting database properties...");
var text = new StringBuilder();
text.Append(AutoGenerateComment);
text.Append(ScriptPropList(Props));
text.AppendLine("GO");
text.AppendLine();
Expand All @@ -1254,6 +1267,7 @@ private void WritePropsScript(Action<TraceLevel, string> log) {
private void WriteSchemaScript(Action<TraceLevel, string> log) {
log(TraceLevel.Verbose, "Scripting database schemas...");
var text = new StringBuilder();
text.Append(AutoGenerateComment);
foreach (var schema in Schemas) {
text.Append(schema.ScriptCreate());
}
Expand All @@ -1271,7 +1285,13 @@ private void WriteScriptDir(string name, ICollection<IScriptable> objects, Actio
foreach (var o in objects) {
log(TraceLevel.Verbose, string.Format("Scripting {0} {1} of {2}...{3}", name, ++index, objects.Count, index < objects.Count ? "\r" : string.Empty));
var filePath = Path.Combine(dir, MakeFileName(o) + ".sql");
var script = o.ScriptCreate() + "\r\nGO\r\n";
var script = "";
if (_seenPaths.ContainsKey(filePath)) {
script += o.ScriptCreate() + "\r\nGO\r\n";
} else {
script += AutoGenerateComment + o.ScriptCreate() + "\r\nGO\r\n";
_seenPaths.Add(filePath, "");
}
File.AppendAllText(filePath, script);
}
}
Expand Down
165 changes: 165 additions & 0 deletions test/CommentTester.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,165 @@
using System;
using System.IO;
using NUnit.Framework;
using SchemaZen.Library;
using SchemaZen.Library.Models;

namespace SchemaZen.Tests
{
[TestFixture]
class CommentTester {
private const string SetupTable0Script = @"
CREATE TABLE [dbo].[TestTable0] (
[VariantVersionId] [smallint] NOT NULL ,
[MetricTypeId] [smallint] NOT NULL ,
[RequestId] [bigint] NOT NULL ,
[ProfessionalId] [bigint] NOT NULL ,
[ZdAppointmentId] [bigint] NOT NULL
,CONSTRAINT [PK_AbAdvancedMetrics_VariantVersionId_MetricTypeId_RequestId] PRIMARY KEY CLUSTERED ([VariantVersionId], [MetricTypeId], [RequestId]),
CONSTRAINT AK_Uni UNIQUE(MetricTypeId)
)";

private const string SetupTable1Script = @"
CREATE TABLE [dbo].[TestTable1] (
[MetricTypeId] [smallint] NOT NULL
CONSTRAINT AK_Metric UNIQUE(MetricTypeId)
)
";

private const string SetUpTable2Script = @"
CREATE TABLE [dbo].[TestTable2] (
ID int
)
";

private const string SetupTableTypeScript = @"
CREATE TYPE [dbo].[TestTableType] AS TABLE(
[ID] [nvarchar](250) NULL,
[Value] [numeric](5, 1) NULL,
[LongNVarchar] [nvarchar](max) NULL
)
";
private const string SetupFKScript = @"
ALTER TABLE [dbo].[TestTable0]
ADD CONSTRAINT TestConstraint
FOREIGN KEY([VariantVersionId]) REFERENCES [dbo].[TestTable1](MetricTypeId)";

private const string SetupFuncScript = @"
CREATE FUNCTION TestFunc
(@Description VARCHAR(50),@CreatedDate DateTime)
RETURNS TABLE
AS
RETURN
with CharLocations AS (Select OpenParenLoc = CHARINDEX('(',@Description),
HyphenLoc = CHARINDEX('-',@Description),
CloseParenLoc = CHARINDEX(')',@Description)),
SubstringInfos AS (Select StartDateStart = OpenParenLoc + 1,
StartDateLen = HyphenLoc - OpenParenLoc - 1,
EndDateStart = HyphenLoc + 1,
EndDateLen = CloseParenLoc - HyphenLoc - 1
From CharLocations),
Substrings As (Select StartDate = SUBSTRING(@Description,StartDateStart,StartDateLen),
EndDate = SUBSTRING(@Description,EndDateStart,EndDateLen),
ConcatYear = CASE
WHEN (StartDateLen > 5) THEN ''
ELSE '/' + RIGHT(DATEPART(yyyy,@CreatedDate),2)
END
From SubstringInfos)
(Select StartDate = CONVERT(DATE,StartDate + ConcatYear,1),
EndDate = CONVERT(DATE,EndDate + ConcatYear,1)
From Substrings)
";

private const string SetupProcScript = @"
CREATE PROCEDURE TestProc
(
@dept_name varchar(20)
)
AS
BEGIN
SELECT * FROM [dbo].[TestTable0]
END";

private const string SetupRoleScript = @"
CREATE ROLE [TestRole]";

private const string SetupTrigScript = @"
CREATE TRIGGER TestTrigger ON
[dbo].[TestTable0]
FOR INSERT
AS
Begin
SELECT * FROM [dbo].[TestTable0]
End
";

private const string SetupUserScript = @"
CREATE USER [TestUser] WITHOUT LOGIN WITH DEFAULT_SCHEMA = dbo
";

private const string SetupViewScript = @"
CREATE VIEW TestView
AS
SELECT * FROM [dbo].[testTable0]
";

private Database _db;

[SetUp]
public void SetUp() {
_db = new Database("TestAppendComment");
_db.Connection = ConfigHelper.TestDB.Replace("database=TESTDB", "database=" + _db.Name);
_db.ExecCreate(true);

DBHelper.ExecSql(_db.Connection, SetupTable0Script);
DBHelper.ExecSql(_db.Connection, SetupTable1Script);
DBHelper.ExecSql(_db.Connection, SetupTableTypeScript);
DBHelper.ExecSql(_db.Connection, SetupFKScript);
DBHelper.ExecSql(_db.Connection, SetupFuncScript);
DBHelper.ExecSql(_db.Connection, SetupProcScript);
DBHelper.ExecSql(_db.Connection, SetupRoleScript);
DBHelper.ExecSql(_db.Connection, SetupTrigScript);
DBHelper.ExecSql(_db.Connection, SetupUserScript);
DBHelper.ExecSql(_db.Connection, SetupViewScript);
_db.Dir = _db.Name;
_db.Load();
_db.ScriptToDir();
}

[TestCase("\\table_types\\", "TYPE_TestTableType.sql")]
[TestCase("\\foreign_keys\\", "TestTable0.sql")]
[TestCase("\\functions\\", "TestFunc.sql")]
[TestCase("\\procedures\\", "TestProc.sql")]
[TestCase("\\roles\\", "TestRole.sql")]
[TestCase("\\triggers\\", "TestTrigger.sql")]
[TestCase("\\tables\\", "TestTable0.sql")]
[TestCase("\\users\\", "TestUser.sql")]
[TestCase("\\views\\", "TestView.sql")]
[TestCase("\\", "schemas.sql")]
public void TestFilesContainComment(string directory, string fileName) {
Assert.IsTrue(ValidateFirstLineIncludesComment(_db.Name +
directory + fileName, Database.AutoGenerateComment));
}

[Test]
public void TestScriptIsValidWithComment() {
var scriptWithComment = Database.AutoGenerateComment + SetUpTable2Script;
DBHelper.ExecBatchSql(_db.Connection, scriptWithComment);
}

[TearDown]
public void TearDown() {
DBHelper.DropDb(_db.Connection);
DBHelper.ClearPool(_db.Connection);
var currPath = ".\\TestAppendComment";
Directory.Delete(currPath, true);
}

bool ValidateFirstLineIncludesComment(string filePath, string matchingStr) {
var firstLine = File.ReadAllLines(filePath)[0];
return matchingStr.Contains(firstLine);
}
}
}
1 change: 1 addition & 0 deletions test/Tests.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -75,6 +75,7 @@
</ItemGroup>
<ItemGroup>
<Compile Include="AssemblyTester.cs" />
<Compile Include="CommentTester.cs" />
<Compile Include="Properties\AssemblyInfo.cs" />
<Compile Include="UserTester.cs" />
</ItemGroup>
Expand Down
3 changes: 1 addition & 2 deletions test/packages.config
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
<?xml version="1.0" encoding="utf-8"?>

<packages>
<package id="NUnit" version="2.6.2" targetFramework="net35" />
<package id="NUnit.Runners" version="2.6.2" targetFramework="net35" />
</packages>
</packages>

0 comments on commit 99ec5be

Please sign in to comment.