Skip to content

feat: support Dapper overloads with CommandDefinition #153

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

Open
wants to merge 3 commits into
base: main
Choose a base branch
from
Open
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
62 changes: 56 additions & 6 deletions src/Dapper.AOT.Analyzers/CodeAnalysis/DapperAnalyzer.cs
Original file line number Diff line number Diff line change
Expand Up @@ -192,7 +192,7 @@ private void ValidateDapperMethod(in OperationAnalysisContext ctx, IOperation sq
var parseState = new ParseState(ctx);
bool aotEnabled = IsEnabled(in parseState, invoke, Types.DapperAotAttribute, out var aotAttribExists);
if (!aotEnabled) flags |= OperationFlags.DoNotGenerate;
var location = SharedParseArgsAndFlags(parseState, invoke, ref flags, out var sql, out var argExpression, onDiagnostic, out _, exitFirstFailure: false);
var location = SharedParseArgsAndFlags(parseState, invoke, ref flags, out var sql, out var argExpression, onDiagnostic, out _, exitFirstFailure: false, out var viaCommandDefinition);

// report our AOT readiness
if (aotEnabled)
Expand Down Expand Up @@ -410,7 +410,7 @@ private void ValidateSql(in OperationAnalysisContext ctx, IOperation sqlSource,
if (caseSensitive) flags |= SqlParseInputFlags.CaseSensitive;

// can we get the SQL itself?
if (!TryGetConstantValueWithSyntax(sqlSource, out string? sql, out var sqlSyntax, out var stringSyntaxKind))
if (!TryGetStringConstantValueWithSyntax(sqlSource, out string? sql, out var sqlSyntax, out var stringSyntaxKind))
{
DiagnosticDescriptor? descriptor = stringSyntaxKind switch
{
Expand Down Expand Up @@ -503,32 +503,70 @@ StringSyntaxKind.ConcatenatedString or StringSyntaxKind.FormatString

// we want a common understanding of the setup between the analyzer and generator
internal static Location SharedParseArgsAndFlags(in ParseState ctx, IInvocationOperation op, ref OperationFlags flags, out string? sql,
Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

put viaCommandDefinition in OperationFlags

out IOperation? argExpression, Action<Diagnostic>? reportDiagnostic, out ITypeSymbol? resultType, bool exitFirstFailure)
out IOperation? argExpression, Action<Diagnostic>? reportDiagnostic, out ITypeSymbol? resultType, bool exitFirstFailure,
out bool viaCommandDefinition)
{
var callLocation = op.GetMemberLocation();
argExpression = null;
sql = null;
bool? buffered = null;
viaCommandDefinition = false;

// check the args
foreach (var arg in op.Arguments)
// default is invocation, so simply take arguments
IEnumerable<IArgumentOperation> arguments = op.Arguments;

// invocation can be packed into a CommandDefinition
if (op.Arguments is { Length: >= 2 })
{
if (op.Arguments[0].Parameter?.Name == "cnn"
&& op.Arguments[1].Parameter?.Name == "command" && op.Arguments[1].Parameter?.Type.IsCommandDefinition() == true)
{
viaCommandDefinition = true;

// by default buffered CommandDefinition constructor initializes `buffered` as true via CommandFlags
// https://github.com/DapperLib/Dapper/blob/5c7143f2e3585d4708294a3b0530a134e18ace86/Dapper/CommandDefinition.cs#L85
buffered = true;

// in-place creation of CommandDefinition like `Query<T>(new CommandDefinition(...))`
if (op.Arguments[1].Value is IObjectCreationOperation { Arguments.IsDefaultOrEmpty: false } commandDefinitionCreation )
{
arguments = commandDefinitionCreation.Arguments;
}

// ideally here we would want to parse other CommandDefinition cases (i.e. local variable).
// but it is complicated, so we can simply rely on passing CommandDefinition's members to the underlying query API
// ...
}
}

// check the args. Names of the parameters are handling Dapper method parameters + CommandDefinition members
foreach (var arg in arguments)
{
switch (arg.Parameter?.Name)
{
case "sql":
if (TryGetConstantValueWithSyntax(arg, out string? s, out _, out _))
case "commandText":
if (TryGetStringConstantValueWithSyntax(arg, out string? s, out _, out _))
{
sql = s;
}
break;
case "flags":
{
if (TryGetEnumConstantValueWithSyntax(arg, out int? value))
{
buffered = (value & 1) != 0; // CommandFlags.Buffered = 1
}
}
break;
case "buffered":
if (TryGetConstantValue(arg, out bool b))
{
buffered = b;
}
break;
case "param":
case "parameters":
if (arg.Value is not IDefaultValueOperation)
{
var expr = arg.Value;
Expand All @@ -555,6 +593,7 @@ internal static Location SharedParseArgsAndFlags(in ParseState ctx, IInvocationO
case "length":
case "returnNullIfFirstMissing":
case "concreteType" when arg.Value is IDefaultValueOperation || (arg.ConstantValue.HasValue && arg.ConstantValue.Value is null):
case "cancellationToken":
// nothing to do
break;
case "commandType":
Expand Down Expand Up @@ -583,6 +622,17 @@ internal static Location SharedParseArgsAndFlags(in ParseState ctx, IInvocationO
}
}
break;
case "command":
{
// case for CommandDefinition - we need to check that we detected it correctly before
// and if we did; then don't drop errors - we could not parse SQL / other flags in complex CommandDefinition usages,
// but we can optimistically pass CommandDefinition data to underlying query
if (!viaCommandDefinition)
{
goto default;
}
}
break;
default:
if (!flags.HasAny(OperationFlags.NotAotSupported | OperationFlags.DoNotGenerate))
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -19,26 +19,38 @@ static void WriteSingleImplementation(
in CommandFactoryState factories,
in RowReaderState readers,
string? fixedSql,
AdditionalCommandState? additionalCommandState)
AdditionalCommandState? additionalCommandState,
bool viaCommandDefinition)
{
sb.Append("return ");
if (flags.HasAll(OperationFlags.Async | OperationFlags.Query | OperationFlags.Buffered))
{
sb.Append("global::Dapper.DapperAotExtensions.AsEnumerableAsync(").Indent(false).NewLine();
}
// (DbConnection connection, DbTransaction? transaction, string sql, TArgs args, CommandType commandType, int timeout, CommandFactory<TArgs>? commandFactory)
sb.Append("global::Dapper.DapperAotExtensions.Command(cnn, ").Append(Forward(methodParameters, "transaction")).Append(", ");
sb.Append("global::Dapper.DapperAotExtensions.Command(cnn, ");

if (viaCommandDefinition) sb.Append("command.Transaction, ");
else sb.Append(Forward(methodParameters, "transaction")).Append(", ");

if (fixedSql is not null)
{
sb.AppendVerbatimLiteral(fixedSql).Append(", ");
}
else
{
sb.Append("sql, ");
if (viaCommandDefinition) sb.Append("command.CommandText, ");
else sb.Append("sql, ");
}

if (commandTypeMode == 0)
{ // not hard-coded
if (HasParam(methodParameters, "command"))
{
if (viaCommandDefinition)
{
sb.Append("command.CommandType ?? default");
}
// not hard-coded
else if (HasParam(methodParameters, "command"))
{
sb.Append("command.GetValueOrDefault()");
}
Expand All @@ -49,9 +61,14 @@ static void WriteSingleImplementation(
}
else
{
sb.Append("global::System.Data.CommandType.").Append(commandTypeMode.ToString());
if (viaCommandDefinition) sb.Append("command.CommandType ?? default");
else sb.Append("global::System.Data.CommandType.").Append(commandTypeMode.ToString());
}
sb.Append(", ").Append(Forward(methodParameters, "commandTimeout")).Append(HasParam(methodParameters, "commandTimeout") ? ".GetValueOrDefault()" : "").Append(", ");
sb.Append(", ");

if (viaCommandDefinition) sb.Append("command.CommandTimeout ?? default, ");
else sb.Append(Forward(methodParameters, "commandTimeout")).Append(HasParam(methodParameters, "commandTimeout") ? ".GetValueOrDefault()" : "").Append(", ");

if (flags.HasAny(OperationFlags.HasParameters))
{
var index = factories.GetIndex(parameterType!, map, cache, additionalCommandState, out var subIndex);
Expand Down Expand Up @@ -79,7 +96,7 @@ static void WriteSingleImplementation(
OperationFlags.Unbuffered => "Unbuffered",
_ => ""
}).Append(isAsync ? "Async" : "").Append("(");
WriteTypedArg(sb, parameterType).Append(", ");
WriteTypedArg(sb, parameterType, viaCommandDefinition).Append(", ");
if (!flags.HasAny(OperationFlags.SingleRow))
{
switch (flags & (OperationFlags.Buffered | OperationFlags.Unbuffered))
Expand Down Expand Up @@ -107,7 +124,7 @@ static void WriteSingleImplementation(
sb.Append("<").Append(resultType).Append(">");
}
sb.Append("(");
WriteTypedArg(sb, parameterType);
WriteTypedArg(sb, parameterType, viaCommandDefinition);
}
else
{
Expand All @@ -124,9 +141,11 @@ static void WriteSingleImplementation(
sb.Append(", rowCountHint: ((").Append(parameterType).Append(")param!).").Append(additionalCommandState.RowCountHintMemberName);
}
}
if (isAsync && HasParam(methodParameters, "cancellationToken"))
if (isAsync && (HasParam(methodParameters, "cancellationToken") || viaCommandDefinition))
{
sb.Append(", cancellationToken: ").Append(Forward(methodParameters, "cancellationToken"));
sb.Append(", cancellationToken: ");
if (viaCommandDefinition) sb.Append("command.CancellationToken");
else sb.Append(Forward(methodParameters, "cancellationToken"));
}
if (flags.HasAll(OperationFlags.Async | OperationFlags.Query | OperationFlags.Buffered))
{
Expand All @@ -153,10 +172,17 @@ static void WriteSingleImplementation(
}
sb.Append(";").NewLine();

static CodeWriter WriteTypedArg(CodeWriter sb, ITypeSymbol? parameterType)
static CodeWriter WriteTypedArg(CodeWriter sb, ITypeSymbol? parameterType, bool viaCommandDefinition)
{
if (viaCommandDefinition)
{
sb.Append("command.Parameters");
return sb;
}

if (parameterType is null || parameterType.IsAnonymousType)
{

sb.Append("param");
}
else
Expand Down
Loading
Loading