Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using t4 templates to generate in-memory SQL at runtime

Tags:

c#

.net

t4

t-sql

We are building a query service that needs to parse the user's search term and generate a form of SQL (not T-SQL but a proprietary SQL-like query language) out of it. To generate the SQL, we are looking into T4 templates.

I looked into another question here at Creating T4 templates at runtime (build-time), and I understand the basic idea; however what we need is not a physical file output but a simple in memory string containing the final SQL statement. Is that possible?

The second question I have, which almost more important: how fast is this T4 stuff when taking into account the rather complex logic we need to generate the SQL inside a T4 template file. Thanks.

like image 492
John Avatar asked Jan 26 '26 18:01

John


1 Answers

What I think you want to take a look at preprocessed templates (aka runtime templates). You create them in visual studio 2010 by using the template Preprocess Text Template.

I created this very simple template (I named it MyTemplate.tt):

<#@ template language="C#"#>
<#
    for (var iter = 0; iter < HowManyCommentsToGenerate; ++iter)
    {
#>
    // <#=iter#>
<#
    }
#>

I added this partial class that extends the generated class with HowManyCommentsToGenerate field:

partial class MyTemplate
{
    int HowManyCommentsToGenerate;

    public MyTemplate (int count)
    {
        HowManyCommentsToGenerate = count;
    }
}

Finally I use it like this (note that the output is string not a file):

class Program
{
    static void Main(string[] args)
    {
        var str = new MyTemplate(32);
        Console.Write(str.TransformText());
    }
}

As far performance I honestly don't have enough experience with run-time templates to advice you on this. I recommend reading the generated code and profiling it.

like image 98
Just another metaprogrammer Avatar answered Jan 29 '26 06:01

Just another metaprogrammer