Skip to main content

RSCG_Sql by Ignat Andrei

NuGet / site data​

Nuget GitHub last commit GitHub Repo stars

Details​

Info​

info

Name: RSCG_Sql

Roslyn incremental source generator that creates asynchronous database operations from SQL files.

Author: Ignat Andrei

NuGet: https://www.nuget.org/packages/RSCG_Sql/

You can find more details at https://github.com/ignatandrei/RSCG_Sql

Source: https://github.com/ignatandrei/RSCG_Sql

Author​

note

Ignat Andrei Alt text

Original Readme​

note

RSCG_Sql​

RSCG_Sql.Generator is a netstandard2.0 Roslyn incremental source generator that reads .sql files registered as AdditionalFiles. It parses each GO-separated batch with Microsoft ScriptDom and generates asynchronous methods in a SqlCommands class in the consuming project's RootNamespace. It emits one source file per SQL AdditionalFile, named using its relative folders and file name joined by underscores (for example, Sql\Commands.sql becomes Sql_Commands.g.cs). The tests and sample target .NET 10.

Install from NuGet​

Install the published RSCG_Sql package:

dotnet add package RSCG_Sql --version 2026.11.1.1516

Or add it directly to your project:

<ItemGroup>
<PackageReference Include="RSCG_Sql" Version="2026.11.1.1516" />
<AdditionalFiles Include="Sql\Commands.sql" />
<CompilerVisibleProperty Include="MSBuildProjectDirectory" />
</ItemGroup>

The package includes the generator and its ScriptDom runtime under analyzers/dotnet/cs. For local development against this repository, reference the generator project as an analyzer and include the ScriptDom assembly:

<ProjectReference Include="..\RSCG_Sql.Generator\RSCG_Sql.Generator.csproj"
OutputItemType="Analyzer"
ReferenceOutputAssembly="false" />
<Analyzer Include="..\RSCG_Sql.Generator\bin\$(Configuration)\netstandard2.0\Microsoft.SqlServer.TransactSql.ScriptDom.dll" />
<AdditionalFiles Include="Sql\Commands.sql" />
<CompilerVisibleProperty Include="MSBuildProjectDirectory" />

Annotate each batch with a method name. @Returns names the row type for a SELECT; @IdType is required for inserts that return an identity:

-- @Name FindPerson
-- @Returns Person
SELECT id, name FROM people WHERE id = @id;
GO
-- @Name InsertPerson
-- @IdType long
INSERT INTO people(name) VALUES (@name);
SELECT last_insert_rowid();

Generated methods accept an already-open DbConnection, one argument for each SQL variable reference, and an optional CancellationToken. They do not open/close connections or create transactions. Annotated result rows are materialized with a public parameterless constructor and public writable properties matched to result column names without case sensitivity. UPDATE and DELETE batches return the sum of affected rows; non-query DDL batches return Task.

Supported syntax and mappings​
  • Batches are separated by a standalone GO line; SQL comments use --.
  • Supported operation forms are SELECT with @Returns, INSERT with @IdType and a recognized identity expression, UPDATE/DELETE, and non-query statements such as DDL. Each batch produces one method.
  • Identity expressions recognized by the generator are SQL Server @@IDENTITY, SCOPE_IDENTITY(), IDENT_CURRENT(...), and OUTPUT INSERTED.ID; SQLite last_insert_rowid(); and PostgreSQL currval(...). Only SQLite is covered by integration tests.
  • SQL declaration types map naturally: integer, bigint, smallint, tinyint, bit, uniqueidentifier, decimal/numeric/money, float/real, date/datetime, time, binary, and character/text types map to their corresponding C# primitives, Guid, DateTime, TimeSpan, byte[], and string. Types the generator cannot infer use object?.
  • SQL dialect extensions must be accepted by the SQL Server ScriptDom parser. Malformed batches, missing/invalid annotations, unsupported identity forms, ambiguous result sets, and duplicate method names produce compiler errors rather than generated fallback behavior.
Build and tests​
dotnet build RSCG_Sql.slnx
dotnet test RSCG_Sql.Tests\RSCG_Sql.Tests.csproj

The test project executes generated methods against an in-memory SQLite database. RSCG_Sql.Sample is a runnable console consumer demonstrating the same integration.

About​

note

Generating sql commands in C# from text

How to use​

Example (source csproj, source files)​

This is the CSharp Project that references RSCG_Sql

<Project Sdk="Microsoft.NET.Sdk">

<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net10.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
</PropertyGroup>

<ItemGroup>
<PackageReference Include="Microsoft.Data.Sqlite" Version="10.0.14" />
<PackageReference Include="RSCG_Sql" Version="2026.11.1.1516" />
</ItemGroup>

<ItemGroup>
<CompilerVisibleProperty Include="MSBuildProjectDirectory" />
<AdditionalFiles Include="Sql\Commands.sql" />
</ItemGroup>
<PropertyGroup>
<EmitCompilerGeneratedFiles>true</EmitCompilerGeneratedFiles>
<CompilerGeneratedFilesOutputPath>$(BaseIntermediateOutputPath)\GX</CompilerGeneratedFilesOutputPath>
</PropertyGroup>
</Project>

Generated Files​

Those are taken from $(BaseIntermediateOutputPath)\GX

// <auto-generated />
#nullable enable
namespace RSCG_Sql.Sample;

public static partial class SqlCommands
{
public static async global::System.Threading.Tasks.Task CreatePeopleAsync(global::System.Data.Common.DbConnection connection, global::System.Threading.CancellationToken cancellationToken = default)
{
if (connection.State != global::System.Data.ConnectionState.Open)
{
throw new global::System.InvalidOperationException("The supplied DbConnection must already be open.");
}
await using (var command = connection.CreateCommand())
{
command.CommandText = "CREATE TABLE people (id INTEGER PRIMARY KEY, name TEXT NOT NULL);";
var rows = await command.ExecuteNonQueryAsync(cancellationToken).ConfigureAwait(false);
}
}

public static async global::System.Threading.Tasks.Task<long> InsertPersonAsync(global::System.Data.Common.DbConnection connection, object? name, global::System.Threading.CancellationToken cancellationToken = default)
{
if (connection.State != global::System.Data.ConnectionState.Open)
{
throw new global::System.InvalidOperationException("The supplied DbConnection must already be open.");
}
object? insertedValue;
await using (var command = connection.CreateCommand())
{
command.CommandText = "INSERT INTO people(name) VALUES (@name);\nSELECT last_insert_rowid();";
var sqlParameter_0 = command.CreateParameter();
sqlParameter_0.ParameterName = "@name";
sqlParameter_0.Value = (object?)name ?? global::System.DBNull.Value;
command.Parameters.Add(sqlParameter_0);
insertedValue = await command.ExecuteScalarAsync(cancellationToken).ConfigureAwait(false);
}
if (insertedValue is null || insertedValue is global::System.DBNull) throw new global::System.InvalidOperationException("The identity query did not return a value.");
var insertedId = ConvertResult<long>(insertedValue);
return insertedId;
}

public static async global::System.Threading.Tasks.Task<Person[]> GetPeopleAsync(global::System.Data.Common.DbConnection connection, global::System.Threading.CancellationToken cancellationToken = default)
{
if (connection.State != global::System.Data.ConnectionState.Open)
{
throw new global::System.InvalidOperationException("The supplied DbConnection must already be open.");
}
var results = new global::System.Collections.Generic.List<Person>();
await using (var command = connection.CreateCommand())
{
command.CommandText = "SELECT id AS Id, name AS Name FROM people;";
await using var reader = await command.ExecuteReaderAsync(cancellationToken).ConfigureAwait(false);
while (reader.FieldCount == 0)
{
if (!await reader.NextResultAsync(cancellationToken).ConfigureAwait(false))
throw new global::System.InvalidOperationException("The annotated SELECT did not return a result set.");
}
while (await reader.ReadAsync(cancellationToken).ConfigureAwait(false))
{
var item = (Person)global::System.Activator.CreateInstance(typeof(Person))!;
for (var column = 0; column < reader.FieldCount; column++)
{
switch (column)
{
case 0:
if (!await reader.IsDBNullAsync(column, cancellationToken).ConfigureAwait(false))
{
item.Id = global::System.Convert.ToInt64(reader.GetValue(column), global::System.Globalization.CultureInfo.InvariantCulture)!;
}
break;
case 1:
if (await reader.IsDBNullAsync(column, cancellationToken).ConfigureAwait(false))
item.Name = default!;
else
{
item.Name = global::System.Convert.ToString(reader.GetValue(column), global::System.Globalization.CultureInfo.InvariantCulture)!;
}
break;
default:
throw new global::System.InvalidOperationException($"The SELECT returned an unmapped column at ordinal {column}.");
}
}
results.Add(item);
}
while (await reader.NextResultAsync(cancellationToken).ConfigureAwait(false)) \{ }
}
return results.ToArray();
}

private static T ConvertResult<T>(object value)
{
if (typeof(T) == typeof(global::System.Guid)) return (T)(object)global::System.Guid.Parse(global::System.Convert.ToString(value, global::System.Globalization.CultureInfo.InvariantCulture)!);
return (T)global::System.Convert.ChangeType(value, typeof(T), global::System.Globalization.CultureInfo.InvariantCulture)!;
}

}

Useful​

Download Example (.NET C#)​

Share RSCG_Sql​

https://ignatandrei.github.io/RSCG_Examples/v2/docs/RSCG_Sql

Category "FilesToCode" has the following generators:​

1 Chorn.EmbeddedResourceAccessGenerator Nuget GitHub Repo stars 2024-01-21

2 corecraft Nuget GitHub Repo stars 2024-02-17

3 Datacute.EmbeddedResourcePropertyGenerator Nuget GitHub Repo stars 2024-11-03

4 DotnetYang Nuget GitHub Repo stars 2024-06-29

5 EmbedResourceCSharp Nuget GitHub Repo stars 2023-04-16

6 Hardcoded.NET Nuget GitHub Repo stars 2026-12-23

7 kli.Localize Nuget GitHub Repo stars 2025-10-01

8 LingoGen Nuget GitHub Repo stars 2024-02-23

9 Maestria.TypeProviders Nuget GitHub Repo stars 2026-04-09

10 MagicConstants Nuget GitHub Repo stars 2026-09-04

11 NFH.FileEmbed Nuget GitHub Repo stars 2025-08-08

12 NotNotAppSettings Nuget GitHub Repo stars 2024-01-26

13 Pinecone.TypedPath Nuget GitHub Repo stars 2026-08-24

14 Podimo.ConstEmbed Nuget GitHub Repo stars 2023-04-16

15 ResXGenerator Nuget GitHub Repo stars 2023-10-02

16 RSCG_JSON2Class Nuget GitHub Repo stars 2024-02-29

17 RSCG_Sql Nuget GitHub Repo stars 2026-11-09

18 RSCG_Utils Nuget GitHub Repo stars 2023-04-16

19 Slang.Net Nuget GitHub Repo stars 2026-09-11

20 Strings.ResourceGenerator Nuget GitHub Repo stars 2025-07-06

21 SvgIconGenerator Nuget GitHub Repo stars 2026-04-04

22 ThisAssembly_Resources Nuget GitHub Repo stars 2023-09-16

23 ThisAssembly.Strings Nuget GitHub Repo stars 2024-07-21

24 TypedPaths Nuget GitHub Repo stars 2026-04-01

25 Weave Nuget GitHub Repo stars 2024-01-27

See category​

FilesToCode