GithubHelp home page GithubHelp logo

aeslinger0 / sqlsharpener Goto Github PK

View Code? Open in Web Editor NEW
49.0 8.0 20.0 3.86 MB

Parses SQL files to create a meta-object hierarchy with which you can generate C# code such as stored procedure wrappers.

License: Other

C# 100.00%

sqlsharpener's Introduction

SqlSharpener

Rather than generating code from the database or using a heavy abstraction layer that might miss differences between the database and data access layer until run-time, this project aims to provide a very fast and simple data access layer that is generated at design-time using SQL files as the source-of-truth (such as those found in an SSDT project) without having to deploy the database first.

SqlSharpener accomplishes this by parsing the SQL files to create a meta-object hierarchy with which you can generate C# code such as stored procedure wrappers or Entity Framework Code-First entities. You can do this manually or by invoking one of the included pre-compiled T4 templates.

Donate

If you find SqlSharpener to be useful, please consider making a donation via PayPay. Thank you.

Examples

See examples of what SqlSharpener can do on the Examples wiki page. Also, a solution with the examples is included with the code for you to download.

Performance

According to the performance tests from Dapper, the best performance came from hand-coded functions using SqlDataReader. SqlSharpener gives you that performance without needing to hand-code your functions.

Installation

Using NuGet, run the following command to install SqlSharpener:

PM> Install-Package SqlSharpener

This will add SqlSharpener as a solution-level package. That means that the dll's do not get added to any of your projects (nor should they).

Quick Start

See the Quick Start Guide for more examples.

The fastest way to get up and running is to call one of SqlSharpener's included pre-compiled templates from your template. Add a new T4 template (*.tt) file to your data project and set its content as follows: (Ensure you have the correct version number in the dll path)

<#@ template debug="false" hostspecific="true" language="C#" #>
<#@ assembly name="$(SolutionDir)\packages\SqlSharpener.1.0.2\tools\SqlSharpener.dll" #>
<#@ output extension=".cs" #>
<#@ import namespace="Microsoft.VisualStudio.TextTemplating" #>
<#@ import namespace="System.Collections.Generic" #>
<#@ import namespace="SqlSharpener" #>
<#
	// Specify paths to your *.sql files. Remember to include your tables as well! We need them to get the data types.
	var sqlPaths = new List<string>();
	sqlPaths.Add(Host.ResolvePath(@"..\SimpleExample.Database\dbo\Tables"));
	sqlPaths.Add(Host.ResolvePath(@"..\SimpleExample.Database\dbo\Stored Procedures"));

	// Set parameters for the template.
	var session = new TextTemplatingSession();
	session["outputNamespace"] = "SimpleExample.DataLayer";
	session["procedurePrefix"] = "usp_";
	session["sqlPaths"] = sqlPaths;

	// Generate the code.
	var t = new SqlSharpener.StoredProceduresTemplate();
    t.Session = session;
	t.Initialize();
	this.Write(t.TransformText());
#>

The generated .cs file will contain a class with functions for all your stored procedures, DTO objects for procedures that return records, and an interface you can used if you use dependency-injection. Whenever your database project changes, simply right-click on the .tt file and click "Run Custom Tool" to regenerate the code.

Usage

Once the code is generated, your business layer can call it like any other function. Here is one example:

    public TaskGetDto Get(int id)
    {
        return storedProcedures.TaskGet(id);
    }

Dependency Injection

If you use a dependency-injection framework such as Ninject, you can use the interface generated. For example:

public class  DataModule : NinjectModule
{
    public override void Load()
    {
        Bind<IStoredProcedures>().To<StoredProcedures>();
    }
}

Documentation

Check out the wiki for more info.

License

SqlSharpener uses The MIT License (MIT), but also has dependencies on DacFx and ScriptDom. I have included their license info in the root directory.

sqlsharpener's People

Contributors

aeslinger0 avatar jamesbascle avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

sqlsharpener's Issues

XML/JSON support

if we had some sproc that returned an xml (or json) column, e.g.:

select id, name, tags=(
    select key [@key], value [@value]
    from tagTable where some_id=o.id
    for xml path('tag'), type)
from someTable o

and sqlsharpener could parse the for xml syntax to generate this corresponding dto:

public class sproc_result
{
    public int id;
    public string name;
    public List<tag> tags;

    public class tag { string key; string value; }
}

it seems very difficult but it would be a great feature

Dependancy Issues with Microsoft.Data.Tools.Schema.Sql

I was attempting to test this library with generating my EF classes, and when I ran the "Custom Tool" from the content menu of my TT file, I get the following error:

Severity Code Description Project File Line Suppression State
Error Running transformation: System.IO.FileNotFoundException: Could not load file or assembly 'Microsoft.Data.Tools.Schema.Sql, Version=12.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a' or one of its dependencies. The system cannot find the file specified.
File name: 'Microsoft.Data.Tools.Schema.Sql, Version=12.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a'
at Microsoft.SqlServer.Dac.Model.TSqlModel..ctor(SqlServerVersion modelTargetVersion, TSqlModelOptions modelCreationOptions)
at SqlSharpener.MetaBuilder.LoadModel()
at SqlSharpener.MetaBuilder.get_Tables()
at Microsoft.VisualStudio.TextTemplating84159610F57874C491F71FE10F447E99B01EE123BEC660EE937086DB49B427A007E765001AD2BA8136FE03AB1833E02A9B714FE13BA1A2A0ED94B7BDBB97E585.GeneratedTextTransformation.TransformText()

WRN: Assembly binding logging is turned OFF.
To enable assembly bind failure logging, set the registry value HKLM\Software\Microsoft\Fusion!EnableLog to 1.
Note: There is some performance penalty associated with assembly bind failure logging.
To turn this feature off, remove the registry value [HKLM\Software\Microsoft\Fusion!EnableLog]. TestGenerateEF C:\Users\bsimbeck\Documents\GNGV2\Test\TestGenerateEF\TestGenerateEF\TextTemplate1.tt 1

Based on what is generated, it looks like it is happening around the following line of my TT file
<# foreach(var tbl in meta.Tables){ #>

I have tried to include the missing DLL library in my solution as well as copy them to the Package folder with the rest of the DLL's it looks like SQLSharpener needs. I have included my solution folder as a zip file for you.
TestGenerateEF.zip

Updated NuGet

Hi, I was wondering if you plan on publishing an updated NuGet package with the view changes that were recently added?

Add support for schema

I can get the schema name from a relationship object. However, I really need it on the table object as well.

Loading a view throws exception

I am having troubles referencing any of my views. The error occurs in the Column class on line 103.

The following expression returns an empty list. The column it fails on is the first [Id] column of the view. It says it is a SqlComputedColumn. I do not know enough about the Microsoft.SqlServer.Dac.Model classes to try to resolve myself.

SqlObject.GetReferenced(dac.Column.DataType).ToList()
Error       Running transformation: System.InvalidOperationException: Sequence contains no elements
   at System.Linq.Enumerable.First[TSource](IEnumerable`1 source)
   at SqlSharpener.Model.Column..ctor(TSqlObject tSqlObject, TSqlObject tSqlTable, IEnumerable`1 primaryKeys, IDictionary`2 foreignKeys)
   at SqlSharpener.Model.View..ctor(TSqlObject tSqlObject, IEnumerable`1 primaryKeys, IDictionary`2 foreignKeys)
   at SqlSharpener.MetaBuilder.<>c__DisplayClass10.<LoadModel>b__9(TSqlObject sqlView)
   at System.Linq.Enumerable.WhereSelectEnumerableIterator`2.MoveNext()
   at System.Collections.Generic.List`1..ctor(IEnumerable`1 collection)
   at System.Linq.Enumerable.ToList[TSource](IEnumerable`1 source)
   at SqlSharpener.MetaBuilder.LoadModel(TSqlModel model)
   at SqlSharpener.MetaBuilder.LoadModel()
   at SqlSharpener.MetaBuilder.get_Tables()

SQL Scripts to repoduce

CREATE TABLE [dbo].[Port] (
    [Id]                 SMALLINT       IDENTITY (1, 1) NOT NULL,
    [Name]               VARCHAR (50)   NOT NULL,
    [Abbreviation]       VARCHAR (3)    NOT NULL,
    [Active]             BIT            NOT NULL,
    [Longitude]          DECIMAL (9, 6) NULL,
    [Latitude]           DECIMAL (9, 6) NULL,
    [PortTypeId]         SMALLINT       NOT NULL,
    [CreatedBy]          VARCHAR(255)   NOT NULL,
    [CreatedDateTime]    DATETIME2      NOT NULL,
    [UpdatedBy]          VARCHAR(255)       NULL,
    [UpdatedDateTime]    DATETIME2          NULL,
    [RowVersion]         ROWVERSION     NOT NULL,
    CONSTRAINT [PK_Port] PRIMARY KEY CLUSTERED ([Id] ASC),
    CONSTRAINT [CK_Port_Latitude_Latitude] CHECK ([Latitude] IS NULL AND [Longitude] IS NULL OR [Latitude] IS NOT NULL AND ([Latitude]>=(-90) AND [Latitude]<=(90)) AND [Longitude] IS NOT NULL AND ([Longitude]>=(-180) AND [Longitude]<=(180))),
    CONSTRAINT [FK_Port_PortTypeId] FOREIGN KEY ([PortTypeId]) REFERENCES [dbo].[PortType] ([Id]),
    CONSTRAINT [UQ_Port_Abbreviation] UNIQUE NONCLUSTERED ([Abbreviation] ASC),
    CONSTRAINT [UQ_Port_Name] UNIQUE NONCLUSTERED ([Name] ASC)
);
CREATE TABLE [dbo].[PortType]
(
    [Id]           SMALLINT      IDENTITY (1, 1) NOT NULL,
    [Name]         VARCHAR(20)   NOT NULL,
    [RowVersion]   ROWVERSION    NOT NULL,
    CONSTRAINT [PK_PortType] PRIMARY KEY CLUSTERED ([Id] ASC),
    CONSTRAINT [UX_PortType_Name] UNIQUE NONCLUSTERED ([Name] ASC)
)
CREATE VIEW [dbo].[RemotePort]
AS
SELECT [Port].*
  FROM [dbo].[Port]
 INNER JOIN [dbo].[PortType]
         ON [PortType].[Id] = [Port].[PortTypeId]
 WHERE [PortType].[Name] = 'Remote Port'

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.