-
Notifications
You must be signed in to change notification settings - Fork 7
Expand file tree
/
Copy pathDatabaseCommand.cs
More file actions
60 lines (50 loc) · 2.53 KB
/
Copy pathDatabaseCommand.cs
File metadata and controls
60 lines (50 loc) · 2.53 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
namespace CoreEx.Database;
/// <summary>
/// Provides extended database command capabilities.
/// </summary>
/// <param name="db">The <see cref="IDatabase"/>.</param>
/// <param name="statement">The <see cref="SqlStatement"/>.</param>
/// <remarks>As the underlying <see cref="DbCommand"/> implements <see cref="IDisposable"/> this is only created (and automatically disposed) where executing the command proper.</remarks>
public abstract partial class DatabaseCommand(IDatabase db, SqlStatement statement) : IDatabaseParameters<DatabaseCommand>
{
/// <inheritdoc/>
public IDatabase Database { get; } = db.ThrowIfNull();
/// <inheritdoc/>
public DatabaseParameterCollection Parameters { get; } = new DatabaseParameterCollection(db);
/// <summary>
/// Gets the <see cref="SqlStatement"/>.
/// </summary>
public SqlStatement Statement { get; } = statement.ThrowIfNull();
/// <summary>
/// Gets the <see cref="DatabaseArgs"/> for the command.
/// </summary>
/// <remarks>Defaults to the underlying <see cref="IDatabase.DbArgs"/>.</remarks>
public DatabaseArgs DbArgs { get; protected set; } = db.DbArgs;
/// <summary>
/// Creates the corresponding <see cref="DbCommand"/>.
/// </summary>
/// <param name="cancellationToken">The <see cref="CancellationToken"/>.</param>
/// <returns>The <see cref="DbCommand"/>.</returns>
private async Task<DbCommand> CreateCommandAsync(CancellationToken cancellationToken)
{
if (Statement.IsIndeterminate)
throw new InvalidOperationException($"Cannot execute a command where the {nameof(Statement)} is {nameof(SqlStatement.IsIndeterminate)}; the {nameof(SqlStatement)} must be set to a valid command.");
var conn = await Database.GetConnectionAsync(cancellationToken).ConfigureAwait(false);
var cmd = conn.CreateCommand();
if (Database.CurrentTransaction is not null)
cmd.Transaction = Database.CurrentTransaction;
cmd.CommandType = Statement.CommandType;
cmd.CommandText = Statement.CommandText;
cmd.Parameters.AddRange(Parameters.ToArray());
return cmd;
}
/// <summary>
/// Logs the command type and text at debug level.
/// </summary>
private DbCommand LogCommand(DbCommand command)
{
if (Database.Logger?.IsEnabled(LogLevel.Debug) is true)
Database.Logger.LogDebug("Executing DbCommand [CommandType='{CommandType}']:{NewLine}{CommandText}", command.CommandType, Environment.NewLine, command.CommandText);
return command;
}
}