-
Notifications
You must be signed in to change notification settings - Fork 0
/
SnowflakeCommand.FirstOrDefault.cs
69 lines (56 loc) · 2.43 KB
/
SnowflakeCommand.FirstOrDefault.cs
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
//-----------------------------------------------------------------------
// <copyright file="SnowflakeCommand.FirstOrDefault.cs" company="Jonas Schubert">
// Copyright (c) Jonas Schubert. All rights reserved.
// </copyright>
// <author>Jonas Schubert</author>
//-----------------------------------------------------------------------
namespace Snowflake.Data.Xt;
/// <summary>
/// The snowflake command.
/// </summary>
/// <typeparam name="T">The generic type. This is used to parse properties for the query.</typeparam>
public partial class SnowflakeCommand<T>
where T : class
{
/// <summary>
/// Gets the first item for a query or null if none is found.
/// </summary>
/// <param name="parameterList">The parameter list.</param>
/// <returns>The first item if found, otherwise null.</returns>
public T? FirstOrDefault(IList<(string, DbType, object)>? parameterList = default)
{
if (this.snowflakeDbConnection is null)
{
using var dbConnection = new SnowflakeDbConnection
{
ConnectionString = EnvironmentExtensions.GetSnowflakeConnectionString(),
};
dbConnection.Open();
var item = this.FirstOrDefault(dbConnection, parameterList);
dbConnection.Close();
return item;
}
if (!this.snowflakeDbConnection.IsOpen())
{
this.snowflakeDbConnection.Open();
}
return this.FirstOrDefault(this.snowflakeDbConnection, parameterList);
}
private T? FirstOrDefault(SnowflakeDbConnection snowflakeDbConnection, IList<(string, DbType, object)>? parameterList = default)
{
this.WriteLogInformation("Performing snowflake command to retrieve one entity (FirstOrDefault).");
var command = snowflakeDbConnection.CreateCommand();
this.WriteLogInformation(this.Sql);
command.CommandText = this.Sql;
var totalParameterList = this.ParameterList.Concat(parameterList ?? new List<(string, DbType, object)>()).ToList();
this.WriteLogInformation(string.Format(CultureInfo.InvariantCulture, "Adding {0} parameters.", totalParameterList.Count));
foreach (var parameter in totalParameterList)
{
command.AddParameter(parameter.Item1, parameter.Item2, parameter.Item3);
}
var reader = command.ExecuteReader();
var item = reader.FirstOrDefault<T>();
this.WriteLogInformation($"Found{(item is not null ? string.Empty : " no")} item for the provided query.");
return item;
}
}