Bundle: redb / redb.Postgres (redb.Postgres.txt), 82 files
Snapshot: development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages.
License: Apache-2.0. Repository: https://github.com/redbase-app/redb
Index: https://redbase.app/src/dev-2026-12-06/redb/_index.txt
====
Path: redb/redb.Postgres/Data/NpgsqlBulkOperations.cs
Snapshot: redb, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages.
License: Apache-2.0. Repository: https://github.com/redbase-app/redb
Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Postgres/Data/NpgsqlBulkOperations.cs
----
using Npgsql;
using NpgsqlTypes;
using redb.Core.Data;
using redb.Core.Models.Entities;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace redb.Postgres.Data
{
///
/// PostgreSQL implementation of IBulkOperations using COPY protocol.
/// Much faster than individual INSERTs for large datasets.
///
public class NpgsqlBulkOperations : IBulkOperations
{
private readonly IRedbConnection _db;
///
/// Create bulk operations handler.
/// Uses the same connection as the context for transaction consistency.
///
public NpgsqlBulkOperations(IRedbConnection db)
{
_db = db ?? throw new ArgumentNullException(nameof(db));
}
/// The timeout of one binary COPY, read at each load; the context hands its BulkInsertTimeout in.
internal Func TimeoutSource { get; init; } = static () => null;
///
/// Sets the importer's timeout from the configured one ( is Npgsql's "no limit");
/// null leaves the importer as the connection opened it.
///
internal static void ApplyTimeout(NpgsqlBinaryImporter writer, TimeSpan? timeout)
{
if (timeout is { } value)
writer.Timeout = value;
}
// === DATE/TIME CONVERSION HELPERS ===
///
/// Convert DateTimeOffset to UTC (required by Npgsql for timestamptz).
///
private static DateTimeOffset ToUtc(DateTimeOffset value) => value.ToUniversalTime();
///
/// Convert nullable DateTimeOffset to UTC.
///
private static DateTimeOffset? ToUtc(DateTimeOffset? value) => value?.ToUniversalTime();
///
/// Bulk insert objects using COPY protocol.
///
public async Task BulkInsertObjectsAsync(IEnumerable objects, CancellationToken cancellationToken = default)
{
var objectsList = objects.ToList();
if (!objectsList.Any()) return;
await _db.ExecuteAtomicAsync(async () =>
{
var conn = (NpgsqlConnection)await _db.GetUnderlyingConnectionAsync();
await using var writer = await conn.BeginBinaryImportAsync(
"COPY _objects (_id, _id_parent, _id_scheme, _name, _id_owner, _id_who_change, " +
"_date_create, _date_modify, _date_begin, _date_complete, _key, " +
"_value_long, _value_string, _value_guid, _value_bool, _value_double, " +
"_value_numeric, _value_datetime, _value_bytes, _note, _hash, _value_unique) FROM STDIN (FORMAT BINARY)");
ApplyTimeout(writer, TimeoutSource());
foreach (var obj in objectsList)
{
await writer.StartRowAsync();
await writer.WriteAsync(obj.Id, NpgsqlDbType.Bigint);
await WriteNullableAsync(writer, obj.IdParent, NpgsqlDbType.Bigint);
await writer.WriteAsync(obj.IdScheme, NpgsqlDbType.Bigint);
await WriteNullableAsync(writer, obj.Name, NpgsqlDbType.Text);
await writer.WriteAsync(obj.IdOwner, NpgsqlDbType.Bigint);
await writer.WriteAsync(obj.IdWhoChange, NpgsqlDbType.Bigint);
await writer.WriteAsync(ToUtc(obj.DateCreate), NpgsqlDbType.TimestampTz);
await writer.WriteAsync(ToUtc(obj.DateModify), NpgsqlDbType.TimestampTz);
await WriteNullableDateTimeAsync(writer, obj.DateBegin);
await WriteNullableDateTimeAsync(writer, obj.DateComplete);
await WriteNullableAsync(writer, obj.Key, NpgsqlDbType.Bigint);
await WriteNullableAsync(writer, obj.ValueLong, NpgsqlDbType.Bigint);
await WriteNullableAsync(writer, obj.ValueString, NpgsqlDbType.Text);
await WriteNullableAsync(writer, obj.ValueGuid, NpgsqlDbType.Uuid);
await WriteNullableAsync(writer, obj.ValueBool, NpgsqlDbType.Boolean);
await WriteNullableAsync(writer, obj.ValueDouble, NpgsqlDbType.Double);
await WriteNullableAsync(writer, obj.ValueNumeric, NpgsqlDbType.Numeric);
await WriteNullableDateTimeAsync(writer, obj.ValueDatetime);
await WriteNullableAsync(writer, obj.ValueBytes, NpgsqlDbType.Bytea);
await WriteNullableAsync(writer, obj.Note, NpgsqlDbType.Text);
await WriteNullableAsync(writer, obj.Hash, NpgsqlDbType.Uuid);
await WriteNullableAsync(writer, obj.ValueUnique, NpgsqlDbType.Text);
}
await writer.CompleteAsync(cancellationToken);
});
}
///
/// Bulk insert values using COPY protocol.
///
public async Task BulkInsertValuesAsync(IEnumerable values, CancellationToken cancellationToken = default)
{
var valuesList = values.ToList();
if (!valuesList.Any()) return;
await _db.ExecuteAtomicAsync(async () =>
{
var conn = (NpgsqlConnection)await _db.GetUnderlyingConnectionAsync();
await using var writer = await conn.BeginBinaryImportAsync(
"COPY _values (_id, _id_structure, _id_object, _String, _Long, _Guid, " +
"_Double, _DateTimeOffset, _Boolean, _ByteArray, _Numeric, _ListItem, _Object, " +
"_unique, _array_parent_id, _array_index) FROM STDIN (FORMAT BINARY)");
ApplyTimeout(writer, TimeoutSource());
foreach (var val in valuesList)
{
await writer.StartRowAsync();
await writer.WriteAsync(val.Id, NpgsqlDbType.Bigint);
await writer.WriteAsync(val.IdStructure, NpgsqlDbType.Bigint);
await writer.WriteAsync(val.IdObject, NpgsqlDbType.Bigint);
await WriteNullableAsync(writer, val.String, NpgsqlDbType.Text);
await WriteNullableAsync(writer, val.Long, NpgsqlDbType.Bigint);
await WriteNullableAsync(writer, val.Guid, NpgsqlDbType.Uuid);
await WriteNullableAsync(writer, val.Double, NpgsqlDbType.Double);
await WriteNullableDateTimeAsync(writer, val.DateTimeOffset);
await WriteNullableAsync(writer, val.Boolean, NpgsqlDbType.Boolean);
await WriteNullableAsync(writer, val.ByteArray, NpgsqlDbType.Bytea);
await WriteNullableAsync(writer, val.Numeric, NpgsqlDbType.Numeric);
await WriteNullableAsync(writer, val.ListItem, NpgsqlDbType.Bigint);
await WriteNullableAsync(writer, val.Object, NpgsqlDbType.Bigint);
await WriteNullableAsync(writer, val.Unique, NpgsqlDbType.Uuid);
await WriteNullableAsync(writer, val.ArrayParentId, NpgsqlDbType.Bigint);
await WriteNullableAsync(writer, val.ArrayIndex, NpgsqlDbType.Text);
}
await writer.CompleteAsync(cancellationToken);
});
}
///
/// Bulk update objects using UPDATE FROM VALUES.
/// Single round-trip for entire batch instead of N individual UPDATEs.
///
public async Task BulkUpdateObjectsAsync(IEnumerable objects, CancellationToken cancellationToken = default)
{
var objectsList = objects.ToList();
if (!objectsList.Any()) return;
// PostgreSQL has no hard parameter limit, but use reasonable batch size
const int batchSize = 500;
foreach (var batch in objectsList.Chunk(batchSize))
{
cancellationToken.ThrowIfCancellationRequested();
await ExecuteObjectsUpdateAsync(batch, cancellationToken);
}
}
///
/// Execute UPDATE FROM VALUES for a batch of objects.
///
private async Task ExecuteObjectsUpdateAsync(RedbObjectRow[] batch, CancellationToken cancellationToken)
{
var sb = new StringBuilder();
var parameters = new List