Skip to content
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

Add FromRawSql api #25457

Closed
wants to merge 1 commit into from
Closed
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
66 changes: 66 additions & 0 deletions src/EFCore.Cosmos/Extensions/CosmosQueryableExtensions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,9 @@
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;
using System.Runtime.CompilerServices;
using JetBrains.Annotations;
using Microsoft.EntityFrameworkCore.Cosmos.Query.Internal;
using Microsoft.EntityFrameworkCore.Query;
using Microsoft.EntityFrameworkCore.Query.Internal;
using Microsoft.EntityFrameworkCore.Utilities;
Expand Down Expand Up @@ -46,5 +49,68 @@ public static class CosmosQueryableExtensions
Expression.Constant(partitionKey)))
: source;
}

/// <summary>
/// <para>
/// Creates a LINQ query based on a raw SQL query.
/// </para>
/// <para>
/// If the database provider supports composing on the supplied SQL, you can compose on top of the raw SQL query using
/// LINQ operators: <c>context.Blogs.FromSqlRaw("SELECT * FROM root c WHERE c["Discriminator"] = "Blog").OrderBy(b => b.Name)</c>.
/// </para>
/// <para>
/// As with any API that accepts SQL it is important to parameterize any user input to protect against a SQL injection
/// attack. You can include parameter place holders in the SQL query string and then supply parameter values as additional
/// arguments. Any parameter values you supply will automatically be converted to a DbParameter:
/// </para>
/// <code>context.Blogs.FromSqlRaw(""SELECT * FROM root c WHERE c["Discriminator"] = {0})", userSuppliedSearchTerm)</code>
///
/// <para>
/// This overload also accepts DbParameter instances as parameter values. This allows you to use named
/// parameters in the SQL query string:
/// </para>
/// <code>context.Blogs.FromSqlRaw(""SELECT * FROM root c WHERE c["Discriminator"] = @searchTerm)", new SqlParameter("@searchTerm", userSuppliedSearchTerm))</code>
/// </summary>
/// <typeparam name="TEntity"> The type of the elements of <paramref name="source" />. </typeparam>
/// <param name="source">
/// An <see cref="IQueryable{T}" /> to use as the base of the raw SQL query (typically a <see cref="DbSet{TEntity}" />).
/// </param>
/// <param name="sql"> The raw SQL query. </param>
/// <param name="parameters"> The values to be assigned to parameters. </param>
/// <returns> An <see cref="IQueryable{T}" /> representing the raw SQL query. </returns>
[StringFormatMethod("sql")]
public static IQueryable<TEntity> FromSqlRaw<TEntity>(
this IQueryable<TEntity> source,
[NotParameterized] string sql,
params object[] parameters)
where TEntity : class
{
Check.NotNull(source, nameof(source));
Check.NotEmpty(sql, nameof(sql));
Check.NotNull(parameters, nameof(parameters));

return source.Provider.CreateQuery<TEntity>(
GenerateFromSqlQueryRoot(
source,
sql,
parameters));
}

private static FromSqlQueryRootExpression GenerateFromSqlQueryRoot(
IQueryable source,
string sql,
object?[] arguments,
[CallerMemberName] string memberName = null!)
{
var queryRootExpression = (QueryRootExpression)source.Expression;

var entityType = queryRootExpression.EntityType;

return new FromSqlQueryRootExpression(
queryRootExpression.QueryProvider!,
entityType,
sql,
Expression.Constant(arguments));
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -187,6 +187,28 @@ static bool TryGetPartitionKeyProperty(IEntityType entityType, out IProperty par
}
}

/// <inheritdoc />
protected override Expression VisitExtension(Expression extensionExpression)
{
switch (extensionExpression)
{
case FromSqlQueryRootExpression fromSqlQueryRootExpression:
var queryExpression = new SelectExpression(
fromSqlQueryRootExpression.EntityType,
fromSqlQueryRootExpression.Sql,
fromSqlQueryRootExpression.Argument);

return new ShapedQueryExpression(
queryExpression,
new FromSqlCosmosEntityShaperExpression(
fromSqlQueryRootExpression.EntityType,
new ProjectionBindingExpression(queryExpression, new ProjectionMember(), typeof(ValueBuffer)),
false));
default:
return base.VisitExtension(extensionExpression);
}
}

/// <summary>
/// This is an internal API that supports the Entity Framework Core infrastructure and not subject to
/// the same compatibility standards as public APIs. It may be changed or removed without notice in
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;
using Microsoft.EntityFrameworkCore.Diagnostics;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Metadata;
using Microsoft.EntityFrameworkCore.Metadata.Internal;
using Microsoft.EntityFrameworkCore.Query;
using Microsoft.EntityFrameworkCore.Storage;
using Microsoft.EntityFrameworkCore.Utilities;

namespace Microsoft.EntityFrameworkCore.Cosmos.Query.Internal
{
/// <summary>
/// <para>
/// An expression that represents creation of an entity instance for Cosmos provider in
/// <see cref="ShapedQueryExpression.ShaperExpression" />.
/// </para>
/// <para>
/// This type is typically used by database providers (and other extensions). It is generally
/// not used in application code.
/// </para>
/// </summary>
public class FromSqlCosmosEntityShaperExpression : EntityShaperExpression
{
/// <summary>
/// Creates a new instance of the <see cref="FromSqlCosmosEntityShaperExpression" /> class.
/// </summary>
/// <param name="entityType"> The entity type to shape. </param>
/// <param name="valueBufferExpression"> An expression of ValueBuffer to get values for properties of the entity. </param>
/// <param name="nullable"> A bool value indicating whether this entity instance can be null. </param>
public FromSqlCosmosEntityShaperExpression(IEntityType entityType, Expression valueBufferExpression, bool nullable)
: base(entityType, valueBufferExpression, nullable, null)
{
}

/// <inheritdoc />
protected override LambdaExpression GenerateMaterializationCondition(IEntityType entityType, bool nullable)
{
Check.NotNull(entityType, nameof(EntityType));

var valueBufferParameter = Parameter(typeof(ValueBuffer));
Expression body;
var concreteEntityTypes = entityType.GetConcreteDerivedTypesInclusive().ToArray();

body = Constant(concreteEntityTypes.Length == 1 ? concreteEntityTypes[0] : entityType, typeof(IEntityType));

return Lambda(body, valueBufferParameter);
}
}
}
106 changes: 106 additions & 0 deletions src/EFCore.Cosmos/Query/Internal/FromSqlExpression.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,106 @@
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.

using System;
using System.Diagnostics.CodeAnalysis;
using System.Linq.Expressions;
using Microsoft.EntityFrameworkCore.Metadata;
using Microsoft.EntityFrameworkCore.Query;
using Microsoft.EntityFrameworkCore.Utilities;

namespace Microsoft.EntityFrameworkCore.Cosmos.Query.Internal
{
/// <summary>
/// This is an internal API that supports the Entity Framework Core infrastructure and not subject to
/// the same compatibility standards as public APIs. It may be changed or removed without notice in
/// any release. You should only use it directly in your code with extreme caution and knowing that
/// doing so can result in application failures when updating to a new Entity Framework Core release.
/// </summary>
public class FromSqlExpression : RootReferenceExpression, ICloneable, IPrintableExpression
{
/// <summary>
/// This is an internal API that supports the Entity Framework Core infrastructure and not subject to
/// the same compatibility standards as public APIs. It may be changed or removed without notice in
/// any release. You should only use it directly in your code with extreme caution and knowing that
/// doing so can result in application failures when updating to a new Entity Framework Core release.
/// </summary>
public FromSqlExpression(IEntityType entityType, string alias, string sql, Expression arguments) : base(entityType, alias)
{
Check.NotEmpty(sql, nameof(sql));
Check.NotNull(arguments, nameof(arguments));

Sql = sql;
Arguments = arguments;
}

/// <summary>
/// The alias assigned to this table source.
/// </summary>
[NotNull]
public override string? Alias => base.Alias!;

/// <summary>
/// The user-provided custom SQL for the table source.
/// </summary>
public virtual string Sql { get; }

/// <summary>
/// The user-provided parameters passed to the custom SQL.
/// </summary>
public virtual Expression Arguments { get; }

/// <summary>
/// Creates a new expression that is like this one, but using the supplied children. If all of the children are the same, it will
/// return this expression.
/// </summary>
/// <param name="arguments"> The <see cref="Arguments" /> property of the result. </param>
/// <returns> This expression if no children changed, or an expression with the updated children. </returns>
public virtual FromSqlExpression Update(Expression arguments)
{
Check.NotNull(arguments, nameof(arguments));

return arguments != Arguments
? new FromSqlExpression(EntityType, Alias, Sql, arguments)
: this;
}

/// <inheritdoc />
protected override Expression VisitChildren(ExpressionVisitor visitor)
{
Check.NotNull(visitor, nameof(visitor));

return this;
}

/// <inheritdoc />
public override Type Type
=> typeof(object);

/// <inheritdoc />
public virtual object Clone() => new FromSqlExpression(EntityType, Alias, Sql, Arguments);

/// <inheritdoc />
void IPrintableExpression.Print(ExpressionPrinter expressionPrinter)
{
Check.NotNull(expressionPrinter, nameof(expressionPrinter));

expressionPrinter.Append(Sql);
}

/// <inheritdoc />
public override bool Equals(object? obj)
=> obj != null
&& (ReferenceEquals(this, obj)
|| obj is FromSqlExpression fromSqlExpression
&& Equals(fromSqlExpression));

private bool Equals(FromSqlExpression fromSqlExpression)
=> base.Equals(fromSqlExpression)
&& Sql == fromSqlExpression.Sql
&& ExpressionEqualityComparer.Instance.Equals(Arguments, fromSqlExpression.Arguments);

/// <inheritdoc />
public override int GetHashCode()
=> HashCode.Combine(base.GetHashCode(), Sql);
}
}
Loading