Skip to content

Commit 2368fa1

Browse files
committed
add(NoSQLiteTable): TryFind method
1 parent 8e4bd3e commit 2368fa1

File tree

2 files changed

+28
-0
lines changed

2 files changed

+28
-0
lines changed

src/NoSQLite/NoSQLiteTable.cs

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
using System.Buffers;
2+
using System.Diagnostics.CodeAnalysis;
23

34
namespace NoSQLite;
45

@@ -155,6 +156,31 @@ public T Find<T, TKey>(Expression<Func<T, TKey>> selector, TKey key)
155156
return found;
156157
}
157158

159+
/// <summary>
160+
/// Attempts to find and return a document by key.
161+
/// </summary>
162+
/// <typeparam name="T">The document type.</typeparam>
163+
/// <typeparam name="TKey">The key type.</typeparam>
164+
/// <param name="selector">An expression selecting the key property.</param>
165+
/// <param name="key">The key value to search for.</param>
166+
/// <param name="value">When this method returns, contains the found document if it exists; otherwise, <c>null</c>.</param>
167+
/// <returns><see langword="true"/> if a document with the specified key was found; otherwise, <see langword="false"/>.</returns>
168+
public bool TryFind<T, TKey>(Expression<Func<T, TKey>> selector, TKey key, [NotNullWhen(true)] out T? value)
169+
{
170+
var propertyPath = selector.GetPropertyPath(JsonOptions);
171+
var jsonKey = JsonSerializer.SerializeToUtf8Bytes(key, JsonOptions);
172+
173+
value = FindStmt.Execute(
174+
b =>
175+
{
176+
b.Text(1, propertyPath);
177+
b.Text(2, jsonKey);
178+
},
179+
static r => r.Deserialize<T>(0)
180+
);
181+
return value is { };
182+
}
183+
158184
private SQLiteStmt FindPropertyStmt => field ??= NewStmt($"""
159185
SELECT "documents"->('$.' || ?)
160186
FROM "{Table}"

test/NoSQLite.Test/Table.cs

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -42,6 +42,8 @@ public async Task CRUD()
4242

4343
// Find
4444
await That(() => table.Find<TestPerson, int>(p => p.Id, 15)).Throws<NoSQLiteException>().WithInnerException().And.IsTypeOf<KeyNotFoundException>();
45+
await That(() => table.TryFind<TestPerson, int>(p => p.Id, 15, out _)).IsFalse();
46+
await That(() => table.TryFind<TestPerson, int>(p => p.Id, id, out _)).IsTrue();
4547
var person5 = await That(table.Find<TestPerson, int>(p => p.Id, id)).IsNotNull();
4648

4749
// Update

0 commit comments

Comments
 (0)