Skip to content
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
2 changes: 2 additions & 0 deletions CONTRIBUTING.md
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ How code gets into Open.Database.Extensions (ODX): the code rules a reviewer che

- **Chains.** The first call stays on the line of what it is called on; from the second call on, one call per line. A single call stays on one line. Never leave a bare receiver alone on a line.
- **Line width.** About 80 columns, a soft limit. An expression body's `=>` goes on the next line.
- **Wrapped initializers.** When an initializer or assignment wraps, its `=` starts the next indented line, as `=>` does, and a joined literal continues with `+` under it. A constant beside it takes the same shape even if it would fit on one line, and each constant has a blank line above it.
- **Arguments.** Keep a call on one line when it fits. When it does not, break the arguments into groups that belong together, one group per line. A long run of one-argument lines is a sign to regroup.
- **Braces.** A header that wraps over two or more lines always gets braces, even for one statement. A one-line header with one short statement may skip them (`csharp_prefer_braces = when_multiline`).

Expand All @@ -22,6 +23,7 @@ How code gets into Open.Database.Extensions (ODX): the code rules a reviewer che

- **Every exception says what is wrong and what to do.** Name the object or parameter, the cause, and the fix ("Call the query's terminal first, then await the capture.").
- **Guard once, at the public entry point,** with the right parameter name. Internal code trusts it and uses `Debug.Assert`. Our code never throws `NullReferenceException`.
- **One text for each fact.** A message that says the same thing in more than one place is one `const` in Core (an `internal` class is visible to the provider packages), referenced everywhere, and a message passed as an argument is that named constant, not an inline concatenation. Messages that differ on purpose, because each names its own call site, stay separate. A name or message of production code is never copied, either: a test does not put one into a constant of its own, it references the `internal` constant (the test project sees the internals of Core).
- **A misuse the compiler can catch is a compile error,** not a runtime throw, when that costs little API.

### Performance
Expand Down
23 changes: 2 additions & 21 deletions Source/Core/ArrayLease.cs
Original file line number Diff line number Diff line change
Expand Up @@ -93,11 +93,8 @@ public void Release()
// keep dirty rows: the clear runs here instead. Never a dirty
// array to a pool, and no one waits on the loop.
if (config.Bin.Post(
new RecycleBin.Work(
ChunkRunner<T>.Instance,
Array,
Used,
config)) == RecycleBin.PostResult.Full)
new RecycleBin.Work(config, Array, Used))
== RecycleBin.PostResult.Full)
{
config.ClearAndReturn(Array, Used);
}
Expand All @@ -113,19 +110,3 @@ public void Release()
public void Dispose()
=> Release();
}

/// <summary>The one runner of each row type.</summary>
/// <include file="Internals.docs.xml" path="docs/members[@name='row']/*" />
// One cached instance for each row type: no allocation per post.
internal sealed class ChunkRunner<T> : RecycleBin.IRunner
{
/// <summary>The one runner of this <typeparamref name="T"/>.</summary>
public static readonly ChunkRunner<T> Instance = new();

/// <summary>Clears the first <paramref name="used"/> rows and gives the array back.</summary>
/// <param name="array">The array to clear and return.</param>
/// <include file="Internals.docs.xml" path="docs/members[@name='used']/*" />
/// <param name="config">The <see cref="ChunkConfig{T}"/> the array came from.</param>
public void Run(Array array, int used, object config)
=> ((ChunkConfig<T>)config).ClearAndReturn((T[])array, used);
}
5 changes: 5 additions & 0 deletions Source/Core/ChunkConfig.cs
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,7 @@ internal sealed class ChunkConfig<T>(
ChunkSizes sizes,
RecycleBin bin,
int deferFromClearedBytes)
: RecycleBin.IRunner
{
/// <summary>
/// The bytes of rows (rows written times the size of a row) from which the
Expand Down Expand Up @@ -186,4 +187,8 @@ public void ClearAndReturn(T[] array, int used)
array.AsSpan(0, used).Clear();
Pool.Return(array, clearArray: false);
}

// What the recycle bin's loop calls: the same clear and return.
void RecycleBin.IRunner.Run(Array array, int used)
=> ClearAndReturn((T[])array, used);
}
13 changes: 13 additions & 0 deletions Source/Core/Core/CommandTextMessages.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
namespace Open.Database.Extensions;

/// <summary>
/// The messages of the checks on a command's text: one text for each fact,
/// used by every place that makes the check.
/// </summary>
internal static class CommandTextMessages
{
/// <summary>A command's text is empty or white space.</summary>
public const string Blank
= "The command cannot be empty or white space. "
+ "Pass the SQL text or the name of the stored procedure.";
}
17 changes: 17 additions & 0 deletions Source/Core/Core/ParameterNameMessages.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
namespace Open.Database.Extensions;

/// <summary>
/// The messages of the checks on a parameter's name: one text for each fact,
/// used by every place that makes the check.
/// </summary>
internal static class ParameterNameMessages
{
/// <summary>A parameter's name is empty or white space.</summary>
public const string Blank
= "Parameter names cannot be empty or white space. "
+ "Pass the name of a parameter of the command.";

/// <summary>A parameter other than a return parameter has no name.</summary>
public const string NullOnlyForReturn
= "Parameter names can only be null for a return parameter.";
}
6 changes: 1 addition & 5 deletions Source/Core/DbQuery.cs
Original file line number Diff line number Diff line change
Expand Up @@ -188,11 +188,7 @@ public static DbQuery Procedure(string name)

// The one check of a command text (a definition's, and a command's).
internal static string Checked(string text, string paramName)
=> DbQueryCall.CheckedText(
text,
paramName,
"The command cannot be empty or white space. "
+ "Pass the SQL text or the name of the stored procedure.");
=> DbQueryCall.CheckedText(text, paramName, CommandTextMessages.Blank);

/// <summary>
/// Returns a new definition with the command timeout set;
Expand Down
5 changes: 1 addition & 4 deletions Source/Core/DbQueryCall.cs
Original file line number Diff line number Diff line change
Expand Up @@ -168,10 +168,7 @@ DbQueryCall Bound()
}

internal static string CheckedName(string name)
=> CheckedText(
name,
nameof(name),
"Parameter names cannot be empty or white space.");
=> CheckedText(name, nameof(name), ParameterNameMessages.Blank);

/// <summary>Checks a text that must be given and not blank.</summary>
/// <param name="text">The text.</param>
Expand Down
2 changes: 1 addition & 1 deletion Source/Core/ExpressiveCommandBase.Param.cs
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,7 @@ public Param(
{
if (name is null) throw new ArgumentNullException(nameof(name));
if (string.IsNullOrWhiteSpace(name))
throw new ArgumentException("Parameter names cannot be empty or white space.", nameof(name));
throw new ArgumentException(ParameterNameMessages.Blank, nameof(name));
Contract.EndContractBlock();

Name = name;
Expand Down
12 changes: 0 additions & 12 deletions Source/Core/ExpressiveCommandBase.cs
Original file line number Diff line number Diff line change
Expand Up @@ -2047,16 +2047,4 @@ public ValueTask<T> ExecuteReturnAsync<T>(
async ValueTask<T> ReturnAsync<T>(CancellationToken cancellationToken)
=> RowMap<T>.ConvertScalar(
await ExecuteReturnAsync(cancellationToken).ConfigureAwait(false));

/// <summary>
/// Gets what the transform overloads hand to the caller's function.
/// </summary>
/// <remarks>
/// NULL (<see cref="DBNull"/>) becomes <see langword="null"/>, like no row;
/// any other value is passed unchanged.
/// </remarks>
/// <param name="value">The raw value from the provider.</param>
/// <returns>The value to pass on.</returns>
private protected static object? ScalarValue(object? value)
=> value is DBNull ? null : value;
}
4 changes: 2 additions & 2 deletions Source/Core/ExpressiveDbCommandBase.cs
Original file line number Diff line number Diff line change
Expand Up @@ -190,7 +190,7 @@ public async ValueTask<T> ExecuteScalarAsync<T>(
Contract.EndContractBlock();

return transform(
ScalarValue(
CoreExtensions.DBNullValueToNull(
await ExecuteScalarAsync(cancellationToken)
.ConfigureAwait(false)));
}
Expand Down Expand Up @@ -237,7 +237,7 @@ public async ValueTask<T> ExecuteScalarAsync<T>(
Contract.EndContractBlock();

return await transform(
ScalarValue(
CoreExtensions.DBNullValueToNull(
await ExecuteScalarAsync(cancellationToken)
.ConfigureAwait(false)))
.ConfigureAwait(false);
Expand Down
9 changes: 3 additions & 6 deletions Source/Core/Extensions/Command.AddParameter.cs
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,6 @@

public static partial class CommandExtensions
{
private const string ParameterNamesNotEmptyMessage = "Parameter names cannot be empty or white space.";
private const string ParameterNamesOnlyNullForReturn = "Parameter names can only be null for a return parameter.";

/// <summary>
/// Adds a parameter with the given name and value to the command, leaving the provider to infer the database type from the value.
/// </summary>
Expand All @@ -24,7 +21,7 @@ public static IDbDataParameter AddParameter(
if (name is null)
throw new ArgumentNullException(nameof(name));
else if (string.IsNullOrWhiteSpace(name))
throw new ArgumentException(ParameterNamesNotEmptyMessage, nameof(name));
throw new ArgumentException(ParameterNameMessages.Blank, nameof(name));
Contract.EndContractBlock();

IDbDataParameter c = target.CreateParameter();
Expand Down Expand Up @@ -170,9 +167,9 @@ public static IDbDataParameter AddParameterType(
if (target is null)
throw new ArgumentNullException(nameof(target));
if (direction != ParameterDirection.ReturnValue && name == null)
throw new ArgumentNullException(nameof(name), ParameterNamesOnlyNullForReturn);
throw new ArgumentNullException(nameof(name), ParameterNameMessages.NullOnlyForReturn);
else if (name != null && string.IsNullOrWhiteSpace(name))
throw new ArgumentException(ParameterNamesNotEmptyMessage, nameof(name));
throw new ArgumentException(ParameterNameMessages.Blank, nameof(name));
Contract.EndContractBlock();

IDbDataParameter c = target.CreateParameter();
Expand Down
6 changes: 1 addition & 5 deletions Source/Core/PooledArray.cs
Original file line number Diff line number Diff line change
Expand Up @@ -408,11 +408,7 @@ void ICollection<T>.CopyTo(T[] array, int arrayIndex)
"The destination is too small.", nameof(array));
}

foreach (ArrayLease<T> chunk in _chunks)
{
chunk.Span.CopyTo(array.AsSpan(arrayIndex));
arrayIndex += chunk.Used;
}
CopyTo(array.AsSpan(arrayIndex));
}

/// <summary>
Expand Down
25 changes: 16 additions & 9 deletions Source/Core/ProcedureParameterMetadata.cs
Original file line number Diff line number Diff line change
Expand Up @@ -148,14 +148,14 @@ or ArgumentException
static ParameterMetadata ReadRows(DataTable table, NameSet names)
{
DataColumnCollection columns = table.Columns;
bool hasMode = columns.Contains("PARAMETER_MODE");
bool hasScale = columns.Contains("NUMERIC_SCALE");
if (!columns.Contains("PARAMETER_NAME") || !hasMode && !hasScale)
bool hasMode = columns.Contains(ProcedureSchemaNames.ParameterModeColumn);
bool hasScale = columns.Contains(ProcedureSchemaNames.NumericScaleColumn);
if (!columns.Contains(ProcedureSchemaNames.ParameterNameColumn) || !hasMode && !hasScale)
{
return ParameterMetadata.Unknown;
}

bool hasOrdinal = columns.Contains("ORDINAL_POSITION");
bool hasOrdinal = columns.Contains(ProcedureSchemaNames.OrdinalPositionColumn);
int count = names.Names.Length;
bool[] modeIn = new bool[count];
int[] scales = new int[count];
Expand All @@ -166,9 +166,9 @@ static ParameterMetadata ReadRows(DataTable table, NameSet names)
{
// The ordinal 0 row is the return value, never a declared
// parameter.
if (hasOrdinal && IsReturnRow(row["ORDINAL_POSITION"])) continue;
if (hasOrdinal && IsReturnRow(row[ProcedureSchemaNames.OrdinalPositionColumn])) continue;

if (row["PARAMETER_NAME"] is not string { Length: > 0 } name
if (row[ProcedureSchemaNames.ParameterNameColumn] is not string { Length: > 0 } name
|| names.Find(name) is not { } entry
|| seen[entry.Index])
{
Expand All @@ -180,9 +180,9 @@ static ParameterMetadata ReadRows(DataTable table, NameSet names)
// Only the exact mode IN counts; INOUT (an OUTPUT parameter on SQL
// Server), OUT, anything unexpected and a missing value do not.
modeIn[entry.Index] = hasMode
&& row["PARAMETER_MODE"] is string mode
&& row[ProcedureSchemaNames.ParameterModeColumn] is string mode
&& string.Equals(mode, "IN", StringComparison.Ordinal);
if (hasScale) scales[entry.Index] = ScaleOf(row["NUMERIC_SCALE"]);
if (hasScale) scales[entry.Index] = ScaleOf(row[ProcedureSchemaNames.NumericScaleColumn]);
}

return any
Expand All @@ -202,7 +202,14 @@ static int ScaleOf(object value)
? scale
: ParameterMetadata.NoScale;

static bool TryInt(object value, out int result)
/// <summary>
/// Reads a value from the schema table as an <see cref="int"/>; a value that
/// is not a number that fits is not known, not a failure.
/// </summary>
/// <param name="value">The value of a schema table cell.</param>
/// <param name="result">The number; 0 when it is not known.</param>
/// <returns><see langword="true"/> if the value is a number that fits; otherwise, <see langword="false"/>.</returns>
public static bool TryInt(object value, out int result)
{
try
{
Expand Down
44 changes: 38 additions & 6 deletions Source/Core/ProcedureSchemaNames.cs
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
using System.Globalization;
using System.Text;

namespace Open.Database.Extensions;
Expand All @@ -17,6 +16,37 @@ static class ProcedureSchemaNames
/// </summary>
public const string Collection = "ProcedureParameters";

/// <summary>
/// The column of the collection with a parameter's name.
/// </summary>
public const string ParameterNameColumn
= "PARAMETER_NAME";

/// <summary>
/// The column of the collection with a parameter's position, 0 for the
/// return value.
/// </summary>
public const string OrdinalPositionColumn
= "ORDINAL_POSITION";

/// <summary>
/// The column of the collection with the schema of the procedure.
/// </summary>
public const string SpecificSchemaColumn
= "SPECIFIC_SCHEMA";

/// <summary>
/// The column of the collection with a parameter's mode.
/// </summary>
public const string ParameterModeColumn
= "PARAMETER_MODE";

/// <summary>
/// The column of the collection with a parameter's numeric scale.
/// </summary>
public const string NumericScaleColumn
= "NUMERIC_SCALE";

/// <summary>
/// Gets the names of the parameters a stored procedure declares.
/// </summary>
Expand Down Expand Up @@ -177,16 +207,18 @@ static ImmutableArray<string> Names(DataTable? table, bool schemaGiven)
if (table is null) return default;

DataColumnCollection columns = table.Columns;
if (!columns.Contains("PARAMETER_NAME") || !columns.Contains("ORDINAL_POSITION")) return default;
if (!columns.Contains(ParameterNameColumn) || !columns.Contains(OrdinalPositionColumn)) return default;

if (!schemaGiven && SpansSchemas(table)) return default;

List<KeyValuePair<int, string>> found = [];
foreach (DataRow row in table.Rows)
{
if (row["PARAMETER_NAME"] is not string { Length: > 0 } name || row["ORDINAL_POSITION"] is DBNull) continue;
if (row[ParameterNameColumn] is not string { Length: > 0 } name || row[OrdinalPositionColumn] is DBNull) continue;

// A value that is not a number that fits is not known, as the metadata read of the column treats it.
if (!ProcedureParameterMetadata.TryInt(row[OrdinalPositionColumn], out int ordinal)) continue;

int ordinal = Convert.ToInt32(row["ORDINAL_POSITION"], CultureInfo.InvariantCulture);
if (ordinal > 0) found.Add(new(ordinal, name));
}

Expand All @@ -202,12 +234,12 @@ static ImmutableArray<string> Names(DataTable? table, bool schemaGiven)
// ambiguous.
public static bool SpansSchemas(DataTable table)
{
if (!table.Columns.Contains("SPECIFIC_SCHEMA")) return false;
if (!table.Columns.Contains(SpecificSchemaColumn)) return false;

string? schema = null;
foreach (DataRow row in table.Rows)
{
string current = row["SPECIFIC_SCHEMA"] as string ?? "";
string current = row[SpecificSchemaColumn] as string ?? "";
schema ??= current;
if (!string.Equals(
schema, current,
Expand Down
Loading