Repository navigation
Expand file tree
/
Copy pathQueryHintSample.cs
More file actions
147 lines (135 loc) · 5.35 KB
/
Copy pathQueryHintSample.cs
File metadata and controls
147 lines (135 loc) · 5.35 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
// Copyright 2021 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
using Google.Cloud.EntityFrameworkCore.Spanner.Samples.SampleModel;
using Google.Cloud.EntityFrameworkCore.Spanner.Storage;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Diagnostics;
using System;
using System.Data.Common;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
/// <summary>
/// Cloud Spanner supports multiple query hints. CommandInterceptors can be used to
/// add hints to queries that are generated by Entity Framework.
/// See https://docs.microsoft.com/en-us/ef/core/logging-events-diagnostics/interceptors#example-command-interception-to-add-query-hints
/// for more information on using CommandInterceptors.
///
/// See https://cloud.google.com/spanner/docs/query-syntax#table-hints for more information
/// on possible table and statement hints for Cloud Spanner.
///
/// Run from the command line with `dotnet run QueryHintSample`
/// </summary>
public static class QueryHintSample
{
// This sample uses a DbContext that adds a command interceptor to the context.
// This command interceptor will add an index hint to any query that has been
// tagged with a specific value.
class TaggedSampleDbContext : SpannerSampleDbContext
{
private static readonly TaggedQueryCommandInterceptor s_interceptor
= new TaggedQueryCommandInterceptor();
public TaggedSampleDbContext(string connectionString) : base(connectionString)
{
}
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
base.OnConfiguring(optionsBuilder);
optionsBuilder.AddInterceptors(s_interceptor);
}
}
public static async Task Run(string connectionString)
{
using var context = new TaggedSampleDbContext(connectionString);
await Setup(context);
var singersOrderedByFullName = context.Singers
// This will add the following comment to the generated query:
// `-- Use hint: force_index FullName`
// This comment will be picked up by the interceptor and an index
// hint will be added to the query that is executed.
.TagWith("Use hint: force_index FullName")
.OrderBy(s => s.FullName)
.AsAsyncEnumerable();
var first = true;
await foreach (var singer in singersOrderedByFullName)
{
if (first)
{
Console.WriteLine("Singers ordered by full name:");
first = false;
}
Console.WriteLine($"{singer.FullName}");
}
}
class TaggedQueryCommandInterceptor : DbCommandInterceptor
{
public override InterceptionResult<DbDataReader> ReaderExecuting(
DbCommand command,
CommandEventData eventData,
InterceptionResult<DbDataReader> result)
{
ManipulateCommand(command);
return result;
}
public override ValueTask<InterceptionResult<DbDataReader>> ReaderExecutingAsync(
DbCommand command,
CommandEventData eventData,
InterceptionResult<DbDataReader> result,
CancellationToken cancellationToken = default)
{
ManipulateCommand(command);
return ValueTask.FromResult(result);
}
/// <summary>
/// Adds a table hint to all queries that have been tagged with
/// `Use hint: force_index FullName`
/// </summary>
/// <param name="command">The command to possibly add a hint to</param>
private static void ManipulateCommand(DbCommand command)
{
if (command.CommandText.StartsWith("-- Use hint: force_index FullName", StringComparison.Ordinal))
{
command.CommandText = command.CommandText.Replace
(
"FROM `Singers`",
"FROM `Singers`@{FORCE_INDEX=Idx_Singers_FullName}"
);
}
Console.WriteLine($"\nQuery being executed:\n{command.CommandText}\n");
}
}
private static async Task Setup(SpannerSampleDbContext context)
{
await context.Singers.AddRangeAsync(
new Singer
{
FirstName = "Alice",
LastName = "Henderson",
BirthDate = new SpannerDate(1983, 10, 19),
},
new Singer
{
FirstName = "Peter",
LastName = "Allison",
BirthDate = new SpannerDate(2000, 5, 2),
},
new Singer
{
FirstName = "Mike",
LastName = "Nicholson",
BirthDate = new SpannerDate(1976, 8, 31),
});
await context.SaveChangesAsync();
}
}