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

DebugView for query and simple way to get SQL from an EF LINQ query #19324

Merged
merged 1 commit into from
Dec 15, 2019
Merged
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
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
using System;
using System.Collections;
using System.Collections.Generic;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.EntityFrameworkCore.Diagnostics;
Expand All @@ -12,9 +13,15 @@

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 partial class CosmosShapedQueryCompilingExpressionVisitor
{
private sealed class QueryingEnumerable<T> : IEnumerable<T>, IAsyncEnumerable<T>
private sealed class QueryingEnumerable<T> : IEnumerable<T>, IAsyncEnumerable<T>, IQueryingEnumerable
{
private readonly CosmosQueryContext _cosmosQueryContext;
private readonly ISqlExpressionFactory _sqlExpressionFactory;
Expand Down Expand Up @@ -48,6 +55,32 @@ public IAsyncEnumerator<T> GetAsyncEnumerator(CancellationToken cancellationToke
public IEnumerator<T> GetEnumerator() => new Enumerator(this);
IEnumerator IEnumerable.GetEnumerator() => GetEnumerator();

public string ToQueryString()
{
var sqlQuery = _querySqlGeneratorFactory.Create().GetSqlQuery(
(SelectExpression)new InExpressionValuesExpandingExpressionVisitor(
Copy link
Member

Choose a reason for hiding this comment

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

Extract and DRY as this is likely to change in the future.

Copy link
Member Author

Choose a reason for hiding this comment

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

Did that, but then reverted since it was more lines of code. But will do it since you think it's worth it.

Copy link
Member

Choose a reason for hiding this comment

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

Fewer LoC isn't always better 😃

_sqlExpressionFactory, _cosmosQueryContext.ParameterValues).Visit(_selectExpression),
_cosmosQueryContext.ParameterValues);

if (sqlQuery.Parameters.Count == 0)
{
return sqlQuery.Query;
}

var builder = new StringBuilder();
foreach (var parameter in sqlQuery.Parameters)
{
builder
.Append("-- ")
.Append(parameter.Name)
.Append("='")
.Append(parameter.Value)
.AppendLine("'");
}

return builder.Append(sqlQuery.Query).ToString();
}

private sealed class Enumerator : IEnumerator<T>
{
private IEnumerator<JObject> _enumerator;
Expand Down
8 changes: 7 additions & 1 deletion src/EFCore.InMemory/Properties/InMemoryStrings.Designer.cs

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

57 changes: 30 additions & 27 deletions src/EFCore.InMemory/Properties/InMemoryStrings.resx
Original file line number Diff line number Diff line change
@@ -1,17 +1,17 @@
<?xml version="1.0" encoding="utf-8"?>
<root>
<!--
Microsoft ResX Schema
<!--
Microsoft ResX Schema

Version 2.0
The primary goals of this format is to allow a simple XML format
that is mostly human readable. The generation and parsing of the
various data types are done through the TypeConverter classes

The primary goals of this format is to allow a simple XML format
that is mostly human readable. The generation and parsing of the
various data types are done through the TypeConverter classes
associated with the data types.

Example:

... ado.net/XML headers & schema ...
<resheader name="resmimetype">text/microsoft-resx</resheader>
<resheader name="version">2.0</resheader>
Expand All @@ -26,36 +26,36 @@
<value>[base64 mime encoded string representing a byte array form of the .NET Framework object]</value>
<comment>This is a comment</comment>
</data>
There are any number of "resheader" rows that contain simple

There are any number of "resheader" rows that contain simple
name/value pairs.
Each data row contains a name, and value. The row also contains a
type or mimetype. Type corresponds to a .NET class that support
text/value conversion through the TypeConverter architecture.
Classes that don't support this are serialized and stored with the

Each data row contains a name, and value. The row also contains a
type or mimetype. Type corresponds to a .NET class that support
text/value conversion through the TypeConverter architecture.
Classes that don't support this are serialized and stored with the
mimetype set.
The mimetype is used for serialized objects, and tells the
ResXResourceReader how to depersist the object. This is currently not

The mimetype is used for serialized objects, and tells the
ResXResourceReader how to depersist the object. This is currently not
extensible. For a given mimetype the value must be set accordingly:
Note - application/x-microsoft.net.object.binary.base64 is the format
that the ResXResourceWriter will generate, however the reader can

Note - application/x-microsoft.net.object.binary.base64 is the format
that the ResXResourceWriter will generate, however the reader can
read any of the formats listed below.

mimetype: application/x-microsoft.net.object.binary.base64
value : The object must be serialized with
value : The object must be serialized with
: System.Runtime.Serialization.Formatters.Binary.BinaryFormatter
: and then encoded with base64 encoding.

mimetype: application/x-microsoft.net.object.soap.base64
value : The object must be serialized with
value : The object must be serialized with
: System.Runtime.Serialization.Formatters.Soap.SoapFormatter
: and then encoded with base64 encoding.

mimetype: application/x-microsoft.net.object.bytearray.base64
value : The object must be serialized into a byte array
value : The object must be serialized into a byte array
: using a System.ComponentModel.TypeConverter
: and then encoded with base64 encoding.
-->
Expand Down Expand Up @@ -125,6 +125,9 @@
<value>Transactions are not supported by the in-memory store. See http://go.microsoft.com/fwlink/?LinkId=800142</value>
<comment>Warning InMemoryEventId.TransactionIgnoredWarning</comment>
</data>
<data name="NoQueryStrings" xml:space="preserve">
<value>There is no query string because the in-memory provider does not use a string-based query language.</value>
</data>
<data name="UpdateConcurrencyException" xml:space="preserve">
<value>Attempted to update or delete an entity that does not exist in the store.</value>
</data>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,15 +7,22 @@
using System.Threading;
using System.Threading.Tasks;
using Microsoft.EntityFrameworkCore.Diagnostics;
using Microsoft.EntityFrameworkCore.InMemory.Internal;
using Microsoft.EntityFrameworkCore.Query;
using Microsoft.EntityFrameworkCore.Storage;
using Microsoft.EntityFrameworkCore.Utilities;

namespace Microsoft.EntityFrameworkCore.InMemory.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 partial class InMemoryShapedQueryCompilingExpressionVisitor
{
private sealed class QueryingEnumerable<T> : IAsyncEnumerable<T>, IEnumerable<T>
private sealed class QueryingEnumerable<T> : IAsyncEnumerable<T>, IEnumerable<T>, IQueryingEnumerable
{
private readonly QueryContext _queryContext;
private readonly IEnumerable<ValueBuffer> _innerEnumerable;
Expand Down Expand Up @@ -44,6 +51,8 @@ public IAsyncEnumerator<T> GetAsyncEnumerator(CancellationToken cancellationToke

IEnumerator IEnumerable.GetEnumerator() => GetEnumerator();

public string ToQueryString() => InMemoryStrings.NoQueryStrings;

private sealed class Enumerator : IEnumerator<T>
{
private IEnumerator<ValueBuffer> _enumerator;
Expand Down
69 changes: 68 additions & 1 deletion src/EFCore.Relational/Query/Internal/QueryingEnumerable.cs
Original file line number Diff line number Diff line change
Expand Up @@ -6,11 +6,13 @@
using System.Collections.Generic;
using System.Data.Common;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using JetBrains.Annotations;
using Microsoft.EntityFrameworkCore.Diagnostics;
using Microsoft.EntityFrameworkCore.Storage;
using Microsoft.EntityFrameworkCore.Storage.Internal;

namespace Microsoft.EntityFrameworkCore.Query.Internal
{
Expand All @@ -20,7 +22,7 @@ namespace Microsoft.EntityFrameworkCore.Query.Internal
/// 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 QueryingEnumerable<T> : IEnumerable<T>, IAsyncEnumerable<T>
public class QueryingEnumerable<T> : IEnumerable<T>, IAsyncEnumerable<T>, IQueryingEnumerable
{
private readonly RelationalQueryContext _relationalQueryContext;
private readonly RelationalCommandCache _relationalCommandCache;
Expand All @@ -30,6 +32,12 @@ public class QueryingEnumerable<T> : IEnumerable<T>, IAsyncEnumerable<T>
private readonly Type _contextType;
private readonly IDiagnosticsLogger<DbLoggerCategory.Query> _logger;

/// <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 QueryingEnumerable(
[NotNull] RelationalQueryContext relationalQueryContext,
[NotNull] RelationalCommandCache relationalCommandCache,
Expand All @@ -48,12 +56,71 @@ public QueryingEnumerable(
_logger = logger;
}

/// <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 virtual IAsyncEnumerator<T> GetAsyncEnumerator(CancellationToken cancellationToken = default)
=> new AsyncEnumerator(this, cancellationToken);

/// <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 virtual IEnumerator<T> GetEnumerator() => new Enumerator(this);

/// <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>
IEnumerator IEnumerable.GetEnumerator() => GetEnumerator();

/// <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 virtual string ToQueryString()
{
using var command = _relationalCommandCache
.GetRelationalCommand(_relationalQueryContext.ParameterValues)
.CreateCommand(
new RelationalCommandParameterObject(
_relationalQueryContext.Connection,
_relationalQueryContext.ParameterValues,
null,
null,
null),
Guid.Empty,
(DbCommandMethod)(-1));

if (command.Parameters.Count == 0)
{
return command.CommandText;
}

var builder = new StringBuilder();
foreach (var parameter in command.Parameters.FormatParameterList(logParameterValues: true))
{
builder.Append("-- ").AppendLine(parameter);
}

return builder.Append(command.CommandText).ToString();
}

/// <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 static int[] BuildIndexMap([CanBeNull] IReadOnlyList<string> columnNames, [NotNull] DbDataReader dataReader)
{
if (columnNames == null)
Expand Down
22 changes: 22 additions & 0 deletions src/EFCore.Relational/Storage/IRelationalCommand.cs
Original file line number Diff line number Diff line change
@@ -1,9 +1,12 @@
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.

using System;
using System.Collections.Generic;
using System.Data.Common;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.EntityFrameworkCore.Diagnostics;

namespace Microsoft.EntityFrameworkCore.Storage
{
Expand Down Expand Up @@ -84,5 +87,24 @@ Task<object> ExecuteScalarAsync(
Task<RelationalDataReader> ExecuteReaderAsync(
RelationalCommandParameterObject parameterObject,
CancellationToken cancellationToken = default);

/// <summary>
/// <para>
/// Called by the execute methods to create a <see cref="DbCommand" /> for the given <see cref="DbConnection" />
/// and configure timeouts and transactions.
/// </para>
/// <para>
/// This method is typically used by database providers (and other extensions). It is generally
/// not used in application code.
/// </para>
/// </summary>
/// <param name="parameterObject"> Parameters for this method. </param>
/// <param name="commandId"> The command correlation ID. </param>
/// <param name="commandMethod"> The method that will be called on the created command. </param>
/// <returns> The created command. </returns>
DbCommand CreateCommand(
RelationalCommandParameterObject parameterObject,
Guid commandId,
DbCommandMethod commandMethod) => throw new NotImplementedException();
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.

using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Common;
using System.Globalization;
Expand Down Expand Up @@ -30,7 +31,19 @@ public static class DbParameterCollectionExtensions
public static string FormatParameters(
[NotNull] this DbParameterCollection parameters,
bool logParameterValues)
=> parameters
=> FormatParameterList(parameters, logParameterValues).Join();

/// <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 static IEnumerable<string> FormatParameterList(
[NotNull] this DbParameterCollection parameters,
bool logParameterValues)
{
return parameters
.Cast<DbParameter>()
.Select(
p => FormatParameter(
Expand All @@ -42,8 +55,8 @@ public static string FormatParameters(
p.IsNullable,
p.Size,
p.Precision,
p.Scale))
.Join();
p.Scale));
}

/// <summary>
/// This is an internal API that supports the Entity Framework Core infrastructure and not subject to
Expand Down
Loading