Public .NET API ReferenceL3 Persistence & IntegrationsStableAOT: Partial

EricksonLopez.SqlBuilder

Immutable, Native AOT-first SQL query builder and high-performance execution ecosystem for .NET 8, 9 & 10. Features type-safe AST compilation, zero-reflection source generators, Roslyn analyzers, and dialect compilers for PostgreSQL, SQL Server, MySQL, MariaDB, SQLite, and Oracle.

34 namespaces244 types1452 membersGenerated from XML docs & assemblies · UTC 2026-12-01

Showing 244 of 244 types (1452 members)

EricksonLopez.SqlBuilder#

20
class

AotSqlRendererBase

Assembly: EricksonLopez.SqlBuilder
public abstract class AotSqlRendererBase : ISqlRenderer
Implements: ISqlRenderer

Provides a base implementation for an AOT-compatible SQL renderer that generates SQL statements using pooled `Text.StringBuilder` buffers (pool-rented, not allocation-free for SQL assembly) and zero-allocation data materialization for the `IDataReader → T` hot path.

Members (7)

  • methodRenderBulkInsert<T>
    public abstract BulkSqlResult RenderBulkInsert<T>(IEnumerable<T> entities, List<EricksonLopez.SqlBuilder.ColumnSelection.IColumnSelectionRule<T>> rules, int batchSize) where T : IStaticEntityMetadata<T>

    Renders a batch of bulk INSERT statements for a collection of entities.

    entities: IEnumerable<T>
    The collection of entities to insert.
    rules: List<EricksonLopez.SqlBuilder.ColumnSelection.IColumnSelectionRule<T>>
    The column selection rules applied to the operation.
    batchSize: int
    The maximum number of entities to process per batch.

    Returns: A `Operations.BulkSqlResult` containing the generated batches.

    Type parameters: T: The type of the entities.

  • methodRenderBulkInsertIgnore<T>
    public abstract BulkSqlResult RenderBulkInsertIgnore<T>(IEnumerable<T> entities, List<EricksonLopez.SqlBuilder.ColumnSelection.IColumnSelectionRule<T>> rules, int batchSize) where T : IStaticEntityMetadata<T>

    Renders a batch of bulk INSERT IGNORE statements for a collection of entities.

    entities: IEnumerable<T>
    The collection of entities to insert.
    rules: List<EricksonLopez.SqlBuilder.ColumnSelection.IColumnSelectionRule<T>>
    The column selection rules applied to the operation.
    batchSize: int
    The maximum number of entities to process per batch.

    Returns: A `Operations.BulkSqlResult` containing the generated batches.

    Type parameters: T: The type of the entities.

  • methodRenderBulkMerge<T>
    public abstract BulkSqlResult RenderBulkMerge<T>(IEnumerable<T> entities, List<EricksonLopez.SqlBuilder.ColumnSelection.IColumnSelectionRule<T>> rules, int batchSize) where T : IStaticEntityMetadata<T>

    Renders a batch of bulk MERGE statements for a collection of entities.

    entities: IEnumerable<T>
    The collection of entities to merge.
    rules: List<EricksonLopez.SqlBuilder.ColumnSelection.IColumnSelectionRule<T>>
    The column selection rules applied to the operation.
    batchSize: int
    The maximum number of entities to process per batch.

    Returns: A `Operations.BulkSqlResult` containing the generated batches.

    Type parameters: T: The type of the entities.

  • methodRenderBulkUpdate<T>
    public abstract BulkSqlResult RenderBulkUpdate<T>(IEnumerable<T> entities, List<EricksonLopez.SqlBuilder.ColumnSelection.IColumnSelectionRule<T>> rules, int batchSize) where T : IStaticEntityMetadata<T>

    Renders a batch of bulk UPDATE statements for a collection of entities.

    entities: IEnumerable<T>
    The collection of entities to update.
    rules: List<EricksonLopez.SqlBuilder.ColumnSelection.IColumnSelectionRule<T>>
    The column selection rules applied to the operation.
    batchSize: int
    The maximum number of entities to process per batch.

    Returns: A `Operations.BulkSqlResult` containing the generated batches.

    Type parameters: T: The type of the entities.

  • methodRenderBulkUpsert<T>
    public abstract BulkSqlResult RenderBulkUpsert<T>(IEnumerable<T> entities, List<EricksonLopez.SqlBuilder.ColumnSelection.IColumnSelectionRule<T>> rules, int batchSize) where T : IStaticEntityMetadata<T>

    Renders a batch of bulk UPSERT statements for a collection of entities.

    entities: IEnumerable<T>
    The collection of entities to upsert.
    rules: List<EricksonLopez.SqlBuilder.ColumnSelection.IColumnSelectionRule<T>>
    The column selection rules applied to the operation.
    batchSize: int
    The maximum number of entities to process per batch.

    Returns: A `Operations.BulkSqlResult` containing the generated batches.

    Type parameters: T: The type of the entities.

  • methodRenderInsert<T>
    public virtual SqlResult RenderInsert<T>(T entity, Span<bool> insertMask) where T : IStaticEntityMetadata<T>

    Renders an INSERT statement for a single entity.

    entity: T
    The entity instance.
    insertMask: Span<bool>
    A span representing which columns to include in the INSERT.

    Returns: A `SqlResult` containing the generated SQL and parameters.

    Type parameters: T: The type of the entity.

  • methodRenderUpdate<T>
    public virtual SqlResult RenderUpdate<T>(T entity, Span<bool> setMask, Span<bool> whereMask) where T : IStaticEntityMetadata<T>

    Renders an UPDATE statement for a single entity.

    entity: T
    The entity instance.
    setMask: Span<bool>
    A span representing which columns to include in the SET clause.
    whereMask: Span<bool>
    A span representing which columns to use in the WHERE clause (usually primary keys).

    Returns: A `SqlResult` containing the generated SQL and parameters.

    Type parameters: T: The type of the entity.

class

CursorPaginationExtensions

Assembly: EricksonLopez.SqlBuilder
public static class CursorPaginationExtensions

Provides extension methods for implementing keyset (cursor-based) pagination.

Members (1)

  • methodSeek<T>
    public static SelectQuery<T> Seek<T>(this SelectQuery<T> query, Expression<Func<T, object>> column, object lastValue, bool ascending = true, int limit = 10) where T : class, new()

    Applies cursor-based pagination (seek method) to the query using the specified column and reference value.

    query: this SelectQuery<T>
    The query to paginate.
    column: Expression<Func<T, object>>
    The expression specifying the seek column (usually a unique sequential identifier or timestamp).
    lastValue: object
    The value of the seek column from the last retrieved row.
    ascending: bool
    If `true`, retrieves rows with values strictly greater than `lastValue`; otherwise, strictly less than.
    limit: int
    The maximum number of rows to retrieve.

    Returns: A new `SelectQuery<T>` instance with the seek condition, sorting, and row limit applied.

    Type parameters: T: The type of the entity to query. Exceptions: ArgumentException: `column` is not a valid property expression

record

DeleteQuery<T>

Assembly: EricksonLopez.SqlBuilder
public sealed record DeleteQuery<T> : IDeleteFromBuilder<T>, IDeleteWhereBuilder<T>, ISqlQuery, IAstQuery where T : class, new()
Implements: IAstQuery, IDeleteFromBuilder<T>, IDeleteWhereBuilder<T>, ISqlQuery

Represents a DELETE query syntax tree builder for the specified entity type.

Remarks:

This type is immutable. All modification methods return a new instance preserving the previous state. Type parameters: T: The type of the entity to delete.

Members (19)

  • methodAddNode
    public DeleteQuery<T> AddNode(ISqlNode node)

    Appends the specified node to the query AST.

    node: ISqlNode
    The node to append to the query.

    Returns: A new `DeleteQuery<T>` instance containing the appended node.

  • methodAnd
    public IDeleteWhereBuilder<T> And(System.Linq.Expressions.Expression<System.Func<T, bool>> predicate)

    Appends an AND logical condition to the current WHERE clause using a predicate expression.

    predicate: System.Linq.Expressions.Expression<System.Func<T, bool>>
    The expression defining the additional filtering condition.

    Returns: A new `IDeleteWhereBuilder<T>` instance with the filter applied.

  • methodBuild
    public SqlResult Build(ISqlCompiler compiler)

    Compiles the abstract syntax tree into an executable SQL string and its parameters.

    compiler: ISqlCompiler
    The SQL compiler specific to the target database provider.

    Returns: The compiled SQL result.

  • methodDelete
    public IDeleteFromBuilder<T> Delete(string? tableName = null)

    Specifies the target table for the DELETE operation.

    tableName: string?
    An optional table name to override the default entity table.

    Returns: A new `IDeleteFromBuilder<T>` instance with the target table applied.

  • methodJoin
    public IDeleteFromBuilder<T> Join(string tableName, string alias, string on)

    Appends an INNER JOIN clause to the query.

    tableName: string
    The name of the table to join.
    alias: string
    The alias for the joined table.
    on: string
    The join condition.

    Returns: A new `IDeleteFromBuilder<T>` instance with the join clause applied.

  • methodJoin<TOther>
    public IDeleteFromBuilder<T> Join<TOther>(System.Linq.Expressions.Expression<System.Func<T, TOther, bool>> onExpression) where TOther : new()

    Appends a strongly-typed INNER JOIN clause to the query based on a predicate.

    onExpression: System.Linq.Expressions.Expression<System.Func<T, TOther, bool>>
    The predicate expression defining the join condition.

    Returns: A new `IDeleteFromBuilder<T>` instance with the join clause applied.

    Type parameters: TOther: The type of the joined entity.

  • methodOr
    public IDeleteWhereBuilder<T> Or(System.Linq.Expressions.Expression<System.Func<T, bool>> predicate)

    Appends an OR logical condition to the current WHERE clause using a predicate expression.

    predicate: System.Linq.Expressions.Expression<System.Func<T, bool>>
    The expression defining the alternative filtering condition.

    Returns: A new `IDeleteWhereBuilder<T>` instance with the filter applied.

  • methodReturning
    public IDeleteWhereBuilder<T> Returning(params string[] columns)

    Specifies the columns to return from the deleted rows.

    columns: params string[]
    The names of the columns to return.

    Returns: A new `IDeleteWhereBuilder<T>` instance with the returning clause applied.

  • methodReturning<TResult>
    public IDeleteWhereBuilder<T> Returning<TResult>(System.Linq.Expressions.Expression<System.Func<T, TResult>> selector)

    Specifies the columns to return from the deleted rows using a predicate expression.

    selector: System.Linq.Expressions.Expression<System.Func<T, TResult>>
    The expression defining the columns to return.

    Returns: A new `IDeleteWhereBuilder<T>` instance with the returning clause applied.

    Type parameters: TResult: The type of the projected result.

  • methodUsing
    public IDeleteFromBuilder<T> Using(string tableName, string? alias = null)

    Specifies an additional source table for the DELETE operation (USING clause).

    tableName: string
    The name of the additional table.
    alias: string?
    An optional alias for the additional table.

    Returns: A new `IDeleteFromBuilder<T>` instance with the USING clause applied.

    Exceptions: ArgumentException: `tableName` is empty or whitespace, or `alias` is whitespace

  • methodUsing<TOther>
    public IDeleteFromBuilder<T> Using<TOther>(string? alias = null) where TOther : new()

    Specifies an additional strongly-typed source table for the DELETE operation (USING clause).

    alias: string?
    An optional alias for the additional table.

    Returns: A new `IDeleteFromBuilder<T>` instance with the USING clause applied.

    Type parameters: TOther: The type of the additional entity.

  • methodWhere
    public IDeleteWhereBuilder<T> Where(FormattableString condition)

    Appends a raw SQL WHERE clause to filter the rows to delete.

    condition: FormattableString
    The formatted string containing the raw filter and its parameters.

    Returns: A new `IDeleteWhereBuilder<T>` instance with the filter applied.

  • methodWhere
    public IDeleteWhereBuilder<T> Where(System.Linq.Expressions.Expression<System.Func<T, bool>> predicate)

    Appends a WHERE clause to filter the rows to delete using a predicate expression.

    predicate: System.Linq.Expressions.Expression<System.Func<T, bool>>
    The expression defining the filtering condition.

    Returns: A new `IDeleteWhereBuilder<T>` instance with the filter applied.

  • methodWhereAll
    public IDeleteWhereBuilder<T> WhereAll()

    Explicitly indicates that the delete should apply to all rows without filtering.

    Returns: The current `IDeleteWhereBuilder<T>` instance.

  • methodWhereExists
    public IDeleteWhereBuilder<T> WhereExists(ISqlQuery subquery)

    Appends a WHERE EXISTS (subquery) condition to the DELETE statement.

    subquery: ISqlQuery
    The subquery to evaluate inside EXISTS.

    Returns: A new `IDeleteWhereBuilder<T>` instance with the EXISTS filter applied.

  • methodWhereNotExists
    public IDeleteWhereBuilder<T> WhereNotExists(ISqlQuery subquery)

    Appends a WHERE NOT EXISTS (subquery) condition to the DELETE statement.

    subquery: ISqlQuery
    The subquery to evaluate inside NOT EXISTS.

    Returns: A new `IDeleteWhereBuilder<T>` instance with the NOT EXISTS filter applied.

  • methodWithTag
    public DeleteQuery<T> WithTag(string tag)

    Creates a new `DeleteQuery<T>` with the specified diagnostic tag.

    tag: string
    The diagnostic tag to associate with the query.

    Returns: A new query instance containing the applied tag.

  • propertyNodes
    public System.Collections.Immutable.ImmutableArray<ISqlNode> Nodes { get; init; }

    Gets the collection of nodes that compose the abstract syntax tree of this query.

  • propertyTag
    public string? Tag { get; init; }

    Gets the optional tag associated with this query for diagnostics or interception.

class

DiffUpdateExtensions

Assembly: EricksonLopez.SqlBuilder
public static class DiffUpdateExtensions

Provides extension methods for generating UPDATE statements based on entity state differences.

Members (1)

  • methodApplyDiff<T>
    public static IUpdateWhereBuilder<T> ApplyDiff<T>(this IUpdateSetBuilder<T> builder, T originalEntity, T currentEntity) where T : class, new()

    Applies SET assignments to the UPDATE query by comparing the original and current state of the entity. Only properties that have changed will generate a SET assignment.

    builder: this IUpdateSetBuilder<T>
    The update query builder to configure.
    originalEntity: T
    The original state of the entity before any modifications.
    currentEntity: T
    The current state of the entity containing the modifications.

    Returns: An `IUpdateWhereBuilder<T>` instance configured with the detected changes.

    Utilizes the `Annotations.ISqlEntity` interface generated by the source generator to perform a reflection-free comparison. Type parameters: T: The type of the entity to update. Exceptions: InvalidOperationException: No changes are detected between the original and current entity, the builder is not of type `UpdateQuery<T>`, or `T` does not implement `Annotations.ISqlEntity`

class

DynamicSortingExtensions

Assembly: EricksonLopez.SqlBuilder
public static class DynamicSortingExtensions

Provides extension methods for applying dynamic sorting to queries using string-based column names.

Members (1)

  • methodOrderByDynamic<T>
    public static SelectQuery<T> OrderByDynamic<T>(this SelectQuery<T> query, string sortBy, bool descending = false) where T : class, new()

    Appends an ORDER BY clause to the query using a string-based column name or property name. Safely resolves the property to its database column name using the entity's metadata cache.

    query: this SelectQuery<T>
    The query to apply the sorting to.
    sortBy: string
    The name of the property or column to sort by. Can include an alias prefix (e.g., "u.Name").
    descending: bool
    If `true`, sorts in descending order; otherwise, ascending.

    Returns: A new `SelectQuery<T>` instance with the sorting rule applied.

    Type parameters: T: The type of the entity to query. Exceptions: ArgumentException: `sortBy` contains invalid characters and cannot be safely resolved

record

InsertQuery<T>

Assembly: EricksonLopez.SqlBuilder
public sealed record InsertQuery<T> : IAstQuery where T : class, new()
Implements: IAstQuery

Represents an INSERT query syntax tree builder for the specified entity type.

Remarks:

This type is immutable. All modification methods return a new instance preserving the previous state. Type parameters: T: The type of the entity to insert.

Members (18)

  • methodAddNode
    public InsertQuery<T> AddNode(ISqlNode node)

    Appends the specified node to the query AST.

    node: ISqlNode
    The node to append to the query.

    Returns: A new `InsertQuery<T>` instance containing the appended node.

  • methodBuild
    public SqlResult Build(ISqlCompiler compiler)

    Compiles the abstract syntax tree into an executable SQL string and its parameters.

    compiler: ISqlCompiler
    The SQL compiler specific to the target database provider.

    Returns: The compiled SQL result.

  • methodBulk
    public InsertQuery<T> Bulk(IEnumerable<T> entities, bool ignoreNulls = false)

    Appends multiple sets of values for bulk insertion based on the provided collection of entities.

    entities: IEnumerable<T>
    The collection of entities to insert.
    ignoreNulls: bool
    If `true`, properties with null values in the first entity will determine the columns excluded for all entities.

    Returns: A new `InsertQuery<T>` instance configured for bulk insertion.

    Exceptions: InvalidOperationException: An entity in the collection does not implement `Annotations.ISqlEntity` or metadata column count does not match value count

  • methodDefaultValues
    public InsertQuery<T> DefaultValues()

    Configures the insertion to use default values for all columns.

    Returns: A new `InsertQuery<T>` instance configured to use default values.

  • methodDoNothing
    public InsertQuery<T> DoNothing()

    Configures the conflict resolution to ignore the insertion if a conflict occurs.

    Returns: A new `InsertQuery<T>` instance with the ignore action applied.

  • methodDoUpdate
    public InsertQuery<T> DoUpdate(Expression<Func<T, object>> updateSelector)

    Configures the conflict resolution to update specific columns if a conflict occurs.

    updateSelector: Expression<Func<T, object>>
    The expression specifying the columns to update.

    Returns: A new `InsertQuery<T>` instance with the update action applied.

  • methodDoUpdate
    public InsertQuery<T> DoUpdate(FormattableString sql)

    Configures the conflict resolution to perform a raw SQL update if a conflict occurs.

    sql: FormattableString
    The formatted string containing the raw update command and its parameters.

    Returns: A new `InsertQuery<T>` instance with the raw update action applied.

  • methodFromSelect
    public InsertQuery<T> FromSelect(ISqlQuery selectQuery, params string[] columns)

    Configures this INSERT query to use the results of a SELECT query as the source data. Generates: `INSERT INTO table [(columns)] SELECT ...`.

    selectQuery: ISqlQuery
    The SELECT query whose results will be inserted.
    columns: params string[]
    Optional explicit column list. When provided, generates `INSERT INTO table (col1, col2) SELECT ...`. When omitted, the column list is inferred from the SELECT result set.

    Returns: A new `InsertQuery<T>` with the INSERT INTO ... SELECT node applied.

    Example:

    var archiveQuery = Sql.From<Order>()
        .Where(o => o.Status == "completed");
    
    var insertFromSelect = Sql.Insert<ArchiveOrder>(null!)
        .Into("archive_orders")
        .FromSelect(archiveQuery, "id", "customer_id", "total");
  • methodInto
    public InsertQuery<T> Into(string tableName)

    Specifies the target table for the insertion.

    tableName: string
    The name of the target table.

    Returns: A new `InsertQuery<T>` instance with the target table applied.

  • methodOnConflict
    public InsertQuery<T> OnConflict(Expression<Func<T, object>> keySelector)

    Specifies the columns that define a conflict target for UPSERT operations using a predicate expression.

    keySelector: Expression<Func<T, object>>
    The expression specifying the conflict target columns.

    Returns: A new `InsertQuery<T>` instance with the conflict target applied.

  • methodOnConflict
    public InsertQuery<T> OnConflict(params string[]? columns)

    Specifies the columns that define a conflict target for UPSERT operations.

    columns: params string[]?
    The names of the columns defining the conflict target.

    Returns: A new `InsertQuery<T>` instance with the conflict target applied.

  • methodReturning
    public InsertQuery<T> Returning(params string[] columns)

    Specifies the columns to return from the inserted row.

    columns: params string[]
    The names of the columns to return.

    Returns: A new `InsertQuery<T>` instance with the returning clause applied.

  • methodReturning<TResult>
    public InsertQuery<T> Returning<TResult>(Expression<Func<T, TResult>> selector)

    Specifies the columns to return from the inserted row using a predicate expression.

    selector: Expression<Func<T, TResult>>
    The expression defining the columns to return.

    Returns: A new `InsertQuery<T>` instance with the returning clause applied.

    Type parameters: TResult: The type of the projected result.

  • methodValues
    public InsertQuery<T> Values(T entity, bool ignoreNulls = true)

    Appends the values to insert based on the properties of the provided entity.

    entity: T
    The entity instance containing the data to insert.
    ignoreNulls: bool
    If `true`, properties with null values will be excluded from the insertion.

    Returns: A new `InsertQuery<T>` instance with the values applied.

    Exceptions: InvalidOperationException: `T` does not implement `Annotations.ISqlEntity` (entity must be decorated with [SqlEntity]) or metadata column count does not match value count

  • methodValues
    public InsertQuery<T> Values(params object?[] values)

    Appends the specified raw values to the insertion.

    values: params object?[]
    The array of values to insert.

    Returns: A new `InsertQuery<T>` instance with the values applied.

  • methodWithTag
    public InsertQuery<T> WithTag(string tag)

    Creates a new `InsertQuery<T>` with the specified diagnostic tag.

    tag: string
    The diagnostic tag to associate with the query.

    Returns: A new query instance containing the applied tag.

  • propertyNodes
    public System.Collections.Immutable.ImmutableArray<ISqlNode> Nodes { get; init; }

    Gets the collection of nodes that compose the abstract syntax tree of this query.

  • propertyTag
    public string? Tag { get; init; }

    Gets the optional tag associated with this query for diagnostics or interception.

class

Param

Assembly: EricksonLopez.SqlBuilder
public static class Param

Provides factory methods for creating explicitly typed SQL parameters.

Members (6)

  • methodArray<T>
    public static SqlParameter Array<T>(T[] values)

    Creates a SQL parameter containing an array of values.

    values: T[]
    The array of values.

    Returns: A new `SqlParameter` containing the array.

    Type parameters: T: The type of the elements in the array.

  • methodComposite
    public static SqlParameter Composite(object value, string compositeTypeName)

    Creates a SQL parameter explicitly marked with a custom composite type name.

    value: object
    The composite value.
    compositeTypeName: string
    The name of the composite type in the database.

    Returns: A new `SqlParameter` configured with the composite type name.

  • methodEnumAsString<TEnum>
    public static SqlParameter EnumAsString<TEnum>(TEnum value) where TEnum : Enum

    Creates a SQL parameter that converts the specified enumeration value to its string representation.

    value: TEnum
    The enumeration value to convert.

    Returns: A new `SqlParameter` containing the string representation of the enumeration.

    Type parameters: TEnum: The type of the enumeration.

  • methodIn<T>
    public static SqlParameter In<T>(IEnumerable<T> values)

    Creates a SQL parameter optimized for IN clause expansion.

    values: IEnumerable<T>
    The collection of values to match against.

    Returns: A new `SqlParameter` configured for an IN clause.

    Type parameters: T: The type of the elements in the collection.

  • methodJson
    public static SqlParameter Json(object value)

    Creates a SQL parameter explicitly marked as the 'json' database type.

    value: object
    The value to serialize or pass as JSON.

    Returns: A new `SqlParameter` configured for JSON.

  • methodJsonb
    public static SqlParameter Jsonb(object value)

    Creates a SQL parameter explicitly marked as the 'jsonb' database type (PostgreSQL specific).

    value: object
    The value to serialize or pass as JSONB.

    Returns: A new `SqlParameter` configured for JSONB.

record

QueryContract

Assembly: EricksonLopez.SqlBuilder
public sealed record QueryContract(string Fingerprint, IReadOnlyList<string> Tables, IReadOnlyList<string> Columns)

Represents the verifiable shape of a compiled query.

Members (4)

  • constructorQueryContract
    public QueryContract(string Fingerprint, IReadOnlyList<string> Tables, IReadOnlyList<string> Columns)

    Initializes a new instance of QueryContract.

    Fingerprint: string
    The unique cryptographic hash identifying the structural shape of the query.
    Tables: IReadOnlyList<string>
    The collection of table names referenced in the query.
    Columns: IReadOnlyList<string>
    The collection of column names projected by the query.
  • propertyColumns
    public IReadOnlyList<string> Columns { get; init; }

    The collection of column names projected by the query.

  • propertyFingerprint
    public string Fingerprint { get; init; }

    The unique cryptographic hash identifying the structural shape of the query.

  • propertyTables
    public IReadOnlyList<string> Tables { get; init; }

    The collection of table names referenced in the query.

class

QueryContractExtensions

Assembly: EricksonLopez.SqlBuilder
public static class QueryContractExtensions

Provides extension methods for generating query contracts.

Members (1)

  • methodGetContract
    public static QueryContract GetContract(this IAstQuery query)

    Generates a contract representing the verifiable structural shape of the specified query.

    query: this IAstQuery
    The query to analyze.

    Returns: A new `QueryContract` containing the fingerprint and referenced database objects.

record

RawQuery

Assembly: EricksonLopez.SqlBuilder
public sealed record RawQuery : ISqlQuery
Implements: ISqlQuery

Represents a raw SQL query that is always fully parameterized. Unlike Dapper's raw string approach, `RawQuery` never accepts string concatenation and enforces NativeAOT-safe parameter passing.

Members (7)

  • constructorRawQuery
    public RawQuery(FormattableString sql)

    Initializes a new instance of the `RawQuery` class from an interpolated SQL string.

    sql: FormattableString
    The formattable SQL string containing parameter placeholders and values.

    Example:

    int minAge = 18;
    string status = "Active";
    var q = new RawQuery($"SELECT * FROM users WHERE age >= {minAge} AND status = {status}");
    // SQL: SELECT * FROM users WHERE age >= @p0 AND status = @p1
  • constructorRawQuery
    public RawQuery(string sql, object? parameters = null)

    Initializes a new instance of the `RawQuery` class from a SQL string and parameter collection.

    sql: string
    The parameterized SQL string.
    parameters: object?
    The parameter values container.

    Exceptions: ArgumentException: `sql` is empty or whitespace; InvalidOperationException: Entity column count does not match value count; NotSupportedException: `parameters` uses reflection or an unsupported format

  • methodBuild
    public SqlResult Build(ISqlCompiler compiler)

    Compiles the raw query into an executable SQL string and its parameters.

    compiler: ISqlCompiler
    The SQL compiler specific to the target database provider.

    Returns: The compiled SQL result.

  • methodWithTag
    public RawQuery WithTag(string tag)

    Creates a new `RawQuery` with the specified diagnostic tag.

    tag: string
    The diagnostic tag to associate with the query.

    Returns: A new query instance containing the applied tag.

  • propertyParameters
    public object? Parameters { get; }

    Gets the parameters associated with this query.

  • propertyRawSql
    public string RawSql { get; }

    Gets the parameterized SQL command text.

  • propertyTag
    public string? Tag { get; init; }

    Gets the optional tag associated with this query for diagnostics or interception.

record

SelectQuery<T>

Assembly: EricksonLopez.SqlBuilder
public sealed record SelectQuery<T> : IAstQuery where T : class, new()
Implements: IAstQuery

Represents a SELECT query syntax tree builder for the specified entity type.

Remarks:

This type is immutable. All modification methods return a new instance preserving the previous state. Type parameters: T: The type of the entity to query.

Members (92)

  • methodAddNode
    public SelectQuery<T> AddNode(ISqlNode node)

    Appends the specified node to the query AST.

    node: ISqlNode
    The node to append to the query.

    Returns: A new `SelectQuery<T>` instance containing the appended node.

  • methodAlias
    public SelectQuery<T> Alias(string alias)

    Applies an alias to the current query when used as a subquery.

    alias: string
    The alias to apply.

    Returns: A new `SelectQuery<T>` instance with the alias applied.

  • methodAnd
    public SelectQuery<T> And(Expression<Func<T, bool>> predicate)

    Appends an AND logical condition to the current WHERE clause using a predicate expression.

    predicate: Expression<Func<T, bool>>
    The expression defining the additional filtering condition.

    Returns: A new `SelectQuery<T>` instance with the filter applied.

  • methodAsAvg
    public SelectQuery<T> AsAvg(string column, string? alias = null)

    Projects an AVG(column) aggregation.

    column: string
    The column name to average.
    alias: string?
    Optional column alias.

    Returns: A new `SelectQuery<T>` instance with the average projection applied.

    Exceptions: ArgumentException: `column` is empty, whitespace, or invalid

  • methodAsCount
    public SelectQuery<T> AsCount(string alias = "")

    Projects a COUNT(*) aggregation.

    alias: string
    The column alias (default: "count").

    Returns: A new `SelectQuery<T>` instance with the count projection applied.

  • methodAsMax
    public SelectQuery<T> AsMax(string column, string? alias = null)

    Projects a MAX(column) aggregation.

    column: string
    The column name to find the maximum for.
    alias: string?
    Optional column alias.

    Returns: A new `SelectQuery<T>` instance with the max projection applied.

    Exceptions: ArgumentException: `column` is empty, whitespace, or invalid

  • methodAsMin
    public SelectQuery<T> AsMin(string column, string? alias = null)

    Projects a MIN(column) aggregation.

    column: string
    The column name to find the minimum for.
    alias: string?
    Optional column alias.

    Returns: A new `SelectQuery<T>` instance with the min projection applied.

    Exceptions: ArgumentException: `column` is empty, whitespace, or invalid

  • methodAsSum
    public SelectQuery<T> AsSum(string column, string? alias = null)

    Projects a SUM(column) aggregation.

    column: string
    The column name to sum.
    alias: string?
    Optional column alias.

    Returns: A new `SelectQuery<T>` instance with the sum projection applied.

    Exceptions: ArgumentException: `column` is empty, whitespace, or invalid

  • methodBuild
    public SqlResult Build(ISqlCompiler compiler)

    Compiles the abstract syntax tree into an executable SQL string and its parameters.

    compiler: ISqlCompiler
    The SQL compiler specific to the target database provider.

    Returns: The compiled SQL result.

  • methodCTE
    public SelectQuery<T> CTE(string name, ISqlQuery query)

    Defines a Common Table Expression (CTE) for the query.

    name: string
    The name assigned to the CTE.
    query: ISqlQuery
    The query defining the CTE data set.

    Returns: A new `SelectQuery<T>` instance with the CTE applied.

  • methodCTE
    public SelectQuery<T> CTE(string name, ISqlQuery query, MaterializationHint hint)

    Defines a Common Table Expression (CTE) for the query with an explicit materialization hint.

    name: string
    The name assigned to the CTE.
    query: ISqlQuery
    The query defining the CTE data set.
    hint: MaterializationHint
    The materialization hint (e.g. MATERIALIZED or NOT MATERIALIZED in PostgreSQL).

    Returns: A new `SelectQuery<T>` instance with the CTE applied.

  • methodCrossApply
    public SelectQuery<T> CrossApply(IAstQuery subquery, string alias)

    Appends a CROSS APPLY clause (SQL Server) / INNER JOIN LATERAL (PostgreSQL) to the query. CROSS APPLY returns only rows from the outer query that have matching rows in the correlated subquery.

    subquery: IAstQuery
    The correlated subquery to apply.
    alias: string
    The alias for the applied result set.

    Returns: A new `SelectQuery<T>` instance with the CROSS APPLY applied.

    Supported by: SQL Server, PostgreSQL (as CROSS JOIN LATERAL). Not supported by: SQLite, MySQL < 8.0, Oracle.

  • methodCrossApply<TSub>
    public SelectQuery<T> CrossApply<TSub>(Func<SelectQuery<TSub>, IAstQuery> subqueryFactory, string alias) where TSub : class, new()

    Appends a CROSS APPLY clause constructed via a fluent subquery factory.

    subqueryFactory: Func<SelectQuery<TSub>, IAstQuery>
    A delegate that configures and returns the correlated subquery.
    alias: string
    The alias for the applied result set.

    Returns: A new `SelectQuery<T>` instance with the CROSS APPLY applied.

    Type parameters: TSub: The entity type of the correlated subquery.

  • methodCrossJoin
    public SelectQuery<T> CrossJoin(string tableName, string alias)

    Appends a CROSS JOIN clause to the query.

    tableName: string
    The name of the table to join.
    alias: string
    The alias for the joined table.

    Returns: A new `SelectQuery<T>` instance with the join clause applied.

  • methodDistinct
    public SelectQuery<T> Distinct()

    Applies the DISTINCT modifier to the current SELECT projection to eliminate duplicate rows.

    Returns: A new `SelectQuery<T>` instance with the DISTINCT modifier applied.

  • methodExcept
    public SelectQuery<T> Except(ISqlQuery query)

    Appends an EXCEPT set operation to return rows from the current query that are not present in the specified query.

    query: ISqlQuery
    The query to compare against.

    Returns: A new `SelectQuery<T>` instance with the set operation applied.

  • methodExceptAll
    public SelectQuery<T> ExceptAll(ISqlQuery query)

    Appends an EXCEPT ALL set operation to return rows from the current query not present in the specified query, preserving duplicate counts.

    query: ISqlQuery
    The query to compare against.

    Returns: A new `SelectQuery<T>` instance with the set operation applied.

  • methodFrom
    public SelectQuery<T> From(ISqlQuery query, string alias)

    Specifies a subquery as the primary data source.

    query: ISqlQuery
    The subquery to execute.
    alias: string
    The alias for the subquery result set.

    Returns: A new `SelectQuery<T>` instance with the subquery FROM clause applied.

  • methodFrom
    public SelectQuery<T> From(string tableName, string? alias = null)

    Specifies the primary table to query from.

    tableName: string
    The name of the source table.
    alias: string?
    An optional alias for the source table.

    Returns: A new `SelectQuery<T>` instance with the FROM clause applied.

    Exceptions: ArgumentException: `tableName` is empty or whitespace, or `alias` is whitespace

  • methodFullJoin
    public SelectQuery<T> FullJoin(string tableName, string alias, string on)

    Appends a FULL OUTER JOIN clause to the query.

    tableName: string
    The name of the table to join.
    alias: string
    The alias for the joined table.
    on: string
    The join condition.

    Returns: A new `SelectQuery<T>` instance with the join clause applied.

  • methodGroupBy
    public SelectQuery<T> GroupBy(params string[] columns)

    Appends a GROUP BY clause to the query to aggregate results.

    columns: params string[]
    The names of the columns to group by.

    Returns: A new `SelectQuery<T>` instance with the grouping applied.

  • methodGroupByCube
    public SelectQuery<T> GroupByCube(params string[] columns)

    Appends a GROUP BY CUBE clause to the query for multidimensional aggregations.

    columns: params string[]
    The names of the columns to produce cube cross-tabulations for.

    Returns: A new `SelectQuery<T>` instance with the CUBE grouping applied.

  • methodGroupByRollup
    public SelectQuery<T> GroupByRollup(params string[] columns)

    Appends a GROUP BY ROLLUP clause to the query for hierarchical subtotal aggregations.

    columns: params string[]
    The names of the columns in the rollup hierarchy.

    Returns: A new `SelectQuery<T>` instance with the ROLLUP grouping applied.

  • methodGroupingSets
    public SelectQuery<T> GroupingSets(params IReadOnlyList<string>[] sets)

    Appends a GROUP BY GROUPING SETS clause to the query for explicit multi-level aggregations.

    sets: params IReadOnlyList<string>[]
    The explicit column grouping combinations.

    Returns: A new `SelectQuery<T>` instance with the GROUPING SETS grouping applied.

  • methodHaving
    public SelectQuery<T> Having(Expression<Func<T, bool>> predicate)

    Appends a HAVING clause to filter aggregated results using a predicate expression.

    predicate: Expression<Func<T, bool>>
    The expression defining the aggregation filter.

    Returns: A new `SelectQuery<T>` instance with the aggregation filter applied.

  • methodHaving
    public SelectQuery<T> Having(FormattableString condition)

    Appends a raw SQL HAVING clause to filter aggregated results.

    condition: FormattableString
    The formatted string containing the raw filter and its parameters.

    Returns: A new `SelectQuery<T>` instance with the aggregation filter applied.

  • methodInnerJoin
    public SelectQuery<T> InnerJoin(string tableName, string alias, string on)

    Appends an INNER JOIN clause to the query. This overload is an explicit alias for `Join(string, string, string)` and produces identical SQL. Prefer `Join<TOther>(Expression<Func<T, TOther, bool>>)` for strongly-typed joins using entity expressions.

    tableName: string
    The name of the table to join.
    alias: string
    The alias for the joined table.
    on: string
    The join condition.

    Returns: A new `SelectQuery<T>` instance with the join clause applied.

  • methodIntersect
    public SelectQuery<T> Intersect(ISqlQuery query)

    Appends an INTERSECT set operation to return only the rows present in both query results.

    query: ISqlQuery
    The query to intersect with.

    Returns: A new `SelectQuery<T>` instance with the set operation applied.

  • methodIntersectAll
    public SelectQuery<T> IntersectAll(ISqlQuery query)

    Appends an INTERSECT ALL set operation to return matching rows from both queries, preserving duplicates.

    query: ISqlQuery
    The query to intersect with.

    Returns: A new `SelectQuery<T>` instance with the set operation applied.

  • methodJoin
    public SelectQuery<T> Join(string tableName, string alias, string on)

    Appends an INNER JOIN clause to the query.

    tableName: string
    The name of the table to join.
    alias: string
    The alias for the joined table.
    on: string
    The join condition.

    Returns: A new `SelectQuery<T>` instance with the join clause applied.

  • methodJoin<TOther>
    public SelectQuery<T> Join<TOther>(Expression<Func<T, TOther, bool>> on) where TOther : new()

    Appends a strongly-typed INNER JOIN clause to the query based on a predicate.

    on: Expression<Func<T, TOther, bool>>
    The predicate expression defining the join condition.

    Returns: A new `SelectQuery<T>` instance with the join clause applied.

    Type parameters: TOther: The type of the joined entity.

  • methodJoinSubquery
    public SelectQuery<T> JoinSubquery(IAstQuery subquery, string alias, string? on = null)

    Appends a JOIN to a subquery (non-lateral, standard INNER JOIN with subquery in parentheses).

    subquery: IAstQuery
    The subquery to join.
    alias: string
    The alias for the derived table.
    on: string?
    The ON condition for the join.

    Returns: A new `SelectQuery<T>` instance with the subquery join applied.

  • methodJoinSubquery<TSub>
    public SelectQuery<T> JoinSubquery<TSub>(IAstQuery subquery, string alias, Expression<Func<T, TSub, bool>> on)

    Appends a JOIN to a subquery with a typed ON expression.

    subquery: IAstQuery
    The subquery to join.
    alias: string
    The alias for the derived table.
    on: Expression<Func<T, TSub, bool>>
    The typed predicate expression defining the join condition.

    Returns: A new `SelectQuery<T>` instance with the subquery join applied.

    Type parameters: TSub: The entity type of the subquery.

  • methodLateralJoin
    public SelectQuery<T> LateralJoin(IAstQuery subquery, string alias, string? on = null)

    Appends a LATERAL JOIN clause (INNER JOIN LATERAL) to the query. The subquery is evaluated per-row of the outer query, like a correlated subquery.

    subquery: IAstQuery
    The correlated subquery to laterally join.
    alias: string
    The alias for the lateral result set.
    on: string?
    Optional ON condition string. Usually omitted for LATERAL (use `TRUE` or `null`).

    Returns: A new `SelectQuery<T>` instance with the LATERAL JOIN applied.

    Supported by: PostgreSQL, MySQL 8.0+. For SQL Server, use CROSS APPLY syntax via `RawJoin`. Not supported by: SQLite, Oracle (use alternatives).

  • methodLateralJoin<TSub>
    public SelectQuery<T> LateralJoin<TSub>(Func<SelectQuery<TSub>, IAstQuery> subqueryFactory, string alias, Expression<Func<T, TSub, bool>> on) where TSub : class, new()

    Appends a LATERAL JOIN clause constructed via a fluent subquery factory with a typed ON expression.

    subqueryFactory: Func<SelectQuery<TSub>, IAstQuery>
    A delegate that configures and returns the correlated subquery.
    alias: string
    The alias for the lateral result set.
    on: Expression<Func<T, TSub, bool>>
    The typed predicate expression defining the join condition.

    Returns: A new `SelectQuery<T>` instance with the LATERAL JOIN applied.

    Type parameters: TSub: The entity type of the correlated subquery.

  • methodLateralJoin<TSub>
    public SelectQuery<T> LateralJoin<TSub>(Func<SelectQuery<TSub>, IAstQuery> subqueryFactory, string alias, string? on = null) where TSub : class, new()

    Appends a LATERAL JOIN clause constructed via a fluent subquery factory.

    subqueryFactory: Func<SelectQuery<TSub>, IAstQuery>
    A delegate that configures and returns the correlated subquery.
    alias: string
    The alias for the lateral result set.
    on: string?
    Optional raw ON condition string.

    Returns: A new `SelectQuery<T>` instance with the LATERAL JOIN applied.

    Type parameters: TSub: The entity type of the correlated subquery.

  • methodLateralJoin<TSub>
    public SelectQuery<T> LateralJoin<TSub>(IAstQuery subquery, string alias, Expression<Func<T, TSub, bool>> on)

    Appends a LATERAL JOIN clause (INNER JOIN LATERAL) with a typed ON expression.

    subquery: IAstQuery
    The correlated subquery to laterally join.
    alias: string
    The alias for the lateral result set.
    on: Expression<Func<T, TSub, bool>>
    The typed predicate expression defining the join condition between the outer query and the lateral subquery.

    Returns: A new `SelectQuery<T>` instance with the LATERAL JOIN applied.

    Type parameters: TSub: The entity type of the correlated subquery.

  • methodLateralLeftJoin
    public SelectQuery<T> LateralLeftJoin(IAstQuery subquery, string alias, string? on = null)

    Appends a LEFT LATERAL JOIN clause (LEFT JOIN LATERAL) to the query. Rows from the outer query that have no match in the lateral subquery are preserved.

    subquery: IAstQuery
    The correlated subquery to laterally join.
    alias: string
    The alias for the lateral result set.
    on: string?
    Optional ON condition string.

    Returns: A new `SelectQuery<T>` instance with the LEFT LATERAL JOIN applied.

  • methodLateralLeftJoin<TSub>
    public SelectQuery<T> LateralLeftJoin<TSub>(Func<SelectQuery<TSub>, IAstQuery> subqueryFactory, string alias, Expression<Func<T, TSub, bool>> on) where TSub : class, new()

    Appends a LEFT LATERAL JOIN clause constructed via a fluent subquery factory with a typed ON expression.

    subqueryFactory: Func<SelectQuery<TSub>, IAstQuery>
    A delegate that configures and returns the correlated subquery.
    alias: string
    The alias for the lateral result set.
    on: Expression<Func<T, TSub, bool>>
    The typed predicate expression defining the join condition.

    Returns: A new `SelectQuery<T>` instance with the LEFT LATERAL JOIN applied.

    Type parameters: TSub: The entity type of the correlated subquery.

  • methodLateralLeftJoin<TSub>
    public SelectQuery<T> LateralLeftJoin<TSub>(Func<SelectQuery<TSub>, IAstQuery> subqueryFactory, string alias, string? on = null) where TSub : class, new()

    Appends a LEFT LATERAL JOIN clause constructed via a fluent subquery factory.

    subqueryFactory: Func<SelectQuery<TSub>, IAstQuery>
    A delegate that configures and returns the correlated subquery.
    alias: string
    The alias for the lateral result set.
    on: string?
    Optional raw ON condition string.

    Returns: A new `SelectQuery<T>` instance with the LEFT LATERAL JOIN applied.

    Type parameters: TSub: The entity type of the correlated subquery.

  • methodLateralLeftJoin<TSub>
    public SelectQuery<T> LateralLeftJoin<TSub>(IAstQuery subquery, string alias, Expression<Func<T, TSub, bool>> on)

    Appends a LEFT LATERAL JOIN clause (LEFT JOIN LATERAL) with a typed ON expression.

    subquery: IAstQuery
    The correlated subquery to laterally join.
    alias: string
    The alias for the lateral result set.
    on: Expression<Func<T, TSub, bool>>
    The typed predicate expression defining the join condition between the outer query and the lateral subquery.

    Returns: A new `SelectQuery<T>` instance with the LEFT LATERAL JOIN applied.

    Type parameters: TSub: The entity type of the correlated subquery.

  • methodLeftJoin
    public SelectQuery<T> LeftJoin(string tableName, string alias, string on)

    Appends a LEFT OUTER JOIN clause to the query.

    tableName: string
    The name of the table to join.
    alias: string
    The alias for the joined table.
    on: string
    The join condition.

    Returns: A new `SelectQuery<T>` instance with the join clause applied.

  • methodLeftJoinSubquery
    public SelectQuery<T> LeftJoinSubquery(IAstQuery subquery, string alias, string? on = null)

    Appends a LEFT JOIN to a subquery (non-lateral).

    subquery: IAstQuery
    The subquery to join.
    alias: string
    The alias for the derived table.
    on: string?
    The ON condition for the join.

    Returns: A new `SelectQuery<T>` instance with the subquery join applied.

  • methodLeftJoinSubquery<TSub>
    public SelectQuery<T> LeftJoinSubquery<TSub>(IAstQuery subquery, string alias, Expression<Func<T, TSub, bool>> on)

    Appends a LEFT JOIN to a subquery with a typed ON expression.

    subquery: IAstQuery
    The subquery to join.
    alias: string
    The alias for the derived table.
    on: Expression<Func<T, TSub, bool>>
    The typed predicate expression defining the join condition.

    Returns: A new `SelectQuery<T>` instance with the subquery join applied.

    Type parameters: TSub: The entity type of the subquery.

  • methodLimit
    public SelectQuery<T> Limit(int limit)

    Restricts the maximum number of rows returned by the query.

    limit: int
    The maximum number of rows.

    Returns: A new `SelectQuery<T>` instance with the row limit applied.

    Exceptions: ArgumentOutOfRangeException: `limit` is negative

  • methodOffset
    public SelectQuery<T> Offset(int offset)

    Specifies the number of rows to skip before returning results.

    offset: int
    The number of rows to skip.

    Returns: A new `SelectQuery<T>` instance with the offset applied.

    Exceptions: ArgumentOutOfRangeException: `offset` is negative

  • methodOr
    public SelectQuery<T> Or(Expression<Func<T, bool>> predicate)

    Appends an OR logical condition to the current WHERE clause using a predicate expression.

    predicate: Expression<Func<T, bool>>
    The expression defining the alternative filtering condition.

    Returns: A new `SelectQuery<T>` instance with the filter applied.

  • methodOrExists
    public SelectQuery<T> OrExists(ISqlQuery subquery)

    Appends an OR EXISTS (subquery) condition to the query.

    subquery: ISqlQuery
    The subquery to evaluate inside EXISTS.

    Returns: A new `SelectQuery<T>` instance with the OR EXISTS filter applied.

  • methodOrHaving
    public SelectQuery<T> OrHaving(Expression<Func<T, bool>> predicate)

    Appends an OR logical condition to the current HAVING clause using a predicate expression.

    predicate: Expression<Func<T, bool>>
    The expression defining the alternative aggregation filter.

    Returns: A new `SelectQuery<T>` instance with the aggregation filter applied.

  • methodOrHaving
    public SelectQuery<T> OrHaving(FormattableString condition)

    Appends a raw SQL OR condition to the current HAVING clause.

    condition: FormattableString
    The formatted string containing the raw alternative filter and its parameters.

    Returns: A new `SelectQuery<T>` instance with the aggregation filter applied.

  • methodOrNotExists
    public SelectQuery<T> OrNotExists(ISqlQuery subquery)

    Appends an OR NOT EXISTS (subquery) condition to the query.

    subquery: ISqlQuery
    The subquery to evaluate inside NOT EXISTS.

    Returns: A new `SelectQuery<T>` instance with the OR NOT EXISTS filter applied.

  • methodOrderBy
    public SelectQuery<T> OrderBy(Expression<Func<T, object>> keySelector)

    Appends an ORDER BY clause to sort the results in ascending order.

    keySelector: Expression<Func<T, object>>
    The expression specifying the sorting key.

    Returns: A new `SelectQuery<T>` instance with the sorting rule applied.

  • methodOrderBy
    public SelectQuery<T> OrderBy(Expression<Func<T, object>> keySelector, NullsPosition nulls)

    Appends an ORDER BY clause to sort the results in ascending order with explicit NULL placement.

    keySelector: Expression<Func<T, object>>
    The expression specifying the sorting key.
    nulls: NullsPosition
    Controls whether NULLs appear first or last in the ordering.

    Returns: A new `SelectQuery<T>` instance with the sorting rule applied.

  • methodOrderBy
    public SelectQuery<T> OrderBy(FormattableString sql)

    Appends a raw SQL ORDER BY clause to sort the results in ascending order.

    sql: FormattableString
    The formatted string containing the raw sorting column or expression.

    Returns: A new `SelectQuery<T>` instance with the sorting rule applied.

  • methodOrderByDescending
    public SelectQuery<T> OrderByDescending(Expression<Func<T, object>> keySelector)

    Appends an ORDER BY clause to sort the results in descending order.

    keySelector: Expression<Func<T, object>>
    The expression specifying the sorting key.

    Returns: A new `SelectQuery<T>` instance with the sorting rule applied.

  • methodOrderByDescending
    public SelectQuery<T> OrderByDescending(Expression<Func<T, object>> keySelector, NullsPosition nulls)

    Appends an ORDER BY clause to sort the results in descending order with explicit NULL placement.

    keySelector: Expression<Func<T, object>>
    The expression specifying the sorting key.
    nulls: NullsPosition
    Controls whether NULLs appear first or last in the ordering.

    Returns: A new `SelectQuery<T>` instance with the sorting rule applied.

  • methodOrderByDescending
    public SelectQuery<T> OrderByDescending(FormattableString sql)

    Appends a raw SQL ORDER BY clause to sort the results in descending order.

    sql: FormattableString
    The formatted string containing the raw sorting column or expression.

    Returns: A new `SelectQuery<T>` instance with the sorting rule applied.

  • methodOuterApply
    public SelectQuery<T> OuterApply(IAstQuery subquery, string alias)

    Appends an OUTER APPLY clause (SQL Server) / LEFT JOIN LATERAL (PostgreSQL) to the query. OUTER APPLY preserves rows from the outer query even when the correlated subquery returns no rows.

    subquery: IAstQuery
    The correlated subquery to apply.
    alias: string
    The alias for the applied result set.

    Returns: A new `SelectQuery<T>` instance with the OUTER APPLY applied.

  • methodOuterApply<TSub>
    public SelectQuery<T> OuterApply<TSub>(Func<SelectQuery<TSub>, IAstQuery> subqueryFactory, string alias) where TSub : class, new()

    Appends an OUTER APPLY clause constructed via a fluent subquery factory.

    subqueryFactory: Func<SelectQuery<TSub>, IAstQuery>
    A delegate that configures and returns the correlated subquery.
    alias: string
    The alias for the applied result set.

    Returns: A new `SelectQuery<T>` instance with the OUTER APPLY applied.

    Type parameters: TSub: The entity type of the correlated subquery.

  • methodRawJoin
    public SelectQuery<T> RawJoin(FormattableString joinSql)

    Appends a raw SQL JOIN clause to the query.

    joinSql: FormattableString
    The formatted string containing the raw join command and its parameters.

    Returns: A new `SelectQuery<T>` instance with the join clause applied.

  • methodRawSelect
    public SelectQuery<T> RawSelect(FormattableString sql)

    Specifies a raw SQL projection for the SELECT clause.

    sql: FormattableString
    The formatted string containing the raw projection and its parameters.

    Returns: A new `SelectQuery<T>` instance with the raw projection applied.

  • methodRecursiveCTE
    public SelectQuery<T> RecursiveCTE(string name, ISqlQuery query)

    Defines a recursive Common Table Expression (CTE) for the query.

    name: string
    The name assigned to the CTE.
    query: ISqlQuery
    The query defining the CTE data set.

    Returns: A new `SelectQuery<T>` instance with the recursive CTE applied.

  • methodRecursiveCTE
    public SelectQuery<T> RecursiveCTE(string name, ISqlQuery query, MaterializationHint hint)

    Defines a recursive Common Table Expression (CTE) for the query with an explicit materialization hint.

    name: string
    The name assigned to the CTE.
    query: ISqlQuery
    The query defining the CTE data set.
    hint: MaterializationHint
    The materialization hint (e.g. MATERIALIZED or NOT MATERIALIZED in PostgreSQL).

    Returns: A new `SelectQuery<T>` instance with the recursive CTE applied.

  • methodRightJoin
    public SelectQuery<T> RightJoin(string tableName, string alias, string on)

    Appends a RIGHT OUTER JOIN clause to the query.

    tableName: string
    The name of the table to join.
    alias: string
    The alias for the joined table.
    on: string
    The join condition.

    Returns: A new `SelectQuery<T>` instance with the join clause applied.

  • methodSeekAfter
    public SelectQuery<T> SeekAfter(params CursorKey[] keys)

    Applies a forward composite keyset cursor, seeking rows that come after the specified anchor keys.

    keys: params CursorKey[]
    The anchor key columns and their values from the last row on the current page.

    Returns: A new `SelectQuery<T>` with the cursor WHERE predicate applied.

    For two ascending keys `(col1, col2)` with values `(v1, v2)`, generates: `WHERE (col1 > @p0 OR (col1 = @p0 AND col2 > @p1))` Keyset pagination requires deterministic column ordering.

  • methodSeekBefore
    public SelectQuery<T> SeekBefore(params CursorKey[] keys)

    Applies a backward composite keyset cursor, seeking rows that come before the specified anchor keys.

    keys: params CursorKey[]
    The anchor key columns and their values from the first row on the current page.

    Returns: A new `SelectQuery<T>` with the cursor WHERE predicate applied.

  • methodSelect
    public SelectQuery<T> Select(params EricksonLopez.SqlBuilder.Abstractions.Nodes.WindowFunctionNode[] windows)

    Appends one or more window function expressions to the SELECT clause.

    windows: params EricksonLopez.SqlBuilder.Abstractions.Nodes.WindowFunctionNode[]
    One or more `WindowFunctionNode` instances produced by the `Window` factory.

    Returns: A new `SelectQuery<T>` instance with the window functions applied.

    Example:

    var query = Sql.From<Employee>()
        .Select(
            Window.Rank<Employee>()
                  .PartitionBy(e => e.Department)
                  .OrderByDescending(e => e.Salary)
                  .As("rank"),
            Window.RowNumber<Employee>()
                  .OrderBy(e => e.CreatedAt)
                  .As("row_num"));
  • methodSelect
    public SelectQuery<T> Select(ISqlQuery subquery, string alias)

    Specifies a scalar subquery projection for the SELECT clause.

    subquery: ISqlQuery
    The subquery that calculates the scalar value.
    alias: string
    The alias name assigned to the scalar column.

    Returns: A new `SelectQuery<T>` instance with the scalar subquery applied.

    Exceptions: ArgumentNullException: `subquery` is `null`; ArgumentException: `alias` is empty or whitespace

  • methodSelect
    public SelectQuery<T> Select(params string[] columns)

    Specifies the columns to project in the SELECT clause.

    columns: params string[]
    The names of the columns to select.

    Returns: A new `SelectQuery<T>` instance with the projection applied.

  • methodSelect<TResult>
    public SelectQuery<T> Select<TResult>(Expression<Func<T, TResult>> selector)

    Specifies the projection for the SELECT clause using an expression.

    selector: Expression<Func<T, TResult>>
    The expression defining the columns to select.

    Returns: A new `SelectQuery<T>` instance with the projection applied.

    Type parameters: TResult: The type of the projected result.

  • methodSelectCase
    public SelectQuery<T> SelectCase(Abstractions.Nodes.CaseNode caseNode)

    Adds a pre-built `Nodes.CaseNode` directly to the SELECT clause.

    caseNode: Abstractions.Nodes.CaseNode
    The prepared case node containing the conditional logic.

    Returns: A new `SelectQuery<T>` instance with the CASE column added.

  • methodSelectCase
    public SelectQuery<T> SelectCase(System.Func<Builders.CaseExpressionBuilder, Builders.CaseExpressionBuilder> configure)

    Adds a CASE expression column to the SELECT clause using a fluent builder.

    configure: System.Func<Builders.CaseExpressionBuilder, Builders.CaseExpressionBuilder>
    A delegate that configures the `Builders.CaseExpressionBuilder`.

    Returns: A new `SelectQuery<T>` instance with the CASE column added.

    Example:

    Sql.From<User>()
       .SelectCase(c => c
           .When("status = {0}", 1).Then("'Active'")
           .When("status = {0}", 2).Then("'Inactive'")
           .Else("'Unknown'")
           .As("status_label"));
  • methodThenBy
    public SelectQuery<T> ThenBy(Expression<Func<T, object>> keySelector)

    Appends a subsequent sort condition in ascending order.

    keySelector: Expression<Func<T, object>>
    The expression specifying the additional sorting key.

    Returns: A new `SelectQuery<T>` instance with the additional sorting rule applied.

  • methodThenBy
    public SelectQuery<T> ThenBy(Expression<Func<T, object>> keySelector, NullsPosition nulls)

    Appends a subsequent sort condition in ascending order with explicit NULL placement.

    keySelector: Expression<Func<T, object>>
    The expression specifying the additional sorting key.
    nulls: NullsPosition
    Controls whether NULLs appear first or last.

    Returns: A new `SelectQuery<T>` instance with the additional sorting rule applied.

  • methodThenByDescending
    public SelectQuery<T> ThenByDescending(Expression<Func<T, object>> keySelector)

    Appends a subsequent sort condition in descending order.

    keySelector: Expression<Func<T, object>>
    The expression specifying the additional sorting key.

    Returns: A new `SelectQuery<T>` instance with the additional sorting rule applied.

  • methodThenByDescending
    public SelectQuery<T> ThenByDescending(Expression<Func<T, object>> keySelector, NullsPosition nulls)

    Appends a subsequent sort condition in descending order with explicit NULL placement.

    keySelector: Expression<Func<T, object>>
    The expression specifying the additional sorting key.
    nulls: NullsPosition
    Controls whether NULLs appear first or last.

    Returns: A new `SelectQuery<T>` instance with the additional sorting rule applied.

  • methodUnion
    public SelectQuery<T> Union(ISqlQuery query)

    Appends a UNION set operation to combine results with another query, eliminating duplicates.

    query: ISqlQuery
    The query to union with.

    Returns: A new `SelectQuery<T>` instance with the set operation applied.

  • methodUnionAll
    public SelectQuery<T> UnionAll(ISqlQuery query)

    Appends a UNION ALL set operation to combine results with another query, retaining duplicates.

    query: ISqlQuery
    The query to union with.

    Returns: A new `SelectQuery<T>` instance with the set operation applied.

  • methodWhere
    public SelectQuery<T> Where(Expression<Func<T, bool>> predicate)

    Appends a WHERE clause to the query using a predicate expression.

    predicate: Expression<Func<T, bool>>
    The expression defining the filtering condition.

    Returns: A new `SelectQuery<T>` instance with the filter applied.

  • methodWhere
    public SelectQuery<T> Where(FormattableString condition)

    Appends a raw SQL WHERE clause to the query.

    condition: FormattableString
    The formatted string containing the raw filter and its parameters.

    Returns: A new `SelectQuery<T>` instance with the filter applied.

  • methodWhereColumns
    public SelectQuery<T> WhereColumns(string column1, string operator, string column2)

    Appends a comparison between two columns to the WHERE clause.

    column1: string
    The left-hand column name.
    operator: string
    The comparison operator (e.g. "=", "<>", "<", ">", "<=", ">=").
    column2: string
    The right-hand column name.

    Returns: A new `SelectQuery<T>` instance.

    Exceptions: ArgumentException: `column1`, `operator`, or `column2` is empty or whitespace

  • methodWhereDate
    public SelectQuery<T> WhereDate(string column, string operator, object value)

    Appends a date comparison condition to the WHERE clause.

    column: string
    The column name containing the date.
    operator: string
    The comparison operator (e.g., "=", ">", "<").
    value: object
    The date value to compare against.

    Returns: A new `SelectQuery<T>` instance.

    Exceptions: ArgumentException: `column` or `operator` is empty, whitespace, or invalid

  • methodWhereDay
    public SelectQuery<T> WhereDay(string column, string operator, int day)

    Appends a day comparison predicate to the WHERE clause.

    column: string
    The column name containing the date.
    operator: string
    The comparison operator (e.g., "=", ">", "<").
    day: int
    The day integer (1-31) to compare against.

    Returns: A new `SelectQuery<T>` instance.

    Exceptions: ArgumentException: `column` or `operator` is empty, whitespace, or invalid

  • methodWhereExists
    public SelectQuery<T> WhereExists(ISqlQuery subquery)

    Appends a WHERE EXISTS (subquery) condition to the query.

    subquery: ISqlQuery
    The subquery to evaluate inside EXISTS.

    Returns: A new `SelectQuery<T>` instance with the EXISTS filter applied.

  • methodWhereMonth
    public SelectQuery<T> WhereMonth(string column, string operator, int month)

    Appends a month comparison predicate to the WHERE clause.

    column: string
    The column name containing the date.
    operator: string
    The comparison operator (e.g., "=", ">", "<").
    month: int
    The month integer (1-12) to compare against.

    Returns: A new `SelectQuery<T>` instance.

    Exceptions: ArgumentException: `column` or `operator` is empty, whitespace, or invalid

  • methodWhereNotExists
    public SelectQuery<T> WhereNotExists(ISqlQuery subquery)

    Appends a WHERE NOT EXISTS (subquery) condition to the query.

    subquery: ISqlQuery
    The subquery to evaluate inside NOT EXISTS.

    Returns: A new `SelectQuery<T>` instance with the NOT EXISTS filter applied.

  • methodWhereYear
    public SelectQuery<T> WhereYear(string column, string operator, int year)

    Appends a year comparison predicate to the WHERE clause.

    column: string
    The column name containing the date.
    operator: string
    The comparison operator (e.g., "=", ">", "<").
    year: int
    The year integer to compare against.

    Returns: A new `SelectQuery<T>` instance.

    Exceptions: ArgumentException: `column` or `operator` is empty, whitespace, or invalid

  • methodWindow
    public SelectQuery<T> Window(string name, string[]? partitionBy = null, string[]? orderBy = null)

    Defines a named window specification for window functions.

    name: string
    The name of the window.
    partitionBy: string[]?
    An optional array of column names to partition the window.
    orderBy: string[]?
    An optional array of column names to order the window.

    Returns: A new `SelectQuery<T>` instance with the window specification applied.

    Exceptions: ArgumentException: `name` is empty, whitespace, or invalid, or an element in `orderBy` is invalid

  • methodWindowPage
    public SelectQuery<T> WindowPage(int pageNumber, int pageSize, string orderByColumn, bool descending = false)

    Applies Window-based pagination (ROW_NUMBER) using the specified column for ordering.

    pageNumber: int
    The one-based page number to retrieve.
    pageSize: int
    The maximum number of items per page. Must be greater than zero.
    orderByColumn: string
    The name of the column to sort by before assigning row numbers.
    descending: bool
    If `true`, sorts the column in descending order; otherwise, ascending.

    Returns: A new `SelectQuery<T>` instance with window-based pagination applied.

    This is an alternative to Offset pagination for better deep-pagination performance. Exceptions: ArgumentOutOfRangeException: `pageSize` is less than or equal to zero

  • methodWithTag
    public SelectQuery<T> WithTag(string tag)

    Creates a new `SelectQuery<T>` with the specified diagnostic tag.

    tag: string
    The diagnostic tag to associate with the query.

    Returns: A new query instance containing the applied tag.

  • propertyNodes
    public System.Collections.Immutable.ImmutableArray<ISqlNode> Nodes { get; init; }

    Gets the collection of nodes that compose the abstract syntax tree of this query.

  • propertyTag
    public string? Tag { get; init; }

    Gets the optional tag associated with this query for diagnostics or interception.

class

Sql

Assembly: EricksonLopez.SqlBuilder
public static class Sql

Provides entry points and static factory methods for constructing type-safe SQL queries.

Members (22)

  • methodAll<TItem>
    public static bool All<TItem>(this TItem value, IEnumerable<TItem> collection)

    Evaluates if a value is equal to all elements in the specified collection.

    value: this TItem
    The value to test.
    collection: IEnumerable<TItem>
    The candidate collection.

    Returns: `true` if the value equals all elements in the collection; otherwise, `false`.

    This method serves as an expression marker for SQL translation and throws if called directly. Type parameters: TItem: The type of items to evaluate. Exceptions: InvalidOperationException: The method is invoked directly at runtime rather than inside a query expression

  • methodAny<TItem>
    public static bool Any<TItem>(this TItem value, IEnumerable<TItem> collection)

    Evaluates if a value is equal to any element in the specified collection.

    value: this TItem
    The value to test.
    collection: IEnumerable<TItem>
    The candidate collection.

    Returns: `true` if the value equals any element in the collection; otherwise, `false`.

    This method serves as an expression marker for SQL translation and throws if called directly. Type parameters: TItem: The type of items to evaluate. Exceptions: InvalidOperationException: The method is invoked directly at runtime rather than inside a query expression

  • methodBetween<TItem>
    public static bool Between<TItem>(this TItem value, TItem from, TItem to) where TItem : System.IComparable<TItem>

    Evaluates if a value is inclusively between two bounds. Translates to SQL: `column BETWEEN @from AND @to`.

    value: this TItem
    The column value (the left-hand side of BETWEEN).
    from: TItem
    The lower bound (inclusive).
    to: TItem
    The upper bound (inclusive).

    Returns: `true` if the value is inclusively between the bounds; otherwise, `false`.

    This method serves as an expression marker for SQL translation and throws if called directly. Type parameters: TItem: The type of the value and bounds (must be comparable). Exceptions: InvalidOperationException: The method is invoked directly at runtime rather than inside a query expression Example:

    // WHERE age BETWEEN 18 AND 65
    Sql.From<User>().Where(u => u.Age.Between(18, 65))
  • methodBulk<T>
    public static EricksonLopez.SqlBuilder.Builders.Bulk.BulkBuilder<T> Bulk<T>(IEnumerable<T> entities) where T : EricksonLopez.SqlBuilder.Abstractions.Metadata.IStaticEntityMetadata<T>

    Creates a highly optimized bulk operation builder for a collection of entities.

    entities: IEnumerable<T>
    The entities to process in bulk.

    Returns: A new `Bulk.BulkBuilder<T>` instance.

    Type parameters: T: The type of the entities, which must implement `Metadata.IStaticEntityMetadata<T>`.

  • methodBulkInsert<T>
    public static InsertQuery<T> BulkInsert<T>(IEnumerable<T> entities) where T : class, new()

    Creates a new bulk INSERT query for the specified entities.

    entities: IEnumerable<T>
    The collection of entities to insert.

    Returns: A new `InsertQuery<T>` instance configured for bulk insertion.

    Type parameters: T: The type of the entities to insert.

  • methodCoalesce<TItem>
    public static TItem Coalesce<TItem>(this TItem? value, TItem fallback)

    Returns the first non-null value from the provided column and the fallback. Translates to SQL: `COALESCE(column, @fallback)`.

    value: this TItem?
    The column value (the left-hand side of COALESCE).
    fallback: TItem
    The fallback value returned when `value` is null.

    Returns: The first non-null value among the operands.

    This method serves as an expression marker for SQL translation and throws if called directly. Type parameters: TItem: The type of the value and fallback. Exceptions: InvalidOperationException: The method is invoked directly at runtime rather than inside a query expression Example:

    // WHERE COALESCE(name, 'Unknown') = 'Alice'
    Sql.From<User>().Where(u => u.Name.Coalesce("Unknown") == "Alice")
  • methodCoalesce<TItem>
    public static TItem Coalesce<TItem>(TItem? val1, TItem? val2, TItem fallback)

    Returns the first non-null value among the provided values. Translates to SQL: `COALESCE(val1, val2, fallback)`.

    val1: TItem?
    The first candidate value.
    val2: TItem?
    The second candidate value.
    fallback: TItem
    The fallback value.

    Returns: The first non-null value among the arguments.

    This method serves as an expression marker for SQL translation and throws if called directly. Type parameters: TItem: The type of the values. Exceptions: InvalidOperationException: The method is invoked directly at runtime rather than inside a query expression

  • methodDelete<T>
    public static EricksonLopez.SqlBuilder.Abstractions.IDeleteFromBuilder<T> Delete<T>() where T : class, new()

    Creates a new DELETE query for the specified entity type.

    Returns: A new `Abstractions.IDeleteFromBuilder<T>` instance.

    Type parameters: T: The type of the entity to delete.

  • methodFrom<T>
    public static SelectQuery<T> From<T>() where T : class, new()

    Creates a new SELECT query for the specified entity type.

    Returns: A new `SelectQuery<T>` instance.

    Type parameters: T: The type of the entity to query.

  • methodFrom<T>
    public static SelectQuery<T> From<T>(string tableName) where T : class, new()

    Creates a new SELECT query for the specified entity type with an explicitly specified table name.

    tableName: string
    The explicit table name.

    Returns: A new `SelectQuery<T>` instance.

    Type parameters: T: The type of the entity to query.

  • methodILike
    public static bool ILike(this string value, string pattern)

    Evaluates if a string matches a pattern (case-insensitive) for SQL translation.

    value: this string
    The source string to evaluate.
    pattern: string
    The pattern string to compare against.

    Returns: `true` if the string matches the pattern; otherwise, `false`.

    This method serves as an expression marker for SQL translation and throws if called directly. Exceptions: InvalidOperationException: The method is invoked directly at runtime rather than inside a query expression

  • methodInsert<T>
    public static InsertQuery<T> Insert<T>(T entity) where T : class, new()

    Creates a new INSERT query for the specified entity.

    entity: T
    The entity instance containing the data to insert.

    Returns: A new `InsertQuery<T>` instance configured with the entity values.

    Type parameters: T: The type of the entity to insert.

  • methodInsertFrom<T>
    public static InsertQuery<T> InsertFrom<T>(ISqlQuery selectQuery, params string[] columns) where T : class, new()

    Creates an INSERT INTO ... SELECT query, inserting the results of a SELECT into the target table.

    selectQuery: ISqlQuery
    The SELECT query whose results are to be inserted.
    columns: params string[]
    Optional explicit column names for the INSERT column list.

    Returns: An `InsertQuery<T>` configured with an INSERT INTO ... SELECT node.

    Type parameters: T: The type of the target entity. Example:

    var archiveQuery = Sql.From<Order>().Where(o => o.Status == "completed");
    var query = Sql.InsertFrom<ArchiveOrder>(archiveQuery, "id", "customer_id", "total");
  • methodIsDistinctFrom<TItem>
    public static bool IsDistinctFrom<TItem>(TItem left, TItem right)

    Evaluates if two values are distinct, treating NULL as a comparable value (null-safe inequality). Translates to SQL: `left IS DISTINCT FROM right`.

    left: TItem
    The left operand.
    right: TItem
    The right operand.

    Returns: `true` if the values are distinct; otherwise, `false`.

    This method serves as an expression marker for SQL translation and throws if called directly. Type parameters: TItem: The type of the values to compare. Exceptions: InvalidOperationException: The method is invoked directly at runtime rather than inside a query expression

  • methodIsNotDistinctFrom<TItem>
    public static bool IsNotDistinctFrom<TItem>(TItem left, TItem right)

    Evaluates if two values are not distinct, treating NULL as a comparable value (null-safe equality). Translates to SQL: `left IS NOT DISTINCT FROM right`.

    left: TItem
    The left operand.
    right: TItem
    The right operand.

    Returns: `true` if the values are not distinct; otherwise, `false`.

    This method serves as an expression marker for SQL translation and throws if called directly. Type parameters: TItem: The type of the values to compare. Exceptions: InvalidOperationException: The method is invoked directly at runtime rather than inside a query expression

  • methodNullIf<TItem>
    public static TItem? NullIf<TItem>(TItem? value, TItem? target)

    Returns NULL if both arguments are equal, otherwise returns the first argument. Translates to SQL: `NULLIF(value, target)`.

    value: TItem?
    The primary value.
    target: TItem?
    The value to compare against.

    Returns: This exists only for SQL expression building and always throws at runtime.

    Type parameters: TItem: The type of the values to compare. Exceptions: InvalidOperationException: The method is invoked directly at runtime rather than inside a query expression

  • methodOuter<TEntity, TProp>
    public static TProp Outer<TEntity, TProp>(System.Linq.Expressions.Expression<System.Func<TEntity, TProp>> column)

    References an outer query column inside a correlated subquery or LATERAL join. Translates to SQL referencing the outer table's column identifier.

    column: System.Linq.Expressions.Expression<System.Func<TEntity, TProp>>
    The expression identifying the outer column.

    Returns: This exists only for SQL expression building and always throws at runtime.

    Type parameters: TEntity: The outer entity type.; TProp: The property type. Exceptions: InvalidOperationException: The method is invoked directly at runtime rather than inside a query expression

  • methodRaw
    public static RawQuery Raw(System.FormattableString sql)

    Creates a raw SQL query from a `System.FormattableString`.

    sql: System.FormattableString
    The formatted string containing the SQL command and its parameters.

    Returns: A new `RawQuery` instance.

  • methodRaw
    public static RawQuery Raw(string sql, object? parameters = null)

    Creates a raw SQL query from a string and optional parameters.

    sql: string
    The SQL string.
    parameters: object?
    Optional parameters dictionary or entity.

    Returns: A new `RawQuery` instance.

  • methodRegisterTypeHandler<T>
    public static void RegisterTypeHandler<T>(EricksonLopez.SqlBuilder.Abstractions.ITypeHandler handler)

    Registers a custom type handler for the specified type.

    handler: EricksonLopez.SqlBuilder.Abstractions.ITypeHandler
    The handler implementation to use for the type.

    Type parameters: T: The type to register the handler for.

  • methodUpdate<T>
    public static EricksonLopez.SqlBuilder.Abstractions.IUpdateSetBuilder<T> Update<T>() where T : class, new()

    Creates a new UPDATE query for the specified entity type.

    Returns: A new `Abstractions.IUpdateSetBuilder<T>` instance.

    Initiates an explicit update where columns must be set manually. Type parameters: T: The type of the entity to update.

  • methodUpdate<T>
    public static EricksonLopez.SqlBuilder.Abstractions.IUpdateSetBuilder<T> Update<T>(T entity) where T : class, new()

    Creates a new UPDATE query for the specified entity.

    entity: T
    The entity instance containing the updated data.

    Returns: A new `Abstractions.IUpdateSetBuilder<T>` instance.

    Initiates a full update using the properties of the provided entity. Type parameters: T: The type of the entity to update.

class

SqlBuilderDiagnostics

Assembly: EricksonLopez.SqlBuilder
public static class SqlBuilderDiagnostics

Provides the diagnostic activity source and metrics for OpenTelemetry instrumentation.

Members (10)

  • propertyErrorQueryCounter
    public static Counter<long> ErrorQueryCounter { get; private set; }

    Gets the counter metric for the total number of SQL query execution errors.

  • propertyLogParameters
    public static bool LogParameters { get; set; }

    Gets or sets a value indicating whether parameter values are included in telemetry tags.

    Default is `false` to prevent logging sensitive data (PII).

  • propertyLoggerFactory
    public static Microsoft.Extensions.Logging.ILoggerFactory? LoggerFactory { get; set; }

    Gets or sets the optional logger factory that captures slow queries and error logging.

  • propertyMeter
    public static Meter Meter { get; private set; }

    Gets the primary `Metrics.Meter` that emits diagnostic metrics.

  • propertyQueryDurationHistogram
    public static Histogram<double> QueryDurationHistogram { get; private set; }

    Gets the histogram metric for tracking the duration of SQL queries in milliseconds.

  • propertyQueryExecutionCounter
    public static Counter<long> QueryExecutionCounter { get; private set; }

    Gets the counter metric for the total number of SQL queries executed.

  • propertySlowQueryCounter
    public static Counter<long> SlowQueryCounter { get; private set; }

    Gets the counter metric for the total number of slow SQL queries executed.

  • propertySlowQueryThresholdMs
    public static int SlowQueryThresholdMs { get; set; }

    Gets or sets the threshold in milliseconds to consider a query as slow.

    Default is 500 ms.

  • fieldActivitySource
    public static readonly ActivitySource ActivitySource

    Gets the primary `Diagnostics.ActivitySource` that emits diagnostic traces.

  • fieldSourceName
    public const string SourceName

    Represents the name of the diagnostic source.

class

SqlCompilerBase

Assembly: EricksonLopez.SqlBuilder
public abstract class SqlCompilerBase : ISqlCompiler, ISqlRenderer
Implements: ISqlCompiler, ISqlRenderer

Provides the base implementation for a SQL compiler that translates AST nodes into executable SQL queries.

Remarks:

LINQ-expression-based query methods (e.g., `.Where(x => ...)`) use reflection-based evaluation and are not compatible with NativeAOT strict trimming. Use `Sql.Raw()` or raw string overloads for AOT paths.

Members (14)

  • methodCompile
    public virtual SqlResult Compile(ISqlQuery query)

    Compiles the specified query AST into an executable SQL string and parameters.

    query: ISqlQuery
    The query to compile.

    Returns: The compiled `SqlResult` containing the SQL text and parameters.

  • methodCompile
    public virtual SqlResult Compile(ISqlQuery query, IParameterManager? existingParameters)

    Compiles the specified query AST using an optional existing parameter manager.

    query: ISqlQuery
    The query to compile.
    existingParameters: IParameterManager?
    An optional existing parameter manager to append parameters to.

    Returns: The compiled `SqlResult` containing the SQL text and parameters.

  • methodCreateParameterManager
    public virtual IParameterManager CreateParameterManager()

    Creates a new parameter manager for storing SQL parameters during compilation.

    Returns: An instance of `IParameterManager`.

  • methodEscape
    public virtual string Escape(string identifier)

    Escapes a SQL identifier, safely handling qualified names containing dots (e.g., 'schema.table').

    identifier: string
    The identifier to escape.

    Returns: The escaped identifier string.

  • methodEscapeIdentifier
    public virtual string EscapeIdentifier(string identifier)

    Escapes a raw SQL identifier string.

    identifier: string
    The raw identifier to escape.

    Returns: The escaped identifier string.

  • methodEscapeIdentifier
    public virtual void EscapeIdentifier(System.Text.StringBuilder sb, System.ReadOnlySpan<char> identifier)

    Escapes a raw identifier span and appends it directly to the provided `StringBuilder`.

    sb: System.Text.StringBuilder
    The string builder to append the escaped identifier to.
    identifier: System.ReadOnlySpan<char>
    The raw identifier span.
  • methodRenderBulkInsert<T>
    public virtual EricksonLopez.SqlBuilder.Builders.Bulk.Operations.BulkSqlResult RenderBulkInsert<T>(IEnumerable<T> entities, List<EricksonLopez.SqlBuilder.ColumnSelection.IColumnSelectionRule<T>> rules, int batchSize) where T : EricksonLopez.SqlBuilder.Abstractions.Metadata.IStaticEntityMetadata<T>

    Renders a batch of bulk INSERT statements for a collection of entities.

    entities: IEnumerable<T>
    The collection of entities to insert.
    rules: List<EricksonLopez.SqlBuilder.ColumnSelection.IColumnSelectionRule<T>>
    The column selection rules applied to the operation.
    batchSize: int
    The maximum number of entities to process per batch.

    Returns: A `Operations.BulkSqlResult` containing the generated batches.

    Type parameters: T: The type of the entities.

  • methodRenderBulkInsertIgnore<T>
    public virtual EricksonLopez.SqlBuilder.Builders.Bulk.Operations.BulkSqlResult RenderBulkInsertIgnore<T>(IEnumerable<T> entities, List<EricksonLopez.SqlBuilder.ColumnSelection.IColumnSelectionRule<T>> rules, int batchSize) where T : EricksonLopez.SqlBuilder.Abstractions.Metadata.IStaticEntityMetadata<T>

    Renders a batch of bulk INSERT IGNORE statements for a collection of entities.

    entities: IEnumerable<T>
    The collection of entities to insert.
    rules: List<EricksonLopez.SqlBuilder.ColumnSelection.IColumnSelectionRule<T>>
    The column selection rules applied to the operation.
    batchSize: int
    The maximum number of entities to process per batch.

    Returns: A `Operations.BulkSqlResult` containing the generated batches.

    Type parameters: T: The type of the entities.

  • methodRenderBulkMerge<T>
    public virtual EricksonLopez.SqlBuilder.Builders.Bulk.Operations.BulkSqlResult RenderBulkMerge<T>(IEnumerable<T> entities, List<EricksonLopez.SqlBuilder.ColumnSelection.IColumnSelectionRule<T>> rules, int batchSize) where T : EricksonLopez.SqlBuilder.Abstractions.Metadata.IStaticEntityMetadata<T>

    Renders a batch of bulk MERGE statements for a collection of entities.

    entities: IEnumerable<T>
    The collection of entities to merge.
    rules: List<EricksonLopez.SqlBuilder.ColumnSelection.IColumnSelectionRule<T>>
    The column selection rules applied to the operation.
    batchSize: int
    The maximum number of entities to process per batch.

    Returns: A `Operations.BulkSqlResult` containing the generated batches.

    Type parameters: T: The type of the entities.

  • methodRenderBulkUpdate<T>
    public virtual EricksonLopez.SqlBuilder.Builders.Bulk.Operations.BulkSqlResult RenderBulkUpdate<T>(IEnumerable<T> entities, List<EricksonLopez.SqlBuilder.ColumnSelection.IColumnSelectionRule<T>> rules, int batchSize) where T : EricksonLopez.SqlBuilder.Abstractions.Metadata.IStaticEntityMetadata<T>

    Renders a batch of bulk UPDATE statements for a collection of entities.

    entities: IEnumerable<T>
    The collection of entities to update.
    rules: List<EricksonLopez.SqlBuilder.ColumnSelection.IColumnSelectionRule<T>>
    The column selection rules applied to the operation.
    batchSize: int
    The maximum number of entities to process per batch.

    Returns: A `Operations.BulkSqlResult` containing the generated batches.

    Type parameters: T: The type of the entities.

  • methodRenderBulkUpsert<T>
    public virtual EricksonLopez.SqlBuilder.Builders.Bulk.Operations.BulkSqlResult RenderBulkUpsert<T>(IEnumerable<T> entities, List<EricksonLopez.SqlBuilder.ColumnSelection.IColumnSelectionRule<T>> rules, int batchSize) where T : EricksonLopez.SqlBuilder.Abstractions.Metadata.IStaticEntityMetadata<T>

    Renders a batch of bulk UPSERT statements for a collection of entities.

    entities: IEnumerable<T>
    The collection of entities to upsert.
    rules: List<EricksonLopez.SqlBuilder.ColumnSelection.IColumnSelectionRule<T>>
    The column selection rules applied to the operation.
    batchSize: int
    The maximum number of entities to process per batch.

    Returns: A `Operations.BulkSqlResult` containing the generated batches.

    Type parameters: T: The type of the entities.

  • methodRenderInsert<T>
    public virtual SqlResult RenderInsert<T>(T entity, Span<bool> insertMask) where T : EricksonLopez.SqlBuilder.Abstractions.Metadata.IStaticEntityMetadata<T>

    Renders an INSERT statement for a single entity.

    entity: T
    The entity instance.
    insertMask: Span<bool>
    A span representing which columns to include in the INSERT.

    Returns: A `SqlResult` containing the generated SQL and parameters.

    Type parameters: T: The type of the entity.

  • methodRenderUpdate<T>
    public virtual SqlResult RenderUpdate<T>(T entity, Span<bool> setMask, Span<bool> whereMask) where T : EricksonLopez.SqlBuilder.Abstractions.Metadata.IStaticEntityMetadata<T>

    Renders an UPDATE statement for a single entity.

    entity: T
    The entity instance.
    setMask: Span<bool>
    A span representing which columns to include in the SET clause.
    whereMask: Span<bool>
    A span representing which columns to use in the WHERE clause (usually primary keys).

    Returns: A `SqlResult` containing the generated SQL and parameters.

    Type parameters: T: The type of the entity.

  • methodSupportsCapability
    public virtual bool SupportsCapability(ProviderCapability capability)

    Determines whether the compiler and target database provider support a specific capability.

    capability: ProviderCapability
    The provider capability to check.

    Returns: `true` if the capability is supported; otherwise, `false`.

class

SqlExpressionVisitor

Assembly: EricksonLopez.SqlBuilder
public class SqlExpressionVisitor : ExpressionVisitor
Inherits: ExpressionVisitor

Provides an expression visitor that traverses LINQ expression trees and translates them into SQL string representations.

Remarks:

This visitor handles common evaluation scenarios required for WHERE and HAVING clauses. It uses reflection-based caching internally for property access and method invocations. Use `Sql.Raw(FormattableString)` for strict NativeAOT scenarios to avoid IL2026 warnings.

Members (3)

  • constructorSqlExpressionVisitor
    public SqlExpressionVisitor(StringBuilder sql, IParameterManager parameters, Func<string, string>? escapeFunc = null)

    Initializes a new instance of the `SqlExpressionVisitor` class.

    sql: StringBuilder
    The string builder where the resulting SQL will be appended.
    parameters: IParameterManager
    The parameter manager for tracking evaluated expression variables.
    escapeFunc: Func<string, string>?
    An optional function used to escape SQL identifiers.

    Exceptions: ArgumentNullException: `sql` or `parameters` is `null`

  • methodParse
    public void Parse(Expression expression)

    Parses the specified expression and appends its translated SQL equivalent to the string builder.

    expression: Expression
    The LINQ expression to parse.
  • methodVisit
    public override Expression? Visit(Expression? node)

    Dispatches the expression to one of the more specialized visit methods.

    node: Expression?
    The expression to visit.

    Returns: The modified expression, if it or any subexpression was modified; otherwise, returns the original expression.

    Exceptions: NotSupportedException: The expression type is not supported

struct

SqlParameter

Assembly: EricksonLopez.SqlBuilder
public readonly struct SqlParameter

Represents a parameterized value used in SQL queries with optional type metadata.

Remarks:

This struct allows passing explicitly typed parameters (such as JSON or array types) to the underlying database driver (like Dapper or ADO.NET) without requiring reflection.

Members (4)

  • constructorSqlParameter
    public SqlParameter(object? value, DbType? dbType = null, string? dbTypeName = null)

    Initializes a new instance of the `SqlParameter` struct with the specified value and optional type metadata.

    value: object?
    The raw value of the parameter.
    dbType: DbType?
    The standard database type of the parameter.
    dbTypeName: string?
    The provider-specific database type name.
  • propertyDatabaseTypeName
    public string? DatabaseTypeName { get; }

    Gets the optional provider-specific database type name (e.g., "jsonb").

  • propertyDbType
    public DbType? DbType { get; }

    Gets the optional database type to explicitly map the parameter.

  • propertyValue
    public object? Value { get; }

    Gets the raw value of the parameter.

class

SqlQueryFingerprintExtensions

Assembly: EricksonLopez.SqlBuilder
public static class SqlQueryFingerprintExtensions

Provides extension methods for calculating deterministic query fingerprints.

Members (1)

  • methodGetFingerprint
    public static string GetFingerprint(this ISqlQuery query)

    Computes a deterministic cryptographic fingerprint of the query's Abstract Syntax Tree (AST).

    query: this ISqlQuery
    The SQL query.

    Returns: A SHA256 hexadecimal string representing the query structure.

record

UpdateQuery<T>

Assembly: EricksonLopez.SqlBuilder
public sealed record UpdateQuery<T> : IAstQuery, IUpdateSetBuilder<T>, IUpdateWhereBuilder<T> where T : class, new()
Implements: IAstQuery, IUpdateSetBuilder<T>, IUpdateWhereBuilder<T>

Represents an UPDATE query syntax tree builder for the specified entity type.

Remarks:

This type is immutable. All modification methods return a new instance preserving the previous state. Type parameters: T: The type of the entity to update.

Members (23)

  • methodAddNode
    public UpdateQuery<T> AddNode(ISqlNode node)

    Appends the specified node to the query AST.

    node: ISqlNode
    The node to append to the query.

    Returns: A new `UpdateQuery<T>` instance containing the appended node.

  • methodAnd
    public IUpdateWhereBuilder<T> And(System.Linq.Expressions.Expression<System.Func<T, bool>> predicate)

    Appends an AND logical condition to the current WHERE clause using a predicate expression.

    predicate: System.Linq.Expressions.Expression<System.Func<T, bool>>
    The expression defining the additional filtering condition.

    Returns: A new `IUpdateWhereBuilder<T>` instance with the filter applied.

  • methodBuild
    public SqlResult Build(ISqlCompiler compiler)

    Compiles the abstract syntax tree into an executable SQL string and its parameters.

    compiler: ISqlCompiler
    The SQL compiler specific to the target database provider.

    Returns: The compiled SQL result.

  • methodFrom
    public IUpdateSetBuilder<T> From(string tableName, string? alias = null)

    Specifies an additional source table for the UPDATE operation (FROM clause).

    tableName: string
    The name of the additional table.
    alias: string?
    An optional alias for the additional table.

    Returns: A new `IUpdateSetBuilder<T>` instance with the FROM clause applied.

    Exceptions: ArgumentException: `tableName` is empty or whitespace, or `alias` is whitespace

  • methodJoin
    public IUpdateSetBuilder<T> Join(string tableName, string alias, string on)

    Appends an INNER JOIN clause to the query.

    tableName: string
    The name of the table to join.
    alias: string
    The alias for the joined table.
    on: string
    The join condition.

    Returns: A new `IUpdateSetBuilder<T>` instance with the join clause applied.

  • methodJoin<TOther>
    public IUpdateSetBuilder<T> Join<TOther>(System.Linq.Expressions.Expression<System.Func<T, TOther, bool>> onExpression) where TOther : new()

    Appends a strongly-typed INNER JOIN clause to the query based on a predicate.

    onExpression: System.Linq.Expressions.Expression<System.Func<T, TOther, bool>>
    The predicate expression defining the join condition.

    Returns: A new `IUpdateSetBuilder<T>` instance with the join clause applied.

    Type parameters: TOther: The type of the joined entity.

  • methodOr
    public IUpdateWhereBuilder<T> Or(System.Linq.Expressions.Expression<System.Func<T, bool>> predicate)

    Appends an OR logical condition to the current WHERE clause using a predicate expression.

    predicate: System.Linq.Expressions.Expression<System.Func<T, bool>>
    The expression defining the alternative filtering condition.

    Returns: A new `IUpdateWhereBuilder<T>` instance with the filter applied.

  • methodReturning
    public IUpdateWhereBuilder<T> Returning(params string[] columns)

    Specifies the columns to return from the updated rows.

    columns: params string[]
    The names of the columns to return.

    Returns: A new `IUpdateWhereBuilder<T>` instance with the returning clause applied.

  • methodReturning<TResult>
    public IUpdateWhereBuilder<T> Returning<TResult>(System.Linq.Expressions.Expression<System.Func<T, TResult>> selector)

    Specifies the columns to return from the updated rows using a predicate expression.

    selector: System.Linq.Expressions.Expression<System.Func<T, TResult>>
    The expression defining the columns to return.

    Returns: A new `IUpdateWhereBuilder<T>` instance with the returning clause applied.

    Type parameters: TResult: The type of the projected result.

  • methodSet
    public IUpdateSetBuilder<T> Set(FormattableString sql)

    Appends a raw SQL SET assignment.

    sql: FormattableString
    The formatted string containing the raw SET assignment and its parameters.

    Returns: A new `IUpdateSetBuilder<T>` instance with the SET assignment applied.

  • methodSet
    public IUpdateSetBuilder<T> Set(T entity, bool ignoreNulls = false)

    Appends SET clauses based on the properties of the provided entity.

    entity: T
    The entity instance containing the updated values.
    ignoreNulls: bool
    If `true`, properties with null values will not generate SET assignments.

    Returns: A new `IUpdateSetBuilder<T>` instance with the SET assignments applied.

    Exceptions: InvalidOperationException: `T` does not implement `Annotations.ISqlEntity` or metadata column count does not match value count

  • methodSet<TProperty>
    public IUpdateSetBuilder<T> Set<TProperty>(System.Linq.Expressions.Expression<System.Func<T, TProperty>> property, TProperty value)

    Appends a SET clause for a specific property using an expression.

    property: System.Linq.Expressions.Expression<System.Func<T, TProperty>>
    The expression selecting the property to update.
    value: TProperty
    The new value to assign to the property.

    Returns: A new `IUpdateSetBuilder<T>` instance with the SET assignment applied.

    Type parameters: TProperty: The type of the property being updated. Exceptions: ArgumentException: `property` is not a valid member expression

  • methodUpdate
    public UpdateQuery<T> Update(string? tableName = null)

    Specifies the target table to update.

    tableName: string?
    An optional table name to override the default entity table.

    Returns: A new `UpdateQuery<T>` instance with the target table applied.

  • methodWhere
    public IUpdateWhereBuilder<T> Where(FormattableString condition)

    Appends a raw SQL WHERE clause to filter the rows to update.

    condition: FormattableString
    The formatted string containing the raw filter and its parameters.

    Returns: A new `IUpdateWhereBuilder<T>` instance with the filter applied.

  • methodWhere
    public IUpdateWhereBuilder<T> Where(System.Linq.Expressions.Expression<System.Func<T, bool>> predicate)

    Appends a WHERE clause to filter the rows to update using a predicate expression.

    predicate: System.Linq.Expressions.Expression<System.Func<T, bool>>
    The expression defining the filtering condition.

    Returns: A new `IUpdateWhereBuilder<T>` instance with the filter applied.

  • methodWhereAll
    public IUpdateWhereBuilder<T> WhereAll()

    Explicitly indicates that the update should apply to all rows without filtering.

    Returns: The current `IUpdateWhereBuilder<T>` instance.

  • methodWhereExists
    public IUpdateWhereBuilder<T> WhereExists(ISqlQuery subquery)

    Appends a WHERE EXISTS (subquery) condition to the UPDATE statement.

    subquery: ISqlQuery
    The subquery to evaluate inside EXISTS.

    Returns: A new `IUpdateWhereBuilder<T>` instance with the EXISTS filter applied.

  • methodWhereNotExists
    public IUpdateWhereBuilder<T> WhereNotExists(ISqlQuery subquery)

    Appends a WHERE NOT EXISTS (subquery) condition to the UPDATE statement.

    subquery: ISqlQuery
    The subquery to evaluate inside NOT EXISTS.

    Returns: A new `IUpdateWhereBuilder<T>` instance with the NOT EXISTS filter applied.

  • methodWithConcurrencyToken<TToken>
    public IUpdateWhereBuilder<T> WithConcurrencyToken<TToken>(System.Linq.Expressions.Expression<System.Func<T, TToken>> tokenSelector, TToken expectedValue)

    Appends an optimistic concurrency check to the UPDATE statement. Generates `AND {column} = @expectedValue` in the WHERE clause and `SET {column} = {column} + 1` for integer tokens.

    tokenSelector: System.Linq.Expressions.Expression<System.Func<T, TToken>>
    Expression identifying the concurrency token column.
    expectedValue: TToken
    The expected current value to match in the WHERE clause.

    Returns: A new `IUpdateWhereBuilder<T>` instance with the concurrency check applied.

    For `int` and `long` tokens, the value auto-increments (`column = column + 1`). For other types (e.g., `Guid`), supply the new value via the three-argument overload. Type parameters: TToken: The type of the concurrency token column (e.g., `int`, `Guid`). Exceptions: ArgumentException: `tokenSelector` is not a member expression

  • methodWithConcurrencyToken<TToken>
    public IUpdateWhereBuilder<T> WithConcurrencyToken<TToken>(System.Linq.Expressions.Expression<System.Func<T, TToken>> tokenSelector, TToken expectedValue, TToken newValue)

    Appends an optimistic concurrency check to the UPDATE statement with an explicit new token value. Generates `AND {column} = @expectedValue` in WHERE and `SET {column} = @newValue`.

    tokenSelector: System.Linq.Expressions.Expression<System.Func<T, TToken>>
    Expression identifying the concurrency token column.
    expectedValue: TToken
    The expected current value to match in the WHERE clause.
    newValue: TToken
    The new value to assign to the token column in the SET clause.

    Returns: A new `IUpdateWhereBuilder<T>` instance with the concurrency check applied.

    Type parameters: TToken: The type of the concurrency token column (e.g., `Guid`, `DateTime`). Exceptions: ArgumentException: `tokenSelector` is not a member expression

  • methodWithTag
    public UpdateQuery<T> WithTag(string tag)

    Creates a new `UpdateQuery<T>` with the specified diagnostic tag.

    tag: string
    The diagnostic tag to associate with the query.

    Returns: A new query instance containing the applied tag.

  • propertyNodes
    public System.Collections.Immutable.ImmutableArray<ISqlNode> Nodes { get; init; }

    Gets the collection of nodes that compose the abstract syntax tree of this query.

  • propertyTag
    public string? Tag { get; init; }

    Gets the optional tag associated with this query for diagnostics or interception.

class

Window

Assembly: EricksonLopez.SqlBuilder
public static class Window

Provides factory methods for creating typed window function builders.

Remarks:

Usage: `Window.Rank<Employee>().PartitionBy(e => e.Dept).OrderByDescending(e => e.Salary).As("rnk")`.

Members (18)

  • methodAvg<T, TCol>
    public static WindowBuilder<T> Avg<T, TCol>(Expression<Func<T, TCol>> column) where T : class, new()

    Creates an AVG(column) OVER window function builder.

    column: Expression<Func<T, TCol>>
    The expression selecting the column.

    Returns: A new `WindowBuilder<TEntity>` instance.

    Type parameters: T: The entity type.; TCol: The type of the column. Exceptions: ArgumentException: `column` is not a property access expression

  • methodCount<T>
    public static WindowBuilder<T> Count<T>() where T : class, new()

    Creates a COUNT(*) OVER window function builder.

    Returns: A new `WindowBuilder<TEntity>` instance.

    Type parameters: T: The entity type.

  • methodCumeDist<T>
    public static WindowBuilder<T> CumeDist<T>() where T : class, new()

    Creates a CUME_DIST() window function builder.

    Returns: A new `WindowBuilder<TEntity>` instance.

    Type parameters: T: The entity type.

  • methodDenseRank<T>
    public static WindowBuilder<T> DenseRank<T>() where T : class, new()

    Creates a DENSE_RANK() window function builder.

    Returns: A new `WindowBuilder<TEntity>` instance.

    Type parameters: T: The entity type.

  • methodFirstValue<T, TCol>
    public static WindowBuilder<T> FirstValue<T, TCol>(Expression<Func<T, TCol>> column) where T : class, new()

    Creates a FIRST_VALUE(column) OVER window function builder.

    column: Expression<Func<T, TCol>>
    The expression selecting the column.

    Returns: A new `WindowBuilder<TEntity>` instance.

    Type parameters: T: The entity type.; TCol: The type of the column. Exceptions: ArgumentException: `column` is not a property access expression

  • methodLag<T, TCol>
    public static WindowBuilder<T> Lag<T, TCol>(Expression<Func<T, TCol>> column, int offset = 1, object? defaultValue = null) where T : class, new()

    Creates a LAG(column, offset) window function builder.

    column: Expression<Func<T, TCol>>
    The expression selecting the column.
    offset: int
    The row offset count.
    defaultValue: object?
    The optional fallback value when offset is out of bounds.

    Returns: A new `WindowBuilder<TEntity>` instance.

    Type parameters: T: The entity type.; TCol: The type of the column. Exceptions: ArgumentException: `column` is not a property access expression

  • methodLastValue<T, TCol>
    public static WindowBuilder<T> LastValue<T, TCol>(Expression<Func<T, TCol>> column) where T : class, new()

    Creates a LAST_VALUE(column) OVER window function builder.

    column: Expression<Func<T, TCol>>
    The expression selecting the column.

    Returns: A new `WindowBuilder<TEntity>` instance.

    Type parameters: T: The entity type.; TCol: The type of the column. Exceptions: ArgumentException: `column` is not a property access expression

  • methodLead<T, TCol>
    public static WindowBuilder<T> Lead<T, TCol>(Expression<Func<T, TCol>> column, int offset = 1, object? defaultValue = null) where T : class, new()

    Creates a LEAD(column, offset) window function builder.

    column: Expression<Func<T, TCol>>
    The expression selecting the column.
    offset: int
    The row offset count.
    defaultValue: object?
    The optional fallback value when offset is out of bounds.

    Returns: A new `WindowBuilder<TEntity>` instance.

    Type parameters: T: The entity type.; TCol: The type of the column. Exceptions: ArgumentException: `column` is not a property access expression

  • methodMax<T, TCol>
    public static WindowBuilder<T> Max<T, TCol>(Expression<Func<T, TCol>> column) where T : class, new()

    Creates a MAX(column) OVER window function builder.

    column: Expression<Func<T, TCol>>
    The expression selecting the column.

    Returns: A new `WindowBuilder<TEntity>` instance.

    Type parameters: T: The entity type.; TCol: The type of the column. Exceptions: ArgumentException: `column` is not a property access expression

  • methodMin<T, TCol>
    public static WindowBuilder<T> Min<T, TCol>(Expression<Func<T, TCol>> column) where T : class, new()

    Creates a MIN(column) OVER window function builder.

    column: Expression<Func<T, TCol>>
    The expression selecting the column.

    Returns: A new `WindowBuilder<TEntity>` instance.

    Type parameters: T: The entity type.; TCol: The type of the column. Exceptions: ArgumentException: `column` is not a property access expression

  • methodNthValue<T, TCol>
    public static WindowBuilder<T> NthValue<T, TCol>(Expression<Func<T, TCol>> column, int n) where T : class, new()

    Creates a NTH_VALUE(column, n) window function builder.

    column: Expression<Func<T, TCol>>
    The expression selecting the column.
    n: int
    The nth position index.

    Returns: A new `WindowBuilder<TEntity>` instance.

    Type parameters: T: The entity type.; TCol: The type of the column. Exceptions: ArgumentException: `column` is not a property access expression; ArgumentOutOfRangeException: `n` is less than or equal to zero

  • methodNtile<T>
    public static WindowBuilder<T> Ntile<T>(int buckets) where T : class, new()

    Creates a NTILE(n) window function builder.

    buckets: int
    The number of buckets to split rows into.

    Returns: A new `WindowBuilder<TEntity>` instance.

    Type parameters: T: The entity type. Exceptions: ArgumentOutOfRangeException: `buckets` is less than or equal to zero

  • methodPercentRank<T>
    public static WindowBuilder<T> PercentRank<T>() where T : class, new()

    Creates a PERCENT_RANK() window function builder.

    Returns: A new `WindowBuilder<TEntity>` instance.

    Type parameters: T: The entity type.

  • methodRank<T>
    public static WindowBuilder<T> Rank<T>() where T : class, new()

    Creates a RANK() window function builder.

    Returns: A new `WindowBuilder<TEntity>` instance.

    Type parameters: T: The entity type.

  • methodRowNumber<T>
    public static WindowBuilder<T> RowNumber<T>() where T : class, new()

    Creates a ROW_NUMBER() window function builder.

    Returns: A new `WindowBuilder<TEntity>` instance.

    Type parameters: T: The entity type.

  • methodStdDev<T, TCol>
    public static WindowBuilder<T> StdDev<T, TCol>(Expression<Func<T, TCol>> column) where T : class, new()

    Creates a STDDEV_SAMP(column) OVER window function builder.

    column: Expression<Func<T, TCol>>
    The expression selecting the column.

    Returns: A new `WindowBuilder<TEntity>` instance.

    Type parameters: T: The entity type.; TCol: The type of the column. Exceptions: ArgumentException: `column` is not a property access expression

  • methodSum<T, TCol>
    public static WindowBuilder<T> Sum<T, TCol>(Expression<Func<T, TCol>> column) where T : class, new()

    Creates a SUM(column) OVER window function builder.

    column: Expression<Func<T, TCol>>
    The expression selecting the column.

    Returns: A new `WindowBuilder<TEntity>` instance.

    Type parameters: T: The entity type.; TCol: The type of the column. Exceptions: ArgumentException: `column` is not a property access expression

  • methodVariance<T, TCol>
    public static WindowBuilder<T> Variance<T, TCol>(Expression<Func<T, TCol>> column) where T : class, new()

    Creates a VARIANCE(column) OVER window function builder.

    column: Expression<Func<T, TCol>>
    The expression selecting the column.

    Returns: A new `WindowBuilder<TEntity>` instance.

    Type parameters: T: The entity type.; TCol: The type of the column. Exceptions: ArgumentException: `column` is not a property access expression

class

WindowBuilder<TEntity>

Assembly: EricksonLopez.SqlBuilder
public sealed class WindowBuilder<TEntity> where TEntity : class, new()

Provides a fluent builder for inline window function expressions. Use `Window` static factory methods to start a chain, then call `As` to produce a `WindowFunctionNode` that can be passed to `SelectQuery<T>.Select(WindowFunctionNode[])`.

Remarks:

Type parameters: TEntity: The type of the entity associated with the window function. Example:

// RANK() OVER (PARTITION BY dept ORDER BY salary DESC) AS rank
var query = Sql.From<Employee>()
    .Select(
        Window.Rank()
              .PartitionBy(e => e.Department)
              .OrderByDescending(e => e.Salary)
              .As("rank"));

// ROW_NUMBER() OVER (ORDER BY created_at) AS row_num
var query = Sql.From<Order>()
    .Select(Window.RowNumber().OrderBy(o => o.CreatedAt).As("row_num"));

// LAG(amount, 1) OVER (PARTITION BY customer_id ORDER BY order_date) AS prev_amount
var query = Sql.From<Order>()
    .Select(Window.Lag<Order, decimal>(o => o.Amount, offset: 1)
                  .PartitionBy(o => o.CustomerId)
                  .OrderBy(o => o.OrderDate)
                  .As("prev_amount"));

Members (10)

  • methodAs
    public WindowFunctionNode As(string alias)

    Finalizes the window function expression with the given alias.

    alias: string
    The AS alias name for this expression in the SELECT clause.

    Returns: A `WindowFunctionNode` ready to pass into `.Select()`.

    Exceptions: ArgumentException: `alias` is null, empty, or whitespace

  • methodFilter
    public WindowBuilder<TEntity> Filter(Expression<Func<TEntity, bool>> filterPredicate)

    Adds a FILTER (WHERE ...) clause using a typed boolean LINQ predicate.

    filterPredicate: Expression<Func<TEntity, bool>>
    The predicate expression defining the filter condition.

    Returns: The current `WindowBuilder<TEntity>` instance.

  • methodFilter
    public WindowBuilder<TEntity> Filter(FormattableString rawCondition)

    Adds a FILTER (WHERE ...) clause using an interpolated string.

    rawCondition: FormattableString
    The formattable string containing the filter expression.

    Returns: The current `WindowBuilder<TEntity>` instance.

  • methodFilter
    public WindowBuilder<TEntity> Filter(string rawCondition, params object?[] parameters)

    Adds a FILTER (WHERE ...) clause using raw SQL and parameters.

    rawCondition: string
    The raw SQL filter expression.
    parameters: params object?[]
    The parameters to bind to the filter.

    Returns: The current `WindowBuilder<TEntity>` instance.

  • methodOrderBy
    public WindowBuilder<TEntity> OrderBy(string columnName)

    Adds an ORDER BY column (ascending) by raw column name.

    columnName: string
    The name of the order column.

    Returns: The current `WindowBuilder<TEntity>` instance.

  • methodOrderBy<TKey>
    public WindowBuilder<TEntity> OrderBy<TKey>(Expression<Func<TEntity, TKey>> columnSelector)

    Adds an ORDER BY column (ascending) using a typed expression.

    columnSelector: Expression<Func<TEntity, TKey>>
    The expression selecting the order column.

    Returns: The current `WindowBuilder<TEntity>` instance.

    Type parameters: TKey: The type of the order key. Exceptions: ArgumentException: `columnSelector` is not a property access expression

  • methodOrderByDescending
    public WindowBuilder<TEntity> OrderByDescending(string columnName)

    Adds an ORDER BY column (descending) by raw column name.

    columnName: string
    The name of the order column.

    Returns: The current `WindowBuilder<TEntity>` instance.

  • methodOrderByDescending<TKey>
    public WindowBuilder<TEntity> OrderByDescending<TKey>(Expression<Func<TEntity, TKey>> columnSelector)

    Adds an ORDER BY column (descending) using a typed expression.

    columnSelector: Expression<Func<TEntity, TKey>>
    The expression selecting the order column.

    Returns: The current `WindowBuilder<TEntity>` instance.

    Type parameters: TKey: The type of the order key. Exceptions: ArgumentException: `columnSelector` is not a property access expression

  • methodPartitionBy
    public WindowBuilder<TEntity> PartitionBy(string columnName)

    Adds a PARTITION BY column by raw column name (snake_case).

    columnName: string
    The name of the partition column.

    Returns: The current `WindowBuilder<TEntity>` instance.

  • methodPartitionBy<TKey>
    public WindowBuilder<TEntity> PartitionBy<TKey>(Expression<Func<TEntity, TKey>> columnSelector)

    Adds a PARTITION BY column using a typed expression.

    columnSelector: Expression<Func<TEntity, TKey>>
    The expression selecting the partition column.

    Returns: The current `WindowBuilder<TEntity>` instance.

    Type parameters: TKey: The type of the partition key. Exceptions: ArgumentException: `columnSelector` is not a property access expression

EricksonLopez.SqlBuilder.Abstractions#

18
class

DbConcurrencyException

Assembly: EricksonLopez.SqlBuilder.Abstractions
public sealed class DbConcurrencyException : Exception
Inherits: Exception

Represents the exception thrown when an optimistic concurrency conflict is detected during an UPDATE operation.

Remarks:

This exception is raised when an UPDATE query with a concurrency token returns 0 rows affected, indicating that the target record was modified or deleted concurrently.

Members (4)

  • constructorDbConcurrencyException
    public DbConcurrencyException(string entityTypeName, int rowsAffected = 0)

    Initializes a new instance of the `DbConcurrencyException` class with entity type information.

    entityTypeName: string
    The name of the entity type that caused the conflict.
    rowsAffected: int
    The number of rows affected by the operation.
  • constructorDbConcurrencyException
    public DbConcurrencyException(string entityTypeName, int rowsAffected, Exception innerException)

    Initializes a new instance of the `DbConcurrencyException` class with a specified inner exception.

    entityTypeName: string
    The name of the entity type that caused the conflict.
    rowsAffected: int
    The number of rows affected by the operation.
    innerException: Exception
    The exception that is the cause of the current exception.
  • propertyEntityTypeName
    public string EntityTypeName { get; }

    Gets the name of the entity type for which the concurrency conflict occurred.

  • propertyRowsAffected
    public int RowsAffected { get; }

    Gets the number of rows affected by the update operation (expected to be 0).

interface

IAstQuery

Assembly: EricksonLopez.SqlBuilder.Abstractions
public interface IAstQuery : ISqlQuery
Implements: ISqlQuery

Defines an immutable SQL query composed of Abstract Syntax Tree (AST) nodes.

Members (1)

  • propertyNodes
    IReadOnlyList<ISqlNode> Nodes { get; }

    Gets the list of nodes that compose the SQL query.

interface

IBulkSerializer<T>

Assembly: EricksonLopez.SqlBuilder.Abstractions
public interface IBulkSerializer<T>

Defines a serializer that extracts entity property values into an array for high-performance bulk operations.

Remarks:

Type parameters: T: The entity type to serialize.

Members (1)

  • methodSerialize
    void Serialize(T entity, object?[] values)

    Serializes the property values of the specified entity into a target array.

    entity: T
    The entity instance to serialize.
    values: object?[]
    The pre-allocated target array to store the serialized values.
interface

IDeleteFromBuilder<T>

Assembly: EricksonLopez.SqlBuilder.Abstractions
public interface IDeleteFromBuilder<T> where T : class, new()

Defines the initial stage of a DELETE query construction where table sources, joins, and using clauses can be specified.

Remarks:

Type parameters: T: The type of the target entity to delete from.

Members (5)

  • methodWhere
    IDeleteWhereBuilder<T> Where(Expression<Func<T, bool>> predicate)

    Adds a WHERE clause to the DELETE statement using a strongly-typed LINQ predicate.

    predicate: Expression<Func<T, bool>>
    The expression defining the condition.

    Returns: An `IDeleteWhereBuilder<T>` that represents a compilable query.

  • methodWhere
    IDeleteWhereBuilder<T> Where(FormattableString condition)

    Adds a WHERE clause to the DELETE statement using a parameterized formattable string.

    condition: FormattableString
    The formatted SQL condition.

    Returns: An `IDeleteWhereBuilder<T>` that represents a compilable query.

  • methodWhereAll
    IDeleteWhereBuilder<T> WhereAll()

    Explicitly allows the delete query to execute without a WHERE clause, deleting all rows in the table.

    Returns: An `IDeleteWhereBuilder<T>` that represents a compilable query.

  • methodWhereExists
    IDeleteWhereBuilder<T> WhereExists(ISqlQuery subquery)

    Adds a WHERE EXISTS (subquery) condition to the DELETE statement.

    subquery: ISqlQuery
    The subquery to evaluate inside EXISTS.

    Returns: An `IDeleteWhereBuilder<T>` that represents a compilable query.

  • methodWhereNotExists
    IDeleteWhereBuilder<T> WhereNotExists(ISqlQuery subquery)

    Adds a WHERE NOT EXISTS (subquery) condition to the DELETE statement.

    subquery: ISqlQuery
    The subquery to evaluate inside NOT EXISTS.

    Returns: An `IDeleteWhereBuilder<T>` that represents a compilable query.

interface

IDeleteWhereBuilder<T>

Assembly: EricksonLopez.SqlBuilder.Abstractions
public interface IDeleteWhereBuilder<T> : IAstQuery where T : class, new()
Implements: IAstQuery

Defines the final stage of a DELETE query construction containing at least one condition or explicit whole-table delete directive.

Remarks:

Type parameters: T: The type of the entity being deleted.

Members (4)

  • methodAnd
    IDeleteWhereBuilder<T> And(Expression<Func<T, bool>> predicate)

    Appends an AND condition to the existing WHERE clause.

    predicate: Expression<Func<T, bool>>
    The expression defining the condition.

    Returns: The current builder instance.

  • methodOr
    IDeleteWhereBuilder<T> Or(Expression<Func<T, bool>> predicate)

    Appends an OR condition to the existing WHERE clause.

    predicate: Expression<Func<T, bool>>
    The expression defining the condition.

    Returns: The current builder instance.

  • methodReturning
    IDeleteWhereBuilder<T> Returning(params string[] columns)

    Specifies columns to return after the delete operation completes.

    columns: params string[]
    The names of the columns to return.

    Returns: The current builder instance.

  • methodReturning<TResult>
    IDeleteWhereBuilder<T> Returning<TResult>(Expression<Func<T, TResult>> selector)

    Specifies properties to return after the delete operation completes, using a strongly-typed selector.

    selector: Expression<Func<T, TResult>>
    The expression defining the columns to return.

    Returns: The current builder instance.

    Type parameters: TResult: The type of the result projection.

interface

IParameterManager

Assembly: EricksonLopez.SqlBuilder.Abstractions
public interface IParameterManager

Defines a parameter collection and naming manager used during SQL statement compilation.

Members (3)

  • methodAdd
    string Add(object? value)

    Adds a parameter value and returns its generated parameter name in the dialect's syntax.

    value: object?
    The value to add as a parameter.

    Returns: The generated parameter name (e.g., '@p0').

  • methodAddNamed
    string AddNamed(string name, object? value)

    Adds a named parameter value and returns its formatted parameter name in the dialect's syntax.

    name: string
    The explicit name of the parameter.
    value: object?
    The value to add.

    Returns: The formatted parameter name (e.g., '@name').

  • methodGetParameters
    IReadOnlyDictionary<string, object?> GetParameters()

    Gets the read-only dictionary of all registered parameters.

    Returns: A dictionary containing the parameter names and their values.

interface

IQueryFingerprinter

Assembly: EricksonLopez.SqlBuilder.Abstractions
public interface IQueryFingerprinter

Defines a contract for contributing Abstract Syntax Tree (AST) components to a deterministic query fingerprint.

Members (4)

  • methodContribute
    void Contribute(bool value)

    Contributes a boolean value to the query fingerprint.

    value: bool
    The boolean value to contribute to the fingerprint.
  • methodContribute
    void Contribute(int value)

    Contributes a numeric value to the query fingerprint.

    value: int
    The integer value to contribute to the fingerprint.
  • methodContribute
    void Contribute(string? value)

    Contributes a string component to the query fingerprint.

    value: string?
    The string value to hash.
  • methodContribute
    void Contribute(Type? type)

    Contributes the type name to the query fingerprint.

    type: Type?
    The type whose name to contribute to the fingerprint.
interface

ISqlCompiler

Assembly: EricksonLopez.SqlBuilder.Abstractions
public interface ISqlCompiler

Defines the compiler that translates an `ISqlQuery` into a compiled `SqlResult`.

Members (6)

  • methodCompile
    SqlResult Compile(ISqlQuery query)

    Compiles the specified SQL query into an executable result.

    query: ISqlQuery
    The query to compile.

    Returns: A `SqlResult` containing the generated SQL string and parameters.

  • methodCompile
    SqlResult Compile(ISqlQuery query, IParameterManager? existingParameters)

    Compiles the specified SQL query using an existing parameter manager.

    query: ISqlQuery
    The query to compile.
    existingParameters: IParameterManager?
    An existing parameter manager to append parameters to.

    Returns: A `SqlResult` containing the generated SQL string and parameters.

  • methodCreateParameterManager
    IParameterManager CreateParameterManager()

    Creates a new parameter manager suitable for this compiler's dialect.

    Returns: A new `IParameterManager` instance.

  • methodEscape
    string Escape(string identifier)

    Escapes an identifier according to the specific database dialect rules.

    identifier: string
    The identifier to escape.

    Returns: The escaped identifier string.

  • methodEscapeIdentifier
    string EscapeIdentifier(string identifier)

    Escapes an identifier only if it contains special characters or keywords, according to dialect rules.

    identifier: string
    The identifier to potentially escape.

    Returns: The escaped identifier string.

  • methodSupportsCapability
    bool SupportsCapability(ProviderCapability capability)

    Determines whether the compiler and target database provider support a specific capability.

    capability: ProviderCapability
    The provider capability to check.

    Returns: `true` if the capability is supported; otherwise, `false`.

interface

ISqlNode

Assembly: EricksonLopez.SqlBuilder.Abstractions
public interface ISqlNode

Defines a node within the SQL Abstract Syntax Tree (AST).

Members (2)

  • methodAccept
    void Accept(ISqlVisitor visitor)

    Accepts a visitor to perform double-dispatch traversal of the AST.

    visitor: ISqlVisitor
    The visitor instance handling the node.
  • methodContributeToFingerprint
    void ContributeToFingerprint(IQueryFingerprinter fingerprinter)

    Contributes the structure of this node to a deterministic cryptographic fingerprint. Values and parameter arguments are ignored to ensure the fingerprint only reflects the AST shape.

    fingerprinter: IQueryFingerprinter
    The fingerprinter instance.
interface

ISqlQuery

Assembly: EricksonLopez.SqlBuilder.Abstractions
public interface ISqlQuery

Defines an immutable SQL query that can be compiled into an executable statement.

Members (3)

  • methodBuild
    SqlResult Build(ISqlCompiler compiler)

    Builds the SQL query using the specified compiler.

    compiler: ISqlCompiler
    The SQL compiler to use.

    Returns: A `SqlResult` containing the generated SQL and parameters.

  • methodContributeToFingerprint
    void ContributeToFingerprint(IQueryFingerprinter fingerprinter)

    Contributes the structure of this query to a deterministic cryptographic fingerprint.

    fingerprinter: IQueryFingerprinter
    The fingerprinter instance.
  • propertyTag
    string? Tag { get; }

    Gets the optional telemetry/instrumentation tag associated with this query.

interface

ISqlVisitor

Assembly: EricksonLopez.SqlBuilder.Abstractions
public interface ISqlVisitor

Defines a visitor for SQL AST nodes, enabling double-dispatch without coupling to a concrete implementation.

Members (41)

  • methodVisit
    void Visit(CaseNode node)

    Visits a `CaseNode` representing a CASE expression in the SELECT clause.

    node: CaseNode
    The case node to process.
  • methodVisit
    void Visit(CompositeCursorNode node)

    Visits a `CompositeCursorNode` representing a composite keyset cursor predicate.

    node: CompositeCursorNode
    The composite cursor node to process.
  • methodVisit
    void Visit(ConcurrencyTokenNode node)

    Visits a `ConcurrencyTokenNode` representing the optimistic concurrency token check.

    node: ConcurrencyTokenNode
    The concurrency token node to process.
  • methodVisit
    void Visit(CteNode node)

    Visits a `CteNode` representing a Common Table Expression.

    node: CteNode
    The CTE node to process.
  • methodVisit
    void Visit(DefaultValuesNode node)

    Visits a `DefaultValuesNode` representing an INSERT DEFAULT VALUES clause.

    node: DefaultValuesNode
    The default values node to process.
  • methodVisit
    void Visit(DeleteNode node)

    Visits a `DeleteNode` representing the target table of a DELETE statement.

    node: DeleteNode
    The delete node to process.
  • methodVisit
    void Visit(DistinctOnNode node)

    Visits a `DistinctOnNode` representing a PostgreSQL DISTINCT ON clause.

    node: DistinctOnNode
    The distinct-on node to process.
  • methodVisit
    void Visit(ExistsWhereNode node)

    Visits an `ExistsWhereNode` representing a WHERE EXISTS or WHERE NOT EXISTS subquery condition.

    node: ExistsWhereNode
    The exists where node to process.
  • methodVisit
    void Visit(ExpressionHavingNode node)

    Visits an `ExpressionHavingNode` representing a HAVING clause derived from a LINQ expression.

    node: ExpressionHavingNode
    The expression having node to process.
  • methodVisit
    void Visit(ExpressionSelectNode node)

    Visits an `ExpressionSelectNode` representing a LINQ expression-based SELECT projection.

    node: ExpressionSelectNode
    The expression select node to process.
  • methodVisit
    void Visit(ExpressionWhereNode node)

    Visits an `ExpressionWhereNode` representing a WHERE clause derived from a LINQ expression.

    node: ExpressionWhereNode
    The expression where node to process.
  • methodVisit
    void Visit(FromNode node)

    Visits a `FromNode` representing the primary FROM clause.

    node: FromNode
    The from node to process.
  • methodVisit
    void Visit(GroupByNode node)

    Visits a `GroupByNode` representing the GROUP BY clause.

    node: GroupByNode
    The group-by node to process.
  • methodVisit
    void Visit(InsertNode node)

    Visits an `InsertNode` representing the INSERT INTO header clause.

    node: InsertNode
    The insert node to process.
  • methodVisit
    void Visit(InsertSelectNode node)

    Visits an `InsertSelectNode` representing an INSERT INTO ... SELECT statement.

    node: InsertSelectNode
    The insert-select node to process.
  • methodVisit
    void Visit(JoinNode node)

    Visits a `JoinNode` representing a typed JOIN clause.

    node: JoinNode
    The join node to process.
  • methodVisit
    void Visit(LimitOffsetNode node)

    Visits a `LimitOffsetNode` representing the LIMIT and OFFSET pagination clauses.

    node: LimitOffsetNode
    The limit/offset node to process.
  • methodVisit
    void Visit(OnConflictNode node)

    Visits an `OnConflictNode` representing the ON CONFLICT clause of an INSERT statement.

    node: OnConflictNode
    The on-conflict node to process.
  • methodVisit
    void Visit(OrderByNode node)

    Visits an `OrderByNode` representing the primary ORDER BY clause.

    node: OrderByNode
    The order-by node to process.
  • methodVisit
    void Visit(QueryAliasNode node)

    Visits a `QueryAliasNode` representing an alias assigned to the outer query.

    node: QueryAliasNode
    The query alias node to process.
  • methodVisit
    void Visit(RawHavingNode node)

    Visits a `RawHavingNode` representing a raw SQL HAVING clause.

    node: RawHavingNode
    The raw having node to process.
  • methodVisit
    void Visit(RawJoinNode node)

    Visits a `RawJoinNode` representing a raw SQL JOIN clause.

    node: RawJoinNode
    The raw join node to process.
  • methodVisit
    void Visit(RawOrderByNode node)

    Visits a `RawOrderByNode` representing a raw SQL ORDER BY clause.

    node: RawOrderByNode
    The raw order-by node to process.
  • methodVisit
    void Visit(RawSelectNode node)

    Visits a `RawSelectNode` representing a raw SQL SELECT clause.

    node: RawSelectNode
    The raw select node to process.
  • methodVisit
    void Visit(RawWhereNode node)

    Visits a `RawWhereNode` representing a raw SQL WHERE clause.

    node: RawWhereNode
    The raw where node to process.
  • methodVisit
    void Visit(ReturningNode node)

    Visits a `ReturningNode` representing the RETURNING or OUTPUT clause.

    node: ReturningNode
    The returning node to process.
  • methodVisit
    void Visit(ScalarSubquerySelectNode node)

    Visits a `ScalarSubquerySelectNode` representing a scalar subquery in the SELECT projection.

    node: ScalarSubquerySelectNode
    The scalar subquery node to process.
  • methodVisit
    void Visit(SelectNode node)

    Visits a `SelectNode` representing a standard SELECT column projection.

    node: SelectNode
    The select node to process.
  • methodVisit
    void Visit(SetNode node)

    Visits a `SetNode` representing a single SET assignment in an UPDATE statement.

    node: SetNode
    The set node to process.
  • methodVisit
    void Visit(SetOperationNode node)

    Visits a `SetOperationNode` representing a set operation such as UNION, INTERSECT, or EXCEPT.

    node: SetOperationNode
    The set operation node to process.
  • methodVisit
    void Visit(SubqueryFromNode node)

    Visits a `SubqueryFromNode` representing a subquery used as the FROM data source.

    node: SubqueryFromNode
    The subquery from node to process.
  • methodVisit
    void Visit(SubqueryJoinNode node)

    Visits a `SubqueryJoinNode` representing a JOIN to a subquery or lateral subquery.

    node: SubqueryJoinNode
    The subquery join node to process.
  • methodVisit
    void Visit(ThenByNode node)

    Visits a `ThenByNode` representing a secondary sort clause.

    node: ThenByNode
    The then-by node to process.
  • methodVisit
    void Visit(UnnestNode node)

    Visits an `UnnestNode` representing an UNNEST array expansion clause.

    node: UnnestNode
    The unnest node to process.
  • methodVisit
    void Visit(UpdateNode node)

    Visits an `UpdateNode` representing the UPDATE table target clause.

    node: UpdateNode
    The update node to process.
  • methodVisit
    void Visit(ValuesNode node)

    Visits a `ValuesNode` representing the VALUES clause of an INSERT statement.

    node: ValuesNode
    The values node to process.
  • methodVisit
    void Visit(WindowFunctionNode node)

    Visits a `WindowFunctionNode` representing a window function expression in the SELECT clause.

    node: WindowFunctionNode
    The window function node to process.
  • methodVisit
    void Visit(WindowNode node)

    Visits a `WindowNode` representing a named window specification.

    node: WindowNode
    The window node to process.
  • methodVisit
    void Visit(WindowPageNode node)

    Visits a `WindowPageNode` representing a ROW_NUMBER-based window pagination clause.

    node: WindowPageNode
    The window page node to process.
  • methodVisitExtension
    void VisitExtension(SqlExtensionNode node)

    Extension point for processing unknown or custom nodes.

    node: SqlExtensionNode
    The custom extension node to process.
  • methodVisitUnknown
    void VisitUnknown(ISqlNode node)

    Handles a node type that is not recognized by this visitor.

    node: ISqlNode
    The unrecognized node.
interface

ITypeHandler

Assembly: EricksonLopez.SqlBuilder.Abstractions
public interface ITypeHandler

Defines a handler for converting custom types to and from database parameters.

Members (2)

  • methodParse
    object? Parse(System.Type destinationType, object? value)

    Parses a database value back to the custom type.

    destinationType: System.Type
    The target type to parse to.
    value: object?
    The value from the database.

    Returns: The parsed object.

  • methodSetValue
    void SetValue(System.Data.IDbDataParameter parameter, object? value)

    Sets the value of a parameter using the custom type.

    parameter: System.Data.IDbDataParameter
    The database parameter.
    value: object?
    The value to set.
interface

IUpdateSetBuilder<T>

Assembly: EricksonLopez.SqlBuilder.Abstractions
public interface IUpdateSetBuilder<T> where T : class, new()

Defines the SET stage of an UPDATE query where column modifications and optional JOIN/WHERE clauses can be configured.

Remarks:

Type parameters: T: The type of the entity being updated.

Members (12)

  • methodFrom
    IUpdateSetBuilder<T> From(string tableName, string? alias = null)

    Adds a FROM clause for the UPDATE statement, useful in PostgreSQL updates with joins.

    tableName: string
    The name of the table to select from.
    alias: string?
    An optional alias for the table.

    Returns: The current builder instance.

  • methodJoin
    IUpdateSetBuilder<T> Join(string tableName, string alias, string on)

    Adds a JOIN clause to the UPDATE statement.

    tableName: string
    The name of the table to join.
    alias: string
    The alias for the joined table.
    on: string
    The explicit join condition.

    Returns: The current builder instance.

  • methodJoin<TOther>
    IUpdateSetBuilder<T> Join<TOther>(Expression<Func<T, TOther, bool>> onExpression) where TOther : new()

    Adds a strongly-typed JOIN clause using a LINQ expression.

    onExpression: Expression<Func<T, TOther, bool>>
    The expression defining the join condition.

    Returns: The current builder instance.

    Type parameters: TOther: The type of the entity to join.

  • methodSet
    IUpdateSetBuilder<T> Set(FormattableString sql)

    Specifies a custom SQL string for the SET clause.

    sql: FormattableString
    The formatted SQL string.

    Returns: The current builder instance.

  • methodSet<TProperty>
    IUpdateSetBuilder<T> Set<TProperty>(Expression<Func<T, TProperty>> property, TProperty value)

    Sets a specific property to a new value.

    property: Expression<Func<T, TProperty>>
    The expression identifying the property.
    value: TProperty
    The new value to assign.

    Returns: The current builder instance.

    Type parameters: TProperty: The type of the property being updated.

  • methodWhere
    IUpdateWhereBuilder<T> Where(Expression<Func<T, bool>> predicate)

    Adds a WHERE clause to the UPDATE statement using a LINQ expression.

    predicate: Expression<Func<T, bool>>
    The expression defining the condition.

    Returns: An `IUpdateWhereBuilder<T>` that represents a compilable query.

  • methodWhere
    IUpdateWhereBuilder<T> Where(FormattableString condition)

    Adds a WHERE clause to the UPDATE statement using a formattable string.

    condition: FormattableString
    The formatted SQL condition.

    Returns: An `IUpdateWhereBuilder<T>` that represents a compilable query.

  • methodWhereAll
    IUpdateWhereBuilder<T> WhereAll()

    Explicitly allows the update query to execute without a WHERE clause, updating all rows in the table.

    Returns: An `IUpdateWhereBuilder<T>` that represents a compilable query.

  • methodWhereExists
    IUpdateWhereBuilder<T> WhereExists(ISqlQuery subquery)

    Adds a WHERE EXISTS (subquery) condition to the UPDATE statement.

    subquery: ISqlQuery
    The subquery to evaluate inside EXISTS.

    Returns: An `IUpdateWhereBuilder<T>` that represents a compilable query.

  • methodWhereNotExists
    IUpdateWhereBuilder<T> WhereNotExists(ISqlQuery subquery)

    Adds a WHERE NOT EXISTS (subquery) condition to the UPDATE statement.

    subquery: ISqlQuery
    The subquery to evaluate inside NOT EXISTS.

    Returns: An `IUpdateWhereBuilder<T>` that represents a compilable query.

  • methodWithConcurrencyToken<TToken>
    IUpdateWhereBuilder<T> WithConcurrencyToken<TToken>(Expression<Func<T, TToken>> tokenSelector, TToken expectedValue)

    Appends an optimistic concurrency check with auto-increment behavior on the concurrency token.

    tokenSelector: Expression<Func<T, TToken>>
    The expression identifying the token property.
    expectedValue: TToken
    The expected current value of the token.

    Returns: An `IUpdateWhereBuilder<T>` that represents a compilable query.

    Type parameters: TToken: The type of the concurrency token property.

  • methodWithConcurrencyToken<TToken>
    IUpdateWhereBuilder<T> WithConcurrencyToken<TToken>(Expression<Func<T, TToken>> tokenSelector, TToken expectedValue, TToken newValue)

    Appends an optimistic concurrency check with an explicit new token value.

    tokenSelector: Expression<Func<T, TToken>>
    The expression identifying the token property.
    expectedValue: TToken
    The expected current value of the token.
    newValue: TToken
    The explicit new value to assign to the token property.

    Returns: An `IUpdateWhereBuilder<T>` that represents a compilable query.

    Type parameters: TToken: The type of the concurrency token property.

interface

IUpdateWhereBuilder<T>

Assembly: EricksonLopez.SqlBuilder.Abstractions
public interface IUpdateWhereBuilder<T> : IAstQuery where T : class, new()
Implements: IAstQuery

Defines the final stage of an UPDATE query construction containing at least one condition or explicit whole-table update directive.

Remarks:

Type parameters: T: The type of the entity being updated.

Members (6)

  • methodAnd
    IUpdateWhereBuilder<T> And(Expression<Func<T, bool>> predicate)

    Appends an AND condition to the existing WHERE clause.

    predicate: Expression<Func<T, bool>>
    The expression defining the condition.

    Returns: The current builder instance.

  • methodOr
    IUpdateWhereBuilder<T> Or(Expression<Func<T, bool>> predicate)

    Appends an OR condition to the existing WHERE clause.

    predicate: Expression<Func<T, bool>>
    The expression defining the condition.

    Returns: The current builder instance.

  • methodReturning
    IUpdateWhereBuilder<T> Returning(params string[] columns)

    Specifies columns to return after the update operation completes.

    columns: params string[]
    The names of the columns to return.

    Returns: The current builder instance.

  • methodReturning<TResult>
    IUpdateWhereBuilder<T> Returning<TResult>(Expression<Func<T, TResult>> selector)

    Specifies properties to return after the update operation completes, using a strongly-typed selector.

    selector: Expression<Func<T, TResult>>
    The expression defining the columns to return.

    Returns: The current builder instance.

    Type parameters: TResult: The type of the result projection.

  • methodWithConcurrencyToken<TToken>
    IUpdateWhereBuilder<T> WithConcurrencyToken<TToken>(Expression<Func<T, TToken>> tokenSelector, TToken expectedValue)

    Appends an optimistic concurrency check with auto-increment behavior on the concurrency token.

    tokenSelector: Expression<Func<T, TToken>>
    The expression identifying the token property.
    expectedValue: TToken
    The expected current value of the token.

    Returns: The current builder instance.

    Type parameters: TToken: The type of the concurrency token property.

  • methodWithConcurrencyToken<TToken>
    IUpdateWhereBuilder<T> WithConcurrencyToken<TToken>(Expression<Func<T, TToken>> tokenSelector, TToken expectedValue, TToken newValue)

    Appends an optimistic concurrency check with an explicit new token value.

    tokenSelector: Expression<Func<T, TToken>>
    The expression identifying the token property.
    expectedValue: TToken
    The expected current value of the token.
    newValue: TToken
    The explicit new value to assign to the token property.

    Returns: The current builder instance.

    Type parameters: TToken: The type of the concurrency token property.

enum

ProviderCapability

Assembly: EricksonLopez.SqlBuilder.Abstractions
public enum ProviderCapability

Represents specific capabilities that a SQL provider might or might not support.

Members (7)

  • fieldApply
    Apply = 1<<0

    Supports CROSS APPLY and OUTER APPLY.

  • fieldCte
    Cte = 1<<5

    Supports Common Table Expressions (WITH).

  • fieldLateral
    Lateral = 1<<1

    Supports INNER JOIN LATERAL and LEFT JOIN LATERAL.

  • fieldMerge
    Merge = 1<<3

    Supports the MERGE (UPSERT) statement.

  • fieldNone
    None = 0

    No special capabilities.

  • fieldReturning
    Returning = 1<<2

    Supports INSERT ... RETURNING or OUTPUT.

  • fieldWindowFunctions
    WindowFunctions = 1<<4

    Supports Window Functions (OVER, PARTITION BY, etc.).

class

RequiresCapabilityAttribute

Assembly: EricksonLopez.SqlBuilder.Abstractions
public sealed class RequiresCapabilityAttribute : Attribute
Inherits: Attribute

Specifies that a method or class requires a specific database provider capability to function correctly.

Members (2)

  • constructorRequiresCapabilityAttribute
    public RequiresCapabilityAttribute(ProviderCapability capability)

    Initializes a new instance of the `RequiresCapabilityAttribute` class.

    capability: ProviderCapability
    The required capability.
  • propertyCapability
    public ProviderCapability Capability { get; }

    Gets the required provider capability.

record

SqlResult

Assembly: EricksonLopez.SqlBuilder.Abstractions
public sealed record SqlResult(string Sql, IReadOnlyDictionary<string, object?> Parameters)

Represents the final, immutable SQL result ready to be consumed by Dapper or another execution engine.

Members (3)

  • constructorSqlResult
    public SqlResult(string Sql, IReadOnlyDictionary<string, object?> Parameters)

    Initializes a new instance of SqlResult.

    Sql: string
    The raw SQL command text.
    Parameters: IReadOnlyDictionary<string, object?>
    A read-only dictionary of parameters associated with the SQL command.
  • propertyParameters
    public IReadOnlyDictionary<string, object?> Parameters { get; init; }

    A read-only dictionary of parameters associated with the SQL command.

  • propertySql
    public string Sql { get; init; }

    The raw SQL command text.

class

SqlVisitorBase

Assembly: EricksonLopez.SqlBuilder.Abstractions
public abstract class SqlVisitorBase : ISqlVisitor
Implements: ISqlVisitor

Provides a base implementation of `ISqlVisitor` where all virtual Visit methods are empty stubs. Derived classes can override only the specific nodes they care about.

Members (41)

  • methodVisit
    public virtual void Visit(CaseNode node)

    Visits a `CteNode` representing a Common Table Expression.

    node: CaseNode
    The CTE node to process.
  • methodVisit
    public virtual void Visit(CompositeCursorNode node)

    Visits a `CteNode` representing a Common Table Expression.

    node: CompositeCursorNode
    The CTE node to process.
  • methodVisit
    public virtual void Visit(ConcurrencyTokenNode node)

    Visits a `CteNode` representing a Common Table Expression.

    node: ConcurrencyTokenNode
    The CTE node to process.
  • methodVisit
    public virtual void Visit(CteNode node)

    Visits a `CteNode` representing a Common Table Expression.

    node: CteNode
    The CTE node to process.
  • methodVisit
    public virtual void Visit(DefaultValuesNode node)

    Visits a `CteNode` representing a Common Table Expression.

    node: DefaultValuesNode
    The CTE node to process.
  • methodVisit
    public virtual void Visit(DeleteNode node)

    Visits a `CteNode` representing a Common Table Expression.

    node: DeleteNode
    The CTE node to process.
  • methodVisit
    public virtual void Visit(DistinctOnNode node)

    Visits a `CteNode` representing a Common Table Expression.

    node: DistinctOnNode
    The CTE node to process.
  • methodVisit
    public virtual void Visit(ExistsWhereNode node)

    Visits a `CteNode` representing a Common Table Expression.

    node: ExistsWhereNode
    The CTE node to process.
  • methodVisit
    public virtual void Visit(ExpressionHavingNode node)

    Visits a `CteNode` representing a Common Table Expression.

    node: ExpressionHavingNode
    The CTE node to process.
  • methodVisit
    public virtual void Visit(ExpressionSelectNode node)

    Visits a `CteNode` representing a Common Table Expression.

    node: ExpressionSelectNode
    The CTE node to process.
  • methodVisit
    public virtual void Visit(ExpressionWhereNode node)

    Visits a `CteNode` representing a Common Table Expression.

    node: ExpressionWhereNode
    The CTE node to process.
  • methodVisit
    public virtual void Visit(FromNode node)

    Visits a `CteNode` representing a Common Table Expression.

    node: FromNode
    The CTE node to process.
  • methodVisit
    public virtual void Visit(GroupByNode node)

    Visits a `CteNode` representing a Common Table Expression.

    node: GroupByNode
    The CTE node to process.
  • methodVisit
    public virtual void Visit(InsertNode node)

    Visits a `CteNode` representing a Common Table Expression.

    node: InsertNode
    The CTE node to process.
  • methodVisit
    public virtual void Visit(InsertSelectNode node)

    Visits a `CteNode` representing a Common Table Expression.

    node: InsertSelectNode
    The CTE node to process.
  • methodVisit
    public virtual void Visit(JoinNode node)

    Visits a `CteNode` representing a Common Table Expression.

    node: JoinNode
    The CTE node to process.
  • methodVisit
    public virtual void Visit(LimitOffsetNode node)

    Visits a `CteNode` representing a Common Table Expression.

    node: LimitOffsetNode
    The CTE node to process.
  • methodVisit
    public virtual void Visit(OnConflictNode node)

    Visits a `CteNode` representing a Common Table Expression.

    node: OnConflictNode
    The CTE node to process.
  • methodVisit
    public virtual void Visit(OrderByNode node)

    Visits a `CteNode` representing a Common Table Expression.

    node: OrderByNode
    The CTE node to process.
  • methodVisit
    public virtual void Visit(QueryAliasNode node)

    Visits a `CteNode` representing a Common Table Expression.

    node: QueryAliasNode
    The CTE node to process.
  • methodVisit
    public virtual void Visit(RawHavingNode node)

    Visits a `CteNode` representing a Common Table Expression.

    node: RawHavingNode
    The CTE node to process.
  • methodVisit
    public virtual void Visit(RawJoinNode node)

    Visits a `CteNode` representing a Common Table Expression.

    node: RawJoinNode
    The CTE node to process.
  • methodVisit
    public virtual void Visit(RawOrderByNode node)

    Visits a `CteNode` representing a Common Table Expression.

    node: RawOrderByNode
    The CTE node to process.
  • methodVisit
    public virtual void Visit(RawSelectNode node)

    Visits a `CteNode` representing a Common Table Expression.

    node: RawSelectNode
    The CTE node to process.
  • methodVisit
    public virtual void Visit(RawWhereNode node)

    Visits a `CteNode` representing a Common Table Expression.

    node: RawWhereNode
    The CTE node to process.
  • methodVisit
    public virtual void Visit(ReturningNode node)

    Visits a `CteNode` representing a Common Table Expression.

    node: ReturningNode
    The CTE node to process.
  • methodVisit
    public virtual void Visit(ScalarSubquerySelectNode node)

    Visits a `CteNode` representing a Common Table Expression.

    node: ScalarSubquerySelectNode
    The CTE node to process.
  • methodVisit
    public virtual void Visit(SelectNode node)

    Visits a `CteNode` representing a Common Table Expression.

    node: SelectNode
    The CTE node to process.
  • methodVisit
    public virtual void Visit(SetNode node)

    Visits a `CteNode` representing a Common Table Expression.

    node: SetNode
    The CTE node to process.
  • methodVisit
    public virtual void Visit(SetOperationNode node)

    Visits a `CteNode` representing a Common Table Expression.

    node: SetOperationNode
    The CTE node to process.
  • methodVisit
    public virtual void Visit(SubqueryFromNode node)

    Visits a `CteNode` representing a Common Table Expression.

    node: SubqueryFromNode
    The CTE node to process.
  • methodVisit
    public virtual void Visit(SubqueryJoinNode node)

    Visits a `CteNode` representing a Common Table Expression.

    node: SubqueryJoinNode
    The CTE node to process.
  • methodVisit
    public virtual void Visit(ThenByNode node)

    Visits a `CteNode` representing a Common Table Expression.

    node: ThenByNode
    The CTE node to process.
  • methodVisit
    public virtual void Visit(UnnestNode node)

    Visits a `CteNode` representing a Common Table Expression.

    node: UnnestNode
    The CTE node to process.
  • methodVisit
    public virtual void Visit(UpdateNode node)

    Visits a `CteNode` representing a Common Table Expression.

    node: UpdateNode
    The CTE node to process.
  • methodVisit
    public virtual void Visit(ValuesNode node)

    Visits a `CteNode` representing a Common Table Expression.

    node: ValuesNode
    The CTE node to process.
  • methodVisit
    public virtual void Visit(WindowFunctionNode node)

    Visits a `CteNode` representing a Common Table Expression.

    node: WindowFunctionNode
    The CTE node to process.
  • methodVisit
    public virtual void Visit(WindowNode node)

    Visits a `CteNode` representing a Common Table Expression.

    node: WindowNode
    The CTE node to process.
  • methodVisit
    public virtual void Visit(WindowPageNode node)

    Visits a `CteNode` representing a Common Table Expression.

    node: WindowPageNode
    The CTE node to process.
  • methodVisitExtension
    public virtual void VisitExtension(SqlExtensionNode node)

    Extension point for processing unknown or custom nodes.

    node: SqlExtensionNode
    The custom extension node to process.
  • methodVisitUnknown
    public virtual void VisitUnknown(ISqlNode node)

    Handles a node type that is not recognized by this visitor.

    node: ISqlNode
    The unrecognized node.

EricksonLopez.SqlBuilder.Abstractions.Exceptions#

4
class

SqlBuilderException

Assembly: EricksonLopez.SqlBuilder.Abstractions
public class SqlBuilderException : Exception
Inherits: Exception

Represents the base exception type for all errors raised within the SqlBuilder ecosystem.

Members (2)

  • constructorSqlBuilderException
    public SqlBuilderException(string message)

    Initializes a new instance of the `SqlBuilderException` class with a specified error message.

    message: string
    The message that describes the error.
  • constructorSqlBuilderException
    public SqlBuilderException(string message, Exception innerException)

    Initializes a new instance of the `SqlBuilderException` class with a specified error message and inner exception.

    message: string
    The message that describes the error.
    innerException: Exception
    The exception that is the cause of the current exception.
class

SqlSafetyException

Assembly: EricksonLopez.SqlBuilder.Abstractions
public class SqlSafetyException : SqlBuilderException
Inherits: SqlBuilderException

Exception thrown when a query violates safety guardrails (e.g. unconstrained mutations or injection attempts).

Members (2)

  • constructorSqlSafetyException
    public SqlSafetyException(string message)

    Initializes a new instance of the `SqlSafetyException` class with a specified error message.

    message: string
    The message that describes the error.
  • constructorSqlSafetyException
    public SqlSafetyException(string message, Exception innerException)

    Initializes a new instance of the `SqlSafetyException` class with a specified error message and inner exception.

    message: string
    The message that describes the error.
    innerException: Exception
    The exception that is the cause of the current exception.
class

SqlSyntaxException

Assembly: EricksonLopez.SqlBuilder.Abstractions
public class SqlSyntaxException : SqlBuilderException
Inherits: SqlBuilderException

Exception thrown when an abstract syntax tree contains conflicting, incomplete, or unsupported SQL constructs.

Members (2)

  • constructorSqlSyntaxException
    public SqlSyntaxException(string message)

    Initializes a new instance of the `SqlSyntaxException` class with a specified error message.

    message: string
    The message that describes the error.
  • constructorSqlSyntaxException
    public SqlSyntaxException(string message, Exception innerException)

    Initializes a new instance of the `SqlSyntaxException` class with a specified error message and inner exception.

    message: string
    The message that describes the error.
    innerException: Exception
    The exception that is the cause of the current exception.
class

SqlValidationException

Assembly: EricksonLopez.SqlBuilder.Abstractions
public class SqlValidationException : SqlBuilderException
Inherits: SqlBuilderException

Represents the exception thrown when a SQL query Abstract Syntax Tree fails structural validation prior to compilation.

Members (2)

  • constructorSqlValidationException
    public SqlValidationException(string message)

    Initializes a new instance of the `SqlValidationException` class with a specified error message.

    message: string
    The message that describes the error.
  • constructorSqlValidationException
    public SqlValidationException(string message, Exception innerException)

    Initializes a new instance of the `SqlValidationException` class with a specified error message and inner exception.

    message: string
    The message that describes the error.
    innerException: Exception
    The exception that is the cause of the current exception.

EricksonLopez.SqlBuilder.Abstractions.Metadata#

5
enum

ColumnFlags

Assembly: EricksonLopez.SqlBuilder.Abstractions
public enum ColumnFlags

Specifies flags that describe the behavior and characteristics of a database column.

Members (6)

  • fieldComputed
    Computed = 1<<3

    Indicates that the column is a computed or virtual column.

  • fieldGeneratedAlways
    GeneratedAlways = 1<<2

    Indicates that the column value is always generated by the database.

  • fieldIdentity
    Identity = 1<<1

    Indicates that the column is an identity or auto-incrementing column.

  • fieldNone
    None = 0

    Indicates that no special column flags are applied.

  • fieldNullable
    Nullable = 1<<4

    Indicates that the column permits null values.

  • fieldPrimaryKey
    PrimaryKey = 1<<0

    Indicates that the column forms part of the primary key.

record

ColumnMetadata

Assembly: EricksonLopez.SqlBuilder.Abstractions
public readonly record struct ColumnMetadata(int Index, string Name, ColumnFlags Flags)

Provides metadata for a database column associated with an entity property.

Members (5)

  • constructorColumnMetadata
    public ColumnMetadata(int Index, string Name, ColumnFlags Flags)

    Initializes a new instance of ColumnMetadata.

    Index: int
    The zero-based index of the column within the entity's column list.
    Name: string
    The mapped name of the column in the database.
    Flags: ColumnFlags
    The characteristics of the column.
  • methodHasFlag
    public bool HasFlag(ColumnFlags flag)

    Determines whether the column has the specified flag.

    flag: ColumnFlags
    The flag to check.

    Returns: `true` if the column has the specified flag; otherwise, `false`.

  • propertyFlags
    public ColumnFlags Flags { get; init; }

    The characteristics of the column.

  • propertyIndex
    public int Index { get; init; }

    The zero-based index of the column within the entity's column list.

  • propertyName
    public string Name { get; init; }

    The mapped name of the column in the database.

record

ColumnToken

Assembly: EricksonLopez.SqlBuilder.Abstractions
public readonly record struct ColumnToken(int Index)

Represents a lightweight token identifying a column index for metadata operations.

Members (2)

  • constructorColumnToken
    public ColumnToken(int Index)

    Initializes a new instance of ColumnToken.

    Index: int
    The zero-based index of the column.
  • propertyIndex
    public int Index { get; init; }

    The zero-based index of the column.

interface

IStaticEntityMetadata<TEntity>

Assembly: EricksonLopez.SqlBuilder.Abstractions
public interface IStaticEntityMetadata<TEntity>

Defines the static metadata and operations required for AOT-optimized query generation for a specific entity type.

Remarks:

Type parameters: TEntity: The type of the entity associated with this metadata.

Members (11)

  • methodAreEqual
    static abstract bool AreEqual(TEntity entity, TEntity snapshot, int columnIndex)

    Determines whether the value of the specified column is equal between the current entity and a snapshot.

    entity: TEntity
    The current entity instance.
    snapshot: TEntity
    The original snapshot of the entity.
    columnIndex: int
    The zero-based index of the column to compare.

    Returns: `true` if the values are equal; otherwise, `false`.

  • methodBindParameter
    static abstract string BindParameter(TEntity entity, int columnIndex, IParameterManager parameters)

    Binds the value of the specified column to the provided parameter manager and returns the parameter name.

    entity: TEntity
    The entity containing the value to bind.
    columnIndex: int
    The zero-based index of the column.
    parameters: IParameterManager
    The parameter manager responsible for holding the bound parameter.

    Returns: The name of the bound parameter.

  • methodExtractColumnArrays
    static abstract void ExtractColumnArrays(ReadOnlySpan<TEntity> entities, ReadOnlySpan<bool> activeColumns, IParameterManager parameters)

    Extracts a batch of entities into column-based arrays and binds them to the parameter manager.

    entities: ReadOnlySpan<TEntity>
    A read-only span of entities to extract.
    activeColumns: ReadOnlySpan<bool>
    A read-only span of booleans indicating which columns should be extracted.
    parameters: IParameterManager
    The parameter manager where the extracted arrays will be bound.

    Supports bulk operations that rely on parameter arrays (e.g., PostgreSQL COPY or array unnesting).

  • methodFromReader
    static abstract TEntity FromReader(System.Data.IDataReader reader)

    Reads and parses a single entity instance from an active `Data.IDataReader` row.

    reader: System.Data.IDataReader
    The active data reader positioned at a valid row.

    Returns: A populated instance of `TEntity`.

  • methodGetColumnName
    static abstract string GetColumnName(int columnIndex)

    Retrieves the database column name for the specified column index.

    columnIndex: int
    The zero-based index of the column.

    Returns: The physical name of the column in the database.

  • methodGetColumns
    static abstract ReadOnlySpan<ColumnMetadata> GetColumns()

    Retrieves a read-only span containing the metadata for all mapped columns.

    Returns: A read-only span of `ColumnMetadata`.

  • methodGetReaderParser
    static abstract Func<System.Data.IDataReader, TEntity> GetReaderParser()

    Returns a high-performance, reusable reader parser delegate for `TEntity`.

    Returns: A delegate that reads and maps reader rows into `TEntity`.

  • methodIsDefault
    static abstract bool IsDefault(TEntity entity, int columnIndex)

    Determines whether the value of the specified column is the default value for the given entity.

    entity: TEntity
    The entity instance to evaluate.
    columnIndex: int
    The zero-based index of the column.

    Returns: `true` if the column value is the default value; otherwise, `false`.

  • methodIsNull
    static abstract bool IsNull(TEntity entity, int columnIndex)

    Determines whether the value of the specified column is null for the given entity.

    entity: TEntity
    The entity instance to evaluate.
    columnIndex: int
    The zero-based index of the column.

    Returns: `true` if the column value is null; otherwise, `false`.

  • propertyColumnCount
    static abstract int ColumnCount { get; }

    Gets the total number of columns mapped for the entity.

  • propertyTableName
    static abstract string TableName { get; }

    Gets the name of the database table associated with the entity.

enum

SqlOperation

Assembly: EricksonLopez.SqlBuilder.Abstractions
public enum SqlOperation

Specifies the type of SQL operation being constructed or executed.

Members (5)

  • fieldDelete
    Delete = 3

    Represents a data deletion operation (DELETE).

  • fieldInsert
    Insert = 1

    Represents a data insertion operation (INSERT).

  • fieldMerge
    Merge = 4

    Represents a data merge or upsert operation (MERGE).

  • fieldSelect
    Select = 0

    Represents a data retrieval operation (SELECT).

  • fieldUpdate
    Update = 2

    Represents a data modification operation (UPDATE).

EricksonLopez.SqlBuilder.Abstractions.Nodes#

46
record

CaseNode

Assembly: EricksonLopez.SqlBuilder.Abstractions
public sealed record CaseNode(CaseWhenBranch[] Branches, string? ElseSql, object?[]? ElseParameters, string? Alias) : ISqlNode
Implements: ISqlNode

Represents a SQL CASE expression node for use inside a SELECT or WHERE clause.

Remarks:

Generates SQL of the form: `CASE WHEN condition1 THEN result1 [WHEN condition2 THEN result2 ...] [ELSE else_result] END AS alias` Use via the `SelectCase` method on `SelectQuery<T>` or the `CaseExpressionBuilder` fluent builder for a type-safe API.

Members (6)

  • constructorCaseNode
    public CaseNode(CaseWhenBranch[] Branches, string? ElseSql, object?[]? ElseParameters, string? Alias)

    Initializes a new instance of CaseNode.

    Branches: CaseWhenBranch[]
    The branches of the CASE expression.
    ElseSql: string?
    The optional ELSE SQL expression.
    ElseParameters: object?[]?
    The optional parameters for the ELSE SQL expression.
    Alias: string?
    The optional alias for the CASE expression.
  • methodAccept
    public void Accept(ISqlVisitor visitor)

    Accepts a visitor to perform double-dispatch traversal of the AST.

    visitor: ISqlVisitor
    The visitor instance handling the node.
  • propertyAlias
    public string? Alias { get; init; }

    The optional alias for the CASE expression.

  • propertyBranches
    public CaseWhenBranch[] Branches { get; init; }

    The branches of the CASE expression.

  • propertyElseParameters
    public object?[]? ElseParameters { get; init; }

    The optional parameters for the ELSE SQL expression.

  • propertyElseSql
    public string? ElseSql { get; init; }

    The optional ELSE SQL expression.

record

CaseWhenBranch

Assembly: EricksonLopez.SqlBuilder.Abstractions
public record CaseWhenBranch(string WhenSql, object?[]? WhenParameters, string ThenSql, object?[]? ThenParameters)

Represents a single WHEN ... THEN ... branch within a CASE expression.

Members (5)

  • constructorCaseWhenBranch
    public CaseWhenBranch(string WhenSql, object?[]? WhenParameters, string ThenSql, object?[]? ThenParameters)

    Initializes a new instance of CaseWhenBranch.

    WhenSql: string
    The raw SQL condition for the WHEN clause (e.g., `"status = 1"`).
    WhenParameters: object?[]?
    Optional parameters for the WHEN condition.
    ThenSql: string
    The raw SQL result expression for the THEN clause (e.g., `"'Active'"`).
    ThenParameters: object?[]?
    Optional parameters for the THEN expression.
  • propertyThenParameters
    public object?[]? ThenParameters { get; init; }

    Optional parameters for the THEN expression.

  • propertyThenSql
    public string ThenSql { get; init; }

    The raw SQL result expression for the THEN clause (e.g., `"'Active'"`).

  • propertyWhenParameters
    public object?[]? WhenParameters { get; init; }

    Optional parameters for the WHEN condition.

  • propertyWhenSql
    public string WhenSql { get; init; }

    The raw SQL condition for the WHEN clause (e.g., `"status = 1"`).

record

CompositeCursorNode

Assembly: EricksonLopez.SqlBuilder.Abstractions
public sealed record CompositeCursorNode(CursorKey[] Keys, bool IsAfter) : ISqlNode
Implements: ISqlNode

Represents a composite keyset cursor node for multi-column keyset pagination.

Members (4)

  • constructorCompositeCursorNode
    public CompositeCursorNode(CursorKey[] Keys, bool IsAfter = true)

    Initializes a new instance of CompositeCursorNode.

    Keys: CursorKey[]
    IsAfter: bool
  • methodAccept
    public void Accept(ISqlVisitor visitor)

    Accepts a visitor to perform double-dispatch traversal of the AST.

    visitor: ISqlVisitor
    The visitor instance handling the node.
  • propertyIsAfter
    public bool IsAfter { get; init; }
  • propertyKeys
    public CursorKey[] Keys { get; init; }
record

ConcurrencyTokenNode

Assembly: EricksonLopez.SqlBuilder.Abstractions
public sealed record ConcurrencyTokenNode(string ColumnName, object? ExpectedValue, object? NewValue, bool AutoIncrement) : ISqlNode
Implements: ISqlNode

Represents an optimistic concurrency check appended to an UPDATE statement.

Remarks:

This node generates an additional `AND column = @expectedValue` in the WHERE clause and, for integer/long tokens, also generates `SET column = column + 1` automatically. Pattern:

UPDATE users SET name = @name, version = version + 1
WHERE id = @id AND version = @expectedVersion

If the UPDATE affects 0 rows, a concurrency conflict has occurred.

Members (6)

  • constructorConcurrencyTokenNode
    public ConcurrencyTokenNode(string ColumnName, object? ExpectedValue, object? NewValue = null, bool AutoIncrement = true)

    Initializes a new instance of ConcurrencyTokenNode.

    ColumnName: string
    The name of the concurrency token column (e.g., "version").
    ExpectedValue: object?
    The expected current value of the token before update.
    NewValue: object?
    Optional explicit new value. If `null`, integer/long tokens auto-increment (`column = column + 1`); other types require an explicit new value.
    AutoIncrement: bool
    When `true`, emits `SET column = column + 1` for integer tokens. When `false`, uses `NewValue` in the SET clause.

    This node generates an additional `AND column = @expectedValue` in the WHERE clause and, for integer/long tokens, also generates `SET column = column + 1` automatically. Pattern:

    UPDATE users SET name = @name, version = version + 1
    WHERE id = @id AND version = @expectedVersion

    If the UPDATE affects 0 rows, a concurrency conflict has occurred.

  • methodAccept
    public void Accept(ISqlVisitor visitor)

    Accepts a visitor to perform double-dispatch traversal of the AST.

    visitor: ISqlVisitor
    The visitor instance handling the node.
  • propertyAutoIncrement
    public bool AutoIncrement { get; init; }

    When `true`, emits `SET column = column + 1` for integer tokens. When `false`, uses `NewValue` in the SET clause.

  • propertyColumnName
    public string ColumnName { get; init; }

    The name of the concurrency token column (e.g., "version").

  • propertyExpectedValue
    public object? ExpectedValue { get; init; }

    The expected current value of the token before update.

  • propertyNewValue
    public object? NewValue { get; init; }

    Optional explicit new value. If `null`, integer/long tokens auto-increment (`column = column + 1`); other types require an explicit new value.

record

CteNode

Assembly: EricksonLopez.SqlBuilder.Abstractions
public sealed record CteNode(string Name, ISqlQuery Query, bool IsRecursive, MaterializationHint Materialization) : ISqlNode
Implements: ISqlNode

Represents a Common Table Expression (CTE) clause in a SQL query.

Members (6)

  • constructorCteNode
    public CteNode(string Name, ISqlQuery Query, bool IsRecursive = false, MaterializationHint Materialization = MaterializationHint.Default)

    Initializes a new instance of CteNode.

    Name: string
    The name of the CTE referenced in the main query body.
    Query: ISqlQuery
    The SQL query that defines the CTE body.
    IsRecursive: bool
    If `true`, emits a RECURSIVE modifier (supported in PostgreSQL and SQLite).
    Materialization: MaterializationHint
    The materialization hint (e.g., MATERIALIZED, NOT MATERIALIZED in PostgreSQL).
  • methodAccept
    public void Accept(ISqlVisitor visitor)

    Accepts a visitor to perform double-dispatch traversal of the AST.

    visitor: ISqlVisitor
    The visitor instance handling the node.
  • propertyIsRecursive
    public bool IsRecursive { get; init; }

    If `true`, emits a RECURSIVE modifier (supported in PostgreSQL and SQLite).

  • propertyMaterialization
    public MaterializationHint Materialization { get; init; }

    The materialization hint (e.g., MATERIALIZED, NOT MATERIALIZED in PostgreSQL).

  • propertyName
    public string Name { get; init; }

    The name of the CTE referenced in the main query body.

  • propertyQuery
    public ISqlQuery Query { get; init; }

    The SQL query that defines the CTE body.

record

CursorKey

Assembly: EricksonLopez.SqlBuilder.Abstractions
public record CursorKey(string ColumnName, object? Value, bool IsDescending)

Represents a key column used in composite cursor (keyset) pagination.

Members (4)

  • constructorCursorKey
    public CursorKey(string ColumnName, object? Value, bool IsDescending = false)

    Initializes a new instance of CursorKey.

    ColumnName: string
    The SQL column name.
    Value: object?
    The anchor value for this column from the last/first row seen.
    IsDescending: bool
    If `true`, this column is sorted descending; otherwise ascending.
  • propertyColumnName
    public string ColumnName { get; init; }

    The SQL column name.

  • propertyIsDescending
    public bool IsDescending { get; init; }

    If `true`, this column is sorted descending; otherwise ascending.

  • propertyValue
    public object? Value { get; init; }

    The anchor value for this column from the last/first row seen.

record

DefaultValuesNode

Assembly: EricksonLopez.SqlBuilder.Abstractions
public sealed record DefaultValuesNode : ISqlNode
Implements: ISqlNode

Represents a DEFAULT VALUES clause in an INSERT statement.

Members (1)

  • methodAccept
    public void Accept(ISqlVisitor visitor)

    Accepts a visitor to perform double-dispatch traversal of the AST.

    visitor: ISqlVisitor
    The visitor instance handling the node.
record

DeleteNode

Assembly: EricksonLopez.SqlBuilder.Abstractions
public sealed record DeleteNode(string TableName) : ISqlNode
Implements: ISqlNode

Represents a DELETE clause specifying the target table.

Members (4)

  • constructorDeleteNode
    public DeleteNode(string TableName)

    Initializes a new instance of DeleteNode.

    TableName: string
    The name of the target table to delete from.
  • methodAccept
    public void Accept(ISqlVisitor visitor)

    Accepts a visitor to perform double-dispatch traversal of the AST.

    visitor: ISqlVisitor
    The visitor instance handling the node.
  • methodContributeToFingerprint
    public void ContributeToFingerprint(IQueryFingerprinter fingerprinter)

    Contributes the structure of this node to a deterministic cryptographic fingerprint. Values and parameter arguments are ignored to ensure the fingerprint only reflects the AST shape.

    fingerprinter: IQueryFingerprinter
    The fingerprinter instance.
  • propertyTableName
    public string TableName { get; init; }

    The name of the target table to delete from.

record

DistinctOnNode

Assembly: EricksonLopez.SqlBuilder.Abstractions
public sealed record DistinctOnNode(string[] Columns) : ISqlNode
Implements: ISqlNode

Represents a DISTINCT ON clause supported in PostgreSQL.

Members (4)

  • constructorDistinctOnNode
    public DistinctOnNode(string[] Columns)

    Initializes a new instance of DistinctOnNode.

    Columns: string[]
    The columns evaluated in the DISTINCT ON expression.
  • methodAccept
    public void Accept(ISqlVisitor visitor)

    Accepts a visitor to perform double-dispatch traversal of the AST.

    visitor: ISqlVisitor
    The visitor instance handling the node.
  • methodContributeToFingerprint
    public void ContributeToFingerprint(IQueryFingerprinter fingerprinter)

    Contributes the structure of this node to a deterministic cryptographic fingerprint. Values and parameter arguments are ignored to ensure the fingerprint only reflects the AST shape.

    fingerprinter: IQueryFingerprinter
    The fingerprinter instance.
  • propertyColumns
    public string[] Columns { get; init; }

    The columns evaluated in the DISTINCT ON expression.

record

ExistsWhereNode

Assembly: EricksonLopez.SqlBuilder.Abstractions
public sealed record ExistsWhereNode(ISqlQuery Subquery, bool IsNot, bool IsOr) : ISqlNode
Implements: ISqlNode

Represents a WHERE EXISTS (subquery) condition.

Members (5)

  • constructorExistsWhereNode
    public ExistsWhereNode(ISqlQuery Subquery, bool IsNot = false, bool IsOr = false)

    Initializes a new instance of ExistsWhereNode.

    Subquery: ISqlQuery
    The subquery evaluated inside the EXISTS (or NOT EXISTS) predicate.
    IsNot: bool
    If `true`, generates NOT EXISTS; otherwise, generates EXISTS.
    IsOr: bool
    If `true`, combines this condition with OR instead of AND.
  • methodAccept
    public void Accept(ISqlVisitor visitor)

    Accepts a visitor to perform double-dispatch traversal of the AST.

    visitor: ISqlVisitor
    The visitor instance handling the node.
  • propertyIsNot
    public bool IsNot { get; init; }

    If `true`, generates NOT EXISTS; otherwise, generates EXISTS.

  • propertyIsOr
    public bool IsOr { get; init; }

    If `true`, combines this condition with OR instead of AND.

  • propertySubquery
    public ISqlQuery Subquery { get; init; }

    The subquery evaluated inside the EXISTS (or NOT EXISTS) predicate.

record

ExpressionHavingNode

Assembly: EricksonLopez.SqlBuilder.Abstractions
public sealed record ExpressionHavingNode(Expression Expression, bool IsOr) : ISqlNode
Implements: ISqlNode

Represents a HAVING clause constructed from a LINQ expression.

Members (5)

  • constructorExpressionHavingNode
    public ExpressionHavingNode(Expression Expression, bool IsOr = false)

    Initializes a new instance of ExpressionHavingNode.

    Expression: Expression
    The LINQ expression representing the HAVING predicate.
    IsOr: bool
    If `true`, combines this condition with OR; otherwise combines with AND.
  • methodAccept
    public void Accept(ISqlVisitor visitor)

    Accepts a visitor to perform double-dispatch traversal of the AST.

    visitor: ISqlVisitor
    The visitor instance handling the node.
  • methodContributeToFingerprint
    public void ContributeToFingerprint(IQueryFingerprinter fingerprinter)

    Contributes the structure of this node to a deterministic cryptographic fingerprint. Values and parameter arguments are ignored to ensure the fingerprint only reflects the AST shape.

    fingerprinter: IQueryFingerprinter
    The fingerprinter instance.
  • propertyExpression
    public Expression Expression { get; init; }

    The LINQ expression representing the HAVING predicate.

  • propertyIsOr
    public bool IsOr { get; init; }

    If `true`, combines this condition with OR; otherwise combines with AND.

record

ExpressionSelectNode

Assembly: EricksonLopez.SqlBuilder.Abstractions
public sealed record ExpressionSelectNode(Expression Selector, bool IsDistinct) : ISqlNode
Implements: ISqlNode

Represents a SELECT clause derived from a LINQ projection expression.

Members (5)

  • constructorExpressionSelectNode
    public ExpressionSelectNode(Expression Selector, bool IsDistinct)

    Initializes a new instance of ExpressionSelectNode.

    Selector: Expression
    The LINQ expression specifying projected members.
    IsDistinct: bool
    If `true`, emits the DISTINCT keyword.
  • methodAccept
    public void Accept(ISqlVisitor visitor)

    Accepts a visitor to perform double-dispatch traversal of the AST.

    visitor: ISqlVisitor
    The visitor instance handling the node.
  • methodContributeToFingerprint
    public void ContributeToFingerprint(IQueryFingerprinter fingerprinter)

    Contributes the structure of this node to a deterministic cryptographic fingerprint. Values and parameter arguments are ignored to ensure the fingerprint only reflects the AST shape.

    fingerprinter: IQueryFingerprinter
    The fingerprinter instance.
  • propertyIsDistinct
    public bool IsDistinct { get; init; }

    If `true`, emits the DISTINCT keyword.

  • propertySelector
    public Expression Selector { get; init; }

    The LINQ expression specifying projected members.

record

ExpressionWhereNode

Assembly: EricksonLopez.SqlBuilder.Abstractions
public sealed record ExpressionWhereNode(Expression Expression, bool IsOr) : ISqlNode
Implements: ISqlNode

Represents a WHERE condition based on a strongly-typed LINQ expression.

Members (5)

  • constructorExpressionWhereNode
    public ExpressionWhereNode(Expression Expression, bool IsOr = false)

    Initializes a new instance of ExpressionWhereNode.

    Expression: Expression
    The LINQ expression representing the WHERE predicate.
    IsOr: bool
    If `true`, combines this condition with OR; otherwise combines with AND.
  • methodAccept
    public void Accept(ISqlVisitor visitor)

    Accepts a visitor to perform double-dispatch traversal of the AST.

    visitor: ISqlVisitor
    The visitor instance handling the node.
  • methodContributeToFingerprint
    public void ContributeToFingerprint(IQueryFingerprinter fingerprinter)

    Contributes the structure of this node to a deterministic cryptographic fingerprint. Values and parameter arguments are ignored to ensure the fingerprint only reflects the AST shape.

    fingerprinter: IQueryFingerprinter
    The fingerprinter instance.
  • propertyExpression
    public Expression Expression { get; init; }

    The LINQ expression representing the WHERE predicate.

  • propertyIsOr
    public bool IsOr { get; init; }

    If `true`, combines this condition with OR; otherwise combines with AND.

record

FromNode

Assembly: EricksonLopez.SqlBuilder.Abstractions
public sealed record FromNode(string TableName, string? Alias) : ISqlNode
Implements: ISqlNode

Represents a standard FROM clause for a table or view.

Members (5)

  • constructorFromNode
    public FromNode(string TableName, string? Alias = null)

    Initializes a new instance of FromNode.

    TableName: string
    The name of the table or view.
    Alias: string?
    An optional alias for the table.
  • methodAccept
    public void Accept(ISqlVisitor visitor)

    Accepts a visitor to perform double-dispatch traversal of the AST.

    visitor: ISqlVisitor
    The visitor instance handling the node.
  • methodContributeToFingerprint
    public void ContributeToFingerprint(IQueryFingerprinter fingerprinter)

    Contributes the structure of this node to a deterministic cryptographic fingerprint. Values and parameter arguments are ignored to ensure the fingerprint only reflects the AST shape.

    fingerprinter: IQueryFingerprinter
    The fingerprinter instance.
  • propertyAlias
    public string? Alias { get; init; }

    An optional alias for the table.

  • propertyTableName
    public string TableName { get; init; }

    The name of the table or view.

record

GroupByNode

Assembly: EricksonLopez.SqlBuilder.Abstractions
public sealed record GroupByNode(IReadOnlyList<string> Columns, GroupByType Type, IReadOnlyList<IReadOnlyList<string>>? Sets) : ISqlNode
Implements: ISqlNode

Represents a GROUP BY clause in a SQL query.

Members (7)

  • constructorGroupByNode
    public GroupByNode(IReadOnlyList<string> Columns, GroupByType Type = GroupByType.Standard, IReadOnlyList<IReadOnlyList<string>>? Sets = null)

    Initializes a new instance of GroupByNode.

    Columns: IReadOnlyList<string>
    The ordered list of column names to group by.
    Type: GroupByType
    The grouping aggregation type (Standard, Rollup, Cube, GroupingSets).
    Sets: IReadOnlyList<IReadOnlyList<string>>?
    The list of column sets when `Type` is `GroupByType.GroupingSets`.
  • methodAccept
    public void Accept(ISqlVisitor visitor)

    Accepts a visitor to perform double-dispatch traversal of the AST.

    visitor: ISqlVisitor
    The visitor instance handling the node.
  • methodContributeToFingerprint
    public void ContributeToFingerprint(IQueryFingerprinter fingerprinter)

    Contributes the structure of this node to a deterministic cryptographic fingerprint. Values and parameter arguments are ignored to ensure the fingerprint only reflects the AST shape.

    fingerprinter: IQueryFingerprinter
    The fingerprinter instance.
  • methodContributeToFingerprinter
    public void ContributeToFingerprinter(IQueryFingerprinter fingerprinter)

    Contributes the structure of this node to a deterministic cryptographic fingerprint.

    fingerprinter: IQueryFingerprinter
    The fingerprinter instance.
  • propertyColumns
    public IReadOnlyList<string> Columns { get; init; }

    The ordered list of column names to group by.

  • propertySets
    public IReadOnlyList<IReadOnlyList<string>>? Sets { get; init; }

    The list of column sets when `Type` is `GroupByType.GroupingSets`.

  • propertyType
    public GroupByType Type { get; init; }

    The grouping aggregation type (Standard, Rollup, Cube, GroupingSets).

enum

GroupByType

Assembly: EricksonLopez.SqlBuilder.Abstractions
public enum GroupByType

Specifies the type of aggregation grouping in a GROUP BY clause.

Members (4)

  • fieldCube
    Cube = 2

    Multidimensional CUBE aggregation (GROUP BY CUBE(c1, c2)).

  • fieldGroupingSets
    GroupingSets = 3

    Explicit GROUPING SETS aggregation (GROUP BY GROUPING SETS ((c1), (c2))).

  • fieldRollup
    Rollup = 1

    Hierarchical ROLLUP aggregation (GROUP BY ROLLUP(c1, c2)).

  • fieldStandard
    Standard = 0

    Standard GROUP BY column list.

record

InsertNode

Assembly: EricksonLopez.SqlBuilder.Abstractions
public sealed record InsertNode(string TableName, IReadOnlyList<string> Columns) : ISqlNode
Implements: ISqlNode

Represents the INTO part of an INSERT statement specifying target table and columns.

Members (5)

  • constructorInsertNode
    public InsertNode(string TableName, IReadOnlyList<string> Columns)

    Initializes a new instance of InsertNode.

    TableName: string
    The name of the target table to insert into.
    Columns: IReadOnlyList<string>
    The list of column names receiving inserted values.
  • methodAccept
    public void Accept(ISqlVisitor visitor)

    Accepts a visitor to perform double-dispatch traversal of the AST.

    visitor: ISqlVisitor
    The visitor instance handling the node.
  • methodContributeToFingerprint
    public void ContributeToFingerprint(IQueryFingerprinter fingerprinter)

    Contributes the structure of this node to a deterministic cryptographic fingerprint. Values and parameter arguments are ignored to ensure the fingerprint only reflects the AST shape.

    fingerprinter: IQueryFingerprinter
    The fingerprinter instance.
  • propertyColumns
    public IReadOnlyList<string> Columns { get; init; }

    The list of column names receiving inserted values.

  • propertyTableName
    public string TableName { get; init; }

    The name of the target table to insert into.

record

InsertSelectNode

Assembly: EricksonLopez.SqlBuilder.Abstractions
public sealed record InsertSelectNode(string TableName, string[]? Columns, ISqlQuery SelectQuery) : ISqlNode
Implements: ISqlNode

Represents an INSERT INTO ... SELECT ... statement, which inserts rows derived from a SELECT query.

Remarks:

Serves as the primary mechanism for INSERT INTO ... SELECT statements in the AST across all supported SQL dialects. Example generated SQL:

INSERT INTO archive_orders ("id", "customer_id", "total")
SELECT "id", "customer_id", "total" FROM "orders" WHERE "status" = @p0

The target table columns must match the projected column count and data types from the SELECT query.

Members (5)

  • constructorInsertSelectNode
    public InsertSelectNode(string TableName, string[]? Columns, ISqlQuery SelectQuery)

    Initializes a new instance of InsertSelectNode.

    TableName: string
    The name of the target table.
    Columns: string[]?
    Optional array of column names. When specified, generates INSERT INTO table (col1, col2, ...) SELECT ... When null or empty, generates INSERT INTO table SELECT ...
    SelectQuery: ISqlQuery
    The SELECT query whose results are inserted into the target table.

    Serves as the primary mechanism for INSERT INTO ... SELECT statements in the AST across all supported SQL dialects. Example generated SQL:

    INSERT INTO archive_orders ("id", "customer_id", "total")
    SELECT "id", "customer_id", "total" FROM "orders" WHERE "status" = @p0

    The target table columns must match the projected column count and data types from the SELECT query.

  • methodAccept
    public void Accept(ISqlVisitor visitor)

    Accepts a visitor to perform double-dispatch traversal of the AST.

    visitor: ISqlVisitor
    The visitor instance handling the node.
  • propertyColumns
    public string[]? Columns { get; init; }

    Optional array of column names. When specified, generates INSERT INTO table (col1, col2, ...) SELECT ... When null or empty, generates INSERT INTO table SELECT ...

  • propertySelectQuery
    public ISqlQuery SelectQuery { get; init; }

    The SELECT query whose results are inserted into the target table.

  • propertyTableName
    public string TableName { get; init; }

    The name of the target table.

record

JoinNode

Assembly: EricksonLopez.SqlBuilder.Abstractions
public sealed record JoinNode(JoinType Type, string TableName, string? Alias, string? RawCondition, Expression? ExpressionCondition) : ISqlNode
Implements: ISqlNode

Represents a JOIN clause in a SQL query.

Members (8)

  • constructorJoinNode
    public JoinNode(JoinType Type, string TableName, string? Alias, string? RawCondition = null, Expression? ExpressionCondition = null)

    Initializes a new instance of JoinNode.

    Type: JoinType
    The type of join.
    TableName: string
    The table name.
    Alias: string?
    The table alias.
    RawCondition: string?
    The raw ON condition.
    ExpressionCondition: Expression?
    The typed ON condition.
  • methodAccept
    public void Accept(ISqlVisitor visitor)

    Accepts a visitor to perform double-dispatch traversal of the AST.

    visitor: ISqlVisitor
    The visitor instance handling the node.
  • methodContributeToFingerprint
    public void ContributeToFingerprint(IQueryFingerprinter fingerprinter)

    Contributes the structure of this node to a deterministic cryptographic fingerprint. Values and parameter arguments are ignored to ensure the fingerprint only reflects the AST shape.

    fingerprinter: IQueryFingerprinter
    The fingerprinter instance.
  • propertyAlias
    public string? Alias { get; init; }

    The table alias.

  • propertyExpressionCondition
    public Expression? ExpressionCondition { get; init; }

    The typed ON condition.

  • propertyRawCondition
    public string? RawCondition { get; init; }

    The raw ON condition.

  • propertyTableName
    public string TableName { get; init; }

    The table name.

  • propertyType
    public JoinType Type { get; init; }

    The type of join.

enum

JoinType

Assembly: EricksonLopez.SqlBuilder.Abstractions
public enum JoinType

Specifies the type of a SQL JOIN clause.

Members (7)

  • fieldCross
    Cross

    Specifies a CROSS JOIN operation.

  • fieldCrossApply
    CrossApply

    Specifies a CROSS APPLY or INNER JOIN LATERAL operation.

  • fieldFull
    Full

    Specifies a FULL OUTER JOIN operation.

  • fieldInner
    Inner

    Specifies an INNER JOIN operation.

  • fieldLeft
    Left

    Specifies a LEFT OUTER JOIN operation.

  • fieldOuterApply
    OuterApply

    Specifies an OUTER APPLY or LEFT JOIN LATERAL operation.

  • fieldRight
    Right

    Specifies a RIGHT OUTER JOIN operation.

record

LimitOffsetNode

Assembly: EricksonLopez.SqlBuilder.Abstractions
public sealed record LimitOffsetNode : ISqlNode
Implements: ISqlNode

Represents a LIMIT and/or OFFSET clause for query pagination.

Members (6)

  • constructorLimitOffsetNode
    public LimitOffsetNode(int? limit, int? offset)

    Initializes a new instance of the `LimitOffsetNode` record.

    limit: int?
    The maximum number of rows to return.
    offset: int?
    The number of rows to skip.

    Exceptions: ArgumentOutOfRangeException: `limit` or `offset` is negative

  • methodAccept
    public void Accept(ISqlVisitor visitor)

    Accepts a visitor to perform double-dispatch traversal of the AST.

    visitor: ISqlVisitor
    The visitor instance handling the node.
  • methodContributeToFingerprint
    public void ContributeToFingerprint(IQueryFingerprinter fingerprinter)

    Contributes the structure of this node to a deterministic cryptographic fingerprint. Values and parameter arguments are ignored to ensure the fingerprint only reflects the AST shape.

    fingerprinter: IQueryFingerprinter
    The fingerprinter instance.
  • methodDeconstruct
    public void Deconstruct(out int? limit, out int? offset)

    Deconstructs the node into its limit and offset components.

    limit: out int?
    When returning, contains the maximum number of rows to return, or `null` if none.
    offset: out int?
    When returning, contains the number of rows to skip, or `null` if none.
  • propertyLimit
    public int? Limit { get; init; }

    Gets the maximum number of rows to return. `null` means no limit is applied.

  • propertyOffset
    public int? Offset { get; init; }

    Gets the number of rows to skip before beginning to return rows. `null` means no offset is applied.

enum

MaterializationHint

Assembly: EricksonLopez.SqlBuilder.Abstractions
public enum MaterializationHint

Specifies the materialization behavior of a Common Table Expression (CTE) in supporting dialects (e.g. PostgreSQL 12+).

Members (3)

  • fieldDefault
    Default = 0

    Default materialization behavior determined by the SQL query planner.

  • fieldMaterialized
    Materialized = 1

    Forces the CTE to be materialized as a temporary physical table (MATERIALIZED).

  • fieldNotMaterialized
    NotMaterialized = 2

    Forces the CTE to be inlined into the outer query where possible (NOT MATERIALIZED).

enum

NullsPosition

Assembly: EricksonLopez.SqlBuilder.Abstractions
public enum NullsPosition

Controls the placement of NULL values within an ORDER BY clause.

Members (3)

  • fieldFirst
    First

    Place NULL values before non-NULL values (NULLS FIRST).

  • fieldLast
    Last

    Place NULL values after non-NULL values (NULLS LAST).

  • fieldNone
    None

    Use the database default (no explicit NULLS clause).

record

OnConflictNode

Assembly: EricksonLopez.SqlBuilder.Abstractions
public sealed record OnConflictNode(string[] TargetColumns, string? UpdateAction, Expression? UpdateExpression, object?[]? Parameters) : ISqlNode
Implements: ISqlNode

Represents an ON CONFLICT clause that governs upsert operations.

Members (6)

  • constructorOnConflictNode
    public OnConflictNode(string[] TargetColumns, string? UpdateAction = null, Expression? UpdateExpression = null, object?[]? Parameters = null)

    Initializes a new instance of OnConflictNode.

    TargetColumns: string[]
    The columns that form the conflict target constraint or index.
    UpdateAction: string?
    The optional raw DO UPDATE SET SQL clause.
    UpdateExpression: Expression?
    The optional LINQ expression specifying update assignments.
    Parameters: object?[]?
    Optional parameters referenced in the conflict resolution clause.
  • methodAccept
    public void Accept(ISqlVisitor visitor)

    Accepts a visitor to perform double-dispatch traversal of the AST.

    visitor: ISqlVisitor
    The visitor instance handling the node.
  • propertyParameters
    public object?[]? Parameters { get; init; }

    Optional parameters referenced in the conflict resolution clause.

  • propertyTargetColumns
    public string[] TargetColumns { get; init; }

    The columns that form the conflict target constraint or index.

  • propertyUpdateAction
    public string? UpdateAction { get; init; }

    The optional raw DO UPDATE SET SQL clause.

  • propertyUpdateExpression
    public Expression? UpdateExpression { get; init; }

    The optional LINQ expression specifying update assignments.

record

OrderByNode

Assembly: EricksonLopez.SqlBuilder.Abstractions
public record OrderByNode(Expression KeySelector, bool IsDescending, NullsPosition Nulls) : ISqlNode
Implements: ISqlNode

Represents a primary ORDER BY sorting clause based on a LINQ expression.

Members (6)

  • constructorOrderByNode
    public OrderByNode(Expression KeySelector, bool IsDescending = false, NullsPosition Nulls = NullsPosition.None)

    Initializes a new instance of OrderByNode.

    KeySelector: Expression
    The LINQ expression identifying the sort key member.
    IsDescending: bool
    If `true`, sorts in descending order; otherwise ascending.
    Nulls: NullsPosition
    Specifies the null ordering strategy.
  • methodAccept
    public virtual void Accept(ISqlVisitor visitor)

    Accepts a visitor to perform double-dispatch traversal of the AST.

    visitor: ISqlVisitor
    The visitor instance handling the node.
  • methodContributeToFingerprint
    public virtual void ContributeToFingerprint(IQueryFingerprinter fingerprinter)

    Contributes the structure of this node to a deterministic cryptographic fingerprint. Values and parameter arguments are ignored to ensure the fingerprint only reflects the AST shape.

    fingerprinter: IQueryFingerprinter
    The fingerprinter instance.
  • propertyIsDescending
    public bool IsDescending { get; init; }

    If `true`, sorts in descending order; otherwise ascending.

  • propertyKeySelector
    public Expression KeySelector { get; init; }

    The LINQ expression identifying the sort key member.

  • propertyNulls
    public NullsPosition Nulls { get; init; }

    Specifies the null ordering strategy.

record

QueryAliasNode

Assembly: EricksonLopez.SqlBuilder.Abstractions
public sealed record QueryAliasNode(string Alias) : ISqlNode
Implements: ISqlNode

Represents an alias assigned to the overall query.

Members (4)

  • constructorQueryAliasNode
    public QueryAliasNode(string Alias)

    Initializes a new instance of QueryAliasNode.

    Alias: string
    The table or query alias name.
  • methodAccept
    public void Accept(ISqlVisitor visitor)

    Accepts a visitor to perform double-dispatch traversal of the AST.

    visitor: ISqlVisitor
    The visitor instance handling the node.
  • methodContributeToFingerprint
    public void ContributeToFingerprint(IQueryFingerprinter fingerprinter)

    Contributes the structure of this node to a deterministic cryptographic fingerprint. Values and parameter arguments are ignored to ensure the fingerprint only reflects the AST shape.

    fingerprinter: IQueryFingerprinter
    The fingerprinter instance.
  • propertyAlias
    public string Alias { get; init; }

    The table or query alias name.

record

RawHavingNode

Assembly: EricksonLopez.SqlBuilder.Abstractions
public sealed record RawHavingNode(string Condition, object?[]? Parameters, bool IsOr) : ISqlNode
Implements: ISqlNode

Represents a raw SQL HAVING clause.

Members (6)

  • constructorRawHavingNode
    public RawHavingNode(string Condition, object?[]? Parameters = null, bool IsOr = false)

    Initializes a new instance of RawHavingNode.

    Condition: string
    The raw SQL HAVING condition. Supports `{0}` parameter placeholders.
    Parameters: object?[]?
    Optional parameters referenced by `Condition`.
    IsOr: bool
    If `true`, combines this condition with OR; otherwise combines with AND.
  • methodAccept
    public void Accept(ISqlVisitor visitor)

    Accepts a visitor to perform double-dispatch traversal of the AST.

    visitor: ISqlVisitor
    The visitor instance handling the node.
  • methodContributeToFingerprint
    public void ContributeToFingerprint(IQueryFingerprinter fingerprinter)

    Contributes the structure of this node to a deterministic cryptographic fingerprint. Values and parameter arguments are ignored to ensure the fingerprint only reflects the AST shape.

    fingerprinter: IQueryFingerprinter
    The fingerprinter instance.
  • propertyCondition
    public string Condition { get; init; }

    The raw SQL HAVING condition. Supports `{0}` parameter placeholders.

  • propertyIsOr
    public bool IsOr { get; init; }

    If `true`, combines this condition with OR; otherwise combines with AND.

  • propertyParameters
    public object?[]? Parameters { get; init; }

    Optional parameters referenced by `Condition`.

record

RawJoinNode

Assembly: EricksonLopez.SqlBuilder.Abstractions
public sealed record RawJoinNode(string JoinSql, object?[]? Parameters) : ISqlNode
Implements: ISqlNode

Represents a completely raw JOIN clause.

Members (5)

  • constructorRawJoinNode
    public RawJoinNode(string JoinSql, object?[]? Parameters = null)

    Initializes a new instance of RawJoinNode.

    JoinSql: string
    The raw SQL string.
    Parameters: object?[]?
    Optional parameters.
  • methodAccept
    public void Accept(ISqlVisitor visitor)

    Accepts a visitor to perform double-dispatch traversal of the AST.

    visitor: ISqlVisitor
    The visitor instance handling the node.
  • methodContributeToFingerprint
    public void ContributeToFingerprint(IQueryFingerprinter fingerprinter)

    Contributes the structure of this node to a deterministic cryptographic fingerprint. Values and parameter arguments are ignored to ensure the fingerprint only reflects the AST shape.

    fingerprinter: IQueryFingerprinter
    The fingerprinter instance.
  • propertyJoinSql
    public string JoinSql { get; init; }

    The raw SQL string.

  • propertyParameters
    public object?[]? Parameters { get; init; }

    Optional parameters.

record

RawOrderByNode

Assembly: EricksonLopez.SqlBuilder.Abstractions
public sealed record RawOrderByNode(string Condition, bool IsDescending, object?[]? Parameters) : ISqlNode
Implements: ISqlNode

Represents a raw SQL ORDER BY sorting clause.

Members (6)

  • constructorRawOrderByNode
    public RawOrderByNode(string Condition, bool IsDescending = false, object?[]? Parameters = null)

    Initializes a new instance of RawOrderByNode.

    Condition: string
    The raw SQL ORDER BY expression.
    IsDescending: bool
    If `true`, sorts in descending order; otherwise ascending.
    Parameters: object?[]?
    Optional parameters referenced by `Condition`.
  • methodAccept
    public void Accept(ISqlVisitor visitor)

    Accepts a visitor to perform double-dispatch traversal of the AST.

    visitor: ISqlVisitor
    The visitor instance handling the node.
  • methodContributeToFingerprint
    public void ContributeToFingerprint(IQueryFingerprinter fingerprinter)

    Contributes the structure of this node to a deterministic cryptographic fingerprint. Values and parameter arguments are ignored to ensure the fingerprint only reflects the AST shape.

    fingerprinter: IQueryFingerprinter
    The fingerprinter instance.
  • propertyCondition
    public string Condition { get; init; }

    The raw SQL ORDER BY expression.

  • propertyIsDescending
    public bool IsDescending { get; init; }

    If `true`, sorts in descending order; otherwise ascending.

  • propertyParameters
    public object?[]? Parameters { get; init; }

    Optional parameters referenced by `Condition`.

record

RawSelectNode

Assembly: EricksonLopez.SqlBuilder.Abstractions
public sealed record RawSelectNode(string RawSql, object?[]? Parameters, bool IsDistinct) : ISqlNode
Implements: ISqlNode

Represents a raw SQL SELECT clause.

Members (6)

  • constructorRawSelectNode
    public RawSelectNode(string RawSql, object?[]? Parameters, bool IsDistinct)

    Initializes a new instance of RawSelectNode.

    RawSql: string
    The raw SQL projection string.
    Parameters: object?[]?
    Optional parameters referenced by `RawSql`.
    IsDistinct: bool
    If `true`, emits the DISTINCT keyword.
  • methodAccept
    public void Accept(ISqlVisitor visitor)

    Accepts a visitor to perform double-dispatch traversal of the AST.

    visitor: ISqlVisitor
    The visitor instance handling the node.
  • methodContributeToFingerprint
    public void ContributeToFingerprint(IQueryFingerprinter fingerprinter)

    Contributes the structure of this node to a deterministic cryptographic fingerprint. Values and parameter arguments are ignored to ensure the fingerprint only reflects the AST shape.

    fingerprinter: IQueryFingerprinter
    The fingerprinter instance.
  • propertyIsDistinct
    public bool IsDistinct { get; init; }

    If `true`, emits the DISTINCT keyword.

  • propertyParameters
    public object?[]? Parameters { get; init; }

    Optional parameters referenced by `RawSql`.

  • propertyRawSql
    public string RawSql { get; init; }

    The raw SQL projection string.

record

RawWhereNode

Assembly: EricksonLopez.SqlBuilder.Abstractions
public sealed record RawWhereNode(string Condition, object?[]? Parameters, bool IsOr) : ISqlNode
Implements: ISqlNode

Represents a raw SQL WHERE condition.

Members (6)

  • constructorRawWhereNode
    public RawWhereNode(string Condition, object?[]? Parameters = null, bool IsOr = false)

    Initializes a new instance of RawWhereNode.

    Condition: string
    The raw SQL condition string. Supports `{0}` parameter placeholders.
    Parameters: object?[]?
    Optional parameters referenced by `Condition`.
    IsOr: bool
    If `true`, combines this condition with OR; otherwise combines with AND.
  • methodAccept
    public void Accept(ISqlVisitor visitor)

    Accepts a visitor to perform double-dispatch traversal of the AST.

    visitor: ISqlVisitor
    The visitor instance handling the node.
  • methodContributeToFingerprint
    public void ContributeToFingerprint(IQueryFingerprinter fingerprinter)

    Contributes the structure of this node to a deterministic cryptographic fingerprint. Values and parameter arguments are ignored to ensure the fingerprint only reflects the AST shape.

    fingerprinter: IQueryFingerprinter
    The fingerprinter instance.
  • propertyCondition
    public string Condition { get; init; }

    The raw SQL condition string. Supports `{0}` parameter placeholders.

  • propertyIsOr
    public bool IsOr { get; init; }

    If `true`, combines this condition with OR; otherwise combines with AND.

  • propertyParameters
    public object?[]? Parameters { get; init; }

    Optional parameters referenced by `Condition`.

record

ReturningNode

Assembly: EricksonLopez.SqlBuilder.Abstractions
public sealed record ReturningNode(string[] Columns) : ISqlNode
Implements: ISqlNode

Represents a RETURNING clause used to retrieve column values from mutated rows.

Members (4)

  • constructorReturningNode
    public ReturningNode(string[] Columns)

    Initializes a new instance of ReturningNode.

    Columns: string[]
    The names of the columns to return.
  • methodAccept
    public void Accept(ISqlVisitor visitor)

    Accepts a visitor to perform double-dispatch traversal of the AST.

    visitor: ISqlVisitor
    The visitor instance handling the node.
  • methodContributeToFingerprint
    public void ContributeToFingerprint(IQueryFingerprinter fingerprinter)

    Contributes the structure of this node to a deterministic cryptographic fingerprint. Values and parameter arguments are ignored to ensure the fingerprint only reflects the AST shape.

    fingerprinter: IQueryFingerprinter
    The fingerprinter instance.
  • propertyColumns
    public string[] Columns { get; init; }

    The names of the columns to return.

record

ScalarSubquerySelectNode

Assembly: EricksonLopez.SqlBuilder.Abstractions
public sealed record ScalarSubquerySelectNode(ISqlQuery Subquery, string Alias) : ISqlNode
Implements: ISqlNode

Represents a scalar subquery projection in the SELECT clause (e.g. (SELECT COUNT(*) FROM ...) AS alias).

Members (5)

  • constructorScalarSubquerySelectNode
    public ScalarSubquerySelectNode(ISqlQuery Subquery, string Alias)

    Initializes a new instance of ScalarSubquerySelectNode.

    Subquery: ISqlQuery
    The subquery that computes the scalar value.
    Alias: string
    The column alias assigned to the scalar result.
  • methodAccept
    public void Accept(ISqlVisitor visitor)

    Accepts a visitor to perform double-dispatch traversal of the AST.

    visitor: ISqlVisitor
    The visitor instance handling the node.
  • methodContributeToFingerprint
    public void ContributeToFingerprint(IQueryFingerprinter fingerprinter)

    Contributes the structure of this node to a deterministic cryptographic fingerprint. Values and parameter arguments are ignored to ensure the fingerprint only reflects the AST shape.

    fingerprinter: IQueryFingerprinter
    The fingerprinter instance.
  • propertyAlias
    public string Alias { get; init; }

    The column alias assigned to the scalar result.

  • propertySubquery
    public ISqlQuery Subquery { get; init; }

    The subquery that computes the scalar value.

record

SelectNode

Assembly: EricksonLopez.SqlBuilder.Abstractions
public sealed record SelectNode(string[] Columns, bool IsDistinct) : ISqlNode
Implements: ISqlNode

Represents a standard SELECT clause specifying one or more column names.

Members (5)

  • constructorSelectNode
    public SelectNode(string[] Columns, bool IsDistinct)

    Initializes a new instance of SelectNode.

    Columns: string[]
    The column names to project.
    IsDistinct: bool
    If `true`, emits the DISTINCT keyword.
  • methodAccept
    public void Accept(ISqlVisitor visitor)

    Accepts a visitor to perform double-dispatch traversal of the AST.

    visitor: ISqlVisitor
    The visitor instance handling the node.
  • methodContributeToFingerprint
    public void ContributeToFingerprint(IQueryFingerprinter fingerprinter)

    Contributes the structure of this node to a deterministic cryptographic fingerprint. Values and parameter arguments are ignored to ensure the fingerprint only reflects the AST shape.

    fingerprinter: IQueryFingerprinter
    The fingerprinter instance.
  • propertyColumns
    public string[] Columns { get; init; }

    The column names to project.

  • propertyIsDistinct
    public bool IsDistinct { get; init; }

    If `true`, emits the DISTINCT keyword.

record

SetNode

Assembly: EricksonLopez.SqlBuilder.Abstractions
public sealed record SetNode(string? Column, object? Value, string? RawExpression, object?[]? Parameters) : ISqlNode
Implements: ISqlNode

Represents a single column assignment in a SET clause of an UPDATE statement.

Members (7)

  • constructorSetNode
    public SetNode(string? Column, object? Value, string? RawExpression = null, object?[]? Parameters = null)

    Initializes a new instance of SetNode.

    Column: string?
    The name of the column to assign. Mutually exclusive with `RawExpression`.
    Value: object?
    The value to assign to the column when `Column` is specified.
    RawExpression: string?
    An optional raw SQL expression used instead of a named column and value (e.g., `"col = col + 1"`).
    Parameters: object?[]?
    Optional parameters referenced by `RawExpression`.
  • methodAccept
    public void Accept(ISqlVisitor visitor)

    Accepts a visitor to perform double-dispatch traversal of the AST.

    visitor: ISqlVisitor
    The visitor instance handling the node.
  • methodContributeToFingerprint
    public void ContributeToFingerprint(IQueryFingerprinter fingerprinter)

    Contributes the structure of this node to a deterministic cryptographic fingerprint. Values and parameter arguments are ignored to ensure the fingerprint only reflects the AST shape.

    fingerprinter: IQueryFingerprinter
    The fingerprinter instance.
  • propertyColumn
    public string? Column { get; init; }

    The name of the column to assign. Mutually exclusive with `RawExpression`.

  • propertyParameters
    public object?[]? Parameters { get; init; }

    Optional parameters referenced by `RawExpression`.

  • propertyRawExpression
    public string? RawExpression { get; init; }

    An optional raw SQL expression used instead of a named column and value (e.g., `"col = col + 1"`).

  • propertyValue
    public object? Value { get; init; }

    The value to assign to the column when `Column` is specified.

record

SetOperationNode

Assembly: EricksonLopez.SqlBuilder.Abstractions
public sealed record SetOperationNode(string Operation, ISqlQuery Query) : ISqlNode
Implements: ISqlNode

Represents a set operation (e.g., UNION, INTERSECT, EXCEPT) combining two queries.

Members (4)

  • constructorSetOperationNode
    public SetOperationNode(string Operation, ISqlQuery Query)

    Initializes a new instance of SetOperationNode.

    Operation: string
    The SQL set operator keyword (e.g., `"UNION"`, `"UNION ALL"`, `"INTERSECT"`, `"EXCEPT"`).
    Query: ISqlQuery
    The right-hand query to combine with the main query using the set operation.
  • methodAccept
    public void Accept(ISqlVisitor visitor)

    Accepts a visitor to perform double-dispatch traversal of the AST.

    visitor: ISqlVisitor
    The visitor instance handling the node.
  • propertyOperation
    public string Operation { get; init; }

    The SQL set operator keyword (e.g., `"UNION"`, `"UNION ALL"`, `"INTERSECT"`, `"EXCEPT"`).

  • propertyQuery
    public ISqlQuery Query { get; init; }

    The right-hand query to combine with the main query using the set operation.

record

SqlExtensionNode

Assembly: EricksonLopez.SqlBuilder.Abstractions
public abstract record SqlExtensionNode : ISqlNode
Implements: ISqlNode

Serves as the base class for dialect-specific or custom AST nodes, allowing extensions beyond the core SQL standard.

Members (1)

  • methodAccept
    public abstract void Accept(ISqlVisitor visitor)

    Accepts a visitor to perform double-dispatch traversal of the AST.

    visitor: ISqlVisitor
    The visitor instance handling the node.
record

SubqueryFromNode

Assembly: EricksonLopez.SqlBuilder.Abstractions
public sealed record SubqueryFromNode(ISqlQuery Query, string Alias) : ISqlNode
Implements: ISqlNode

Represents a FROM clause containing a subquery.

Members (5)

  • constructorSubqueryFromNode
    public SubqueryFromNode(ISqlQuery Query, string Alias)

    Initializes a new instance of SubqueryFromNode.

    Query: ISqlQuery
    The subquery used as the FROM data source.
    Alias: string
    The alias assigned to the subquery.
  • methodAccept
    public void Accept(ISqlVisitor visitor)

    Accepts a visitor to perform double-dispatch traversal of the AST.

    visitor: ISqlVisitor
    The visitor instance handling the node.
  • methodContributeToFingerprint
    public void ContributeToFingerprint(IQueryFingerprinter fingerprinter)

    Contributes the structure of this node to a deterministic cryptographic fingerprint. Values and parameter arguments are ignored to ensure the fingerprint only reflects the AST shape.

    fingerprinter: IQueryFingerprinter
    The fingerprinter instance.
  • propertyAlias
    public string Alias { get; init; }

    The alias assigned to the subquery.

  • propertyQuery
    public ISqlQuery Query { get; init; }

    The subquery used as the FROM data source.

record

SubqueryJoinNode

Assembly: EricksonLopez.SqlBuilder.Abstractions
public sealed record SubqueryJoinNode(JoinType Type, IAstQuery Subquery, string Alias, string? OnCondition, bool IsLateral, Expression? ExpressionCondition) : ISqlNode
Implements: ISqlNode

Represents a subquery JOIN clause.

Members (9)

  • constructorSubqueryJoinNode
    public SubqueryJoinNode(JoinType Type, IAstQuery Subquery, string Alias, string? OnCondition = null, bool IsLateral = false, Expression? ExpressionCondition = null)

    Initializes a new instance of SubqueryJoinNode.

    Type: JoinType
    The join type.
    Subquery: IAstQuery
    The subquery AST.
    Alias: string
    The table alias.
    OnCondition: string?
    The raw ON condition.
    IsLateral: bool
    Whether this is a LATERAL join.
    ExpressionCondition: Expression?
    Optional typed ON expression condition.
  • methodAccept
    public void Accept(ISqlVisitor visitor)

    Accepts a visitor to perform double-dispatch traversal of the AST.

    visitor: ISqlVisitor
    The visitor instance handling the node.
  • methodContributeToFingerprint
    public void ContributeToFingerprint(IQueryFingerprinter fingerprinter)

    Contributes the structure of this node to a deterministic cryptographic fingerprint. Values and parameter arguments are ignored to ensure the fingerprint only reflects the AST shape.

    fingerprinter: IQueryFingerprinter
    The fingerprinter instance.
  • propertyAlias
    public string Alias { get; init; }

    The table alias.

  • propertyExpressionCondition
    public Expression? ExpressionCondition { get; init; }

    Optional typed ON expression condition.

  • propertyIsLateral
    public bool IsLateral { get; init; }

    Whether this is a LATERAL join.

  • propertyOnCondition
    public string? OnCondition { get; init; }

    The raw ON condition.

  • propertySubquery
    public IAstQuery Subquery { get; init; }

    The subquery AST.

  • propertyType
    public JoinType Type { get; init; }

    The join type.

record

ThenByNode

Assembly: EricksonLopez.SqlBuilder.Abstractions
public sealed record ThenByNode(Expression KeySelector, bool IsDescending, NullsPosition Nulls) : OrderByNode
Inherits: OrderByNode

Represents a secondary (or subsequent) sorting clause, typically matching a THEN BY operation.

Members (6)

  • constructorThenByNode
    public ThenByNode(Expression KeySelector, bool IsDescending = false, NullsPosition Nulls = NullsPosition.None)

    Initializes a new instance of ThenByNode.

    KeySelector: Expression
    The LINQ expression identifying the secondary sort key member.
    IsDescending: bool
    If `true`, sorts in descending order; otherwise ascending.
    Nulls: NullsPosition
    Specifies the null ordering strategy.
  • methodAccept
    public override void Accept(ISqlVisitor visitor)

    Accepts a visitor to perform double-dispatch traversal of the AST.

    visitor: ISqlVisitor
    The visitor instance handling the node.
  • methodContributeToFingerprint
    public override void ContributeToFingerprint(IQueryFingerprinter fingerprinter)

    Contributes the structure of this node to a deterministic cryptographic fingerprint. Values and parameter arguments are ignored to ensure the fingerprint only reflects the AST shape.

    fingerprinter: IQueryFingerprinter
    The fingerprinter instance.
  • propertyIsDescending
    public bool IsDescending { get; init; }

    If `true`, sorts in descending order; otherwise ascending.

  • propertyKeySelector
    public Expression KeySelector { get; init; }

    The LINQ expression identifying the secondary sort key member.

  • propertyNulls
    public NullsPosition Nulls { get; init; }

    Specifies the null ordering strategy.

record

UnnestNode

Assembly: EricksonLopez.SqlBuilder.Abstractions
public sealed record UnnestNode(object[] Arrays, string Alias) : ISqlNode
Implements: ISqlNode

Represents a FROM clause that unnests an array (common in PostgreSQL).

Members (5)

  • constructorUnnestNode
    public UnnestNode(object[] Arrays, string Alias)

    Initializes a new instance of UnnestNode.

    Arrays: object[]
    The array objects to expand with UNNEST.
    Alias: string
    The alias assigned to the expanded table.
  • methodAccept
    public void Accept(ISqlVisitor visitor)

    Accepts a visitor to perform double-dispatch traversal of the AST.

    visitor: ISqlVisitor
    The visitor instance handling the node.
  • methodContributeToFingerprint
    public void ContributeToFingerprint(IQueryFingerprinter fingerprinter)

    Contributes the structure of this node to a deterministic cryptographic fingerprint. Values and parameter arguments are ignored to ensure the fingerprint only reflects the AST shape.

    fingerprinter: IQueryFingerprinter
    The fingerprinter instance.
  • propertyAlias
    public string Alias { get; init; }

    The alias assigned to the expanded table.

  • propertyArrays
    public object[] Arrays { get; init; }

    The array objects to expand with UNNEST.

record

UpdateNode

Assembly: EricksonLopez.SqlBuilder.Abstractions
public sealed record UpdateNode(string TableName) : ISqlNode
Implements: ISqlNode

Represents the target table clause of an UPDATE statement.

Members (4)

  • constructorUpdateNode
    public UpdateNode(string TableName)

    Initializes a new instance of UpdateNode.

    TableName: string
    The name of the table to update.
  • methodAccept
    public void Accept(ISqlVisitor visitor)

    Accepts a visitor to perform double-dispatch traversal of the AST.

    visitor: ISqlVisitor
    The visitor instance handling the node.
  • methodContributeToFingerprint
    public void ContributeToFingerprint(IQueryFingerprinter fingerprinter)

    Contributes the structure of this node to a deterministic cryptographic fingerprint. Values and parameter arguments are ignored to ensure the fingerprint only reflects the AST shape.

    fingerprinter: IQueryFingerprinter
    The fingerprinter instance.
  • propertyTableName
    public string TableName { get; init; }

    The name of the table to update.

record

ValuesNode

Assembly: EricksonLopez.SqlBuilder.Abstractions
public sealed record ValuesNode(IReadOnlyList<IReadOnlyList<object?>> ValuesSets) : ISqlNode
Implements: ISqlNode

Represents the VALUES clause of an INSERT statement containing multiple sets of values.

Members (3)

  • constructorValuesNode
    public ValuesNode(IReadOnlyList<IReadOnlyList<object?>> ValuesSets)

    Initializes a new instance of ValuesNode.

    ValuesSets: IReadOnlyList<IReadOnlyList<object?>>
    The nested collections of row value sets to insert.
  • methodAccept
    public void Accept(ISqlVisitor visitor)

    Accepts a visitor to perform double-dispatch traversal of the AST.

    visitor: ISqlVisitor
    The visitor instance handling the node.
  • propertyValuesSets
    public IReadOnlyList<IReadOnlyList<object?>> ValuesSets { get; init; }

    The nested collections of row value sets to insert.

record

WindowFunctionNode

Assembly: EricksonLopez.SqlBuilder.Abstractions
public sealed record WindowFunctionNode(string FunctionName, string? ColumnName, int? Offset, object? DefaultValue, string[] PartitionByColumns, string[] OrderByColumns, bool[] OrderByDescending, string Alias, System.Linq.Expressions.Expression? FilterExpression, string? FilterRaw, object?[]? FilterRawArgs) : ISqlNode
Implements: ISqlNode

Represents a window function expression in a SELECT clause (inline OVER clause).

Remarks:

Generates SQL conforming to: `FUNC([Column]) OVER (PARTITION BY col1, col2 ORDER BY col3 DESC) AS alias`.

Members (13)

  • constructorWindowFunctionNode
    public WindowFunctionNode(string FunctionName, string? ColumnName, int? Offset, object? DefaultValue, string[] PartitionByColumns, string[] OrderByColumns, bool[] OrderByDescending, string Alias, System.Linq.Expressions.Expression? FilterExpression = null, string? FilterRaw = null, object?[]? FilterRawArgs = null)

    Initializes a new instance of WindowFunctionNode.

    FunctionName: string
    The SQL window function name. Examples: ROW_NUMBER, RANK, DENSE_RANK, LAG, LEAD, SUM, AVG, COUNT, MIN, MAX.
    ColumnName: string?
    Optional column argument. `null` for functions that take no argument (ROW_NUMBER, RANK, DENSE_RANK, COUNT(*)).
    Offset: int?
    Optional numeric offset argument for LAG/LEAD.
    DefaultValue: object?
    Optional default value for LAG/LEAD when the offset goes out of range.
    PartitionByColumns: string[]
    Columns for the PARTITION BY clause. Empty means no PARTITION BY.
    OrderByColumns: string[]
    Column names for the ORDER BY clause inside OVER. Empty means no ORDER BY.
    OrderByDescending: bool[]
    Parallel array to `OrderByColumns`. `true` = DESC.
    Alias: string
    The AS alias for this expression in the SELECT list.
    FilterExpression: System.Linq.Expressions.Expression?
    Optional LINQ predicate for the FILTER (WHERE ...) clause.
    FilterRaw: string?
    Optional raw SQL condition for the FILTER (WHERE ...) clause.
    FilterRawArgs: object?[]?
    Optional arguments for `FilterRaw`.
  • methodAccept
    public void Accept(ISqlVisitor visitor)

    Accepts a visitor to perform double-dispatch traversal of the AST.

    visitor: ISqlVisitor
    The visitor instance handling the node.
  • propertyAlias
    public string Alias { get; init; }

    The AS alias for this expression in the SELECT list.

  • propertyColumnName
    public string? ColumnName { get; init; }

    Optional column argument. `null` for functions that take no argument (ROW_NUMBER, RANK, DENSE_RANK, COUNT(*)).

  • propertyDefaultValue
    public object? DefaultValue { get; init; }

    Optional default value for LAG/LEAD when the offset goes out of range.

  • propertyFilterExpression
    public System.Linq.Expressions.Expression? FilterExpression { get; init; }

    Optional LINQ predicate for the FILTER (WHERE ...) clause.

  • propertyFilterRaw
    public string? FilterRaw { get; init; }

    Optional raw SQL condition for the FILTER (WHERE ...) clause.

  • propertyFilterRawArgs
    public object?[]? FilterRawArgs { get; init; }

    Optional arguments for `FilterRaw`.

  • propertyFunctionName
    public string FunctionName { get; init; }

    The SQL window function name. Examples: ROW_NUMBER, RANK, DENSE_RANK, LAG, LEAD, SUM, AVG, COUNT, MIN, MAX.

  • propertyOffset
    public int? Offset { get; init; }

    Optional numeric offset argument for LAG/LEAD.

  • propertyOrderByColumns
    public string[] OrderByColumns { get; init; }

    Column names for the ORDER BY clause inside OVER. Empty means no ORDER BY.

  • propertyOrderByDescending
    public bool[] OrderByDescending { get; init; }

    Parallel array to `OrderByColumns`. `true` = DESC.

  • propertyPartitionByColumns
    public string[] PartitionByColumns { get; init; }

    Columns for the PARTITION BY clause. Empty means no PARTITION BY.

record

WindowNode

Assembly: EricksonLopez.SqlBuilder.Abstractions
public sealed record WindowNode(string Name, string[]? PartitionBy, string[]? OrderBy) : ISqlNode
Implements: ISqlNode

Represents a WINDOW clause in a SQL query.

Members (5)

  • constructorWindowNode
    public WindowNode(string Name, string[]? PartitionBy, string[]? OrderBy)

    Initializes a new instance of WindowNode.

    Name: string
    The window name.
    PartitionBy: string[]?
    An array of columns to partition by.
    OrderBy: string[]?
    An array of columns to order by (optionally containing ASC/DESC suffixes).
  • methodAccept
    public void Accept(ISqlVisitor visitor)

    Accepts a visitor to perform double-dispatch traversal of the AST.

    visitor: ISqlVisitor
    The visitor instance handling the node.
  • propertyName
    public string Name { get; init; }

    The window name.

  • propertyOrderBy
    public string[]? OrderBy { get; init; }

    An array of columns to order by (optionally containing ASC/DESC suffixes).

  • propertyPartitionBy
    public string[]? PartitionBy { get; init; }

    An array of columns to partition by.

record

WindowPageNode

Assembly: EricksonLopez.SqlBuilder.Abstractions
public sealed record WindowPageNode(int PageNumber, int PageSize, string OrderByColumn, bool Descending) : ISqlNode
Implements: ISqlNode

Represents a specialized node that uses window functions to perform offset-based pagination.

Members (6)

  • constructorWindowPageNode
    public WindowPageNode(int PageNumber, int PageSize, string OrderByColumn, bool Descending)

    Initializes a new instance of WindowPageNode.

    PageNumber: int
    The 1-based page number.
    PageSize: int
    The maximum number of rows per page.
    OrderByColumn: string
    The column used to determine the sort order for pagination.
    Descending: bool
    If `true`, sorts in descending order; otherwise ascending.
  • methodAccept
    public void Accept(ISqlVisitor visitor)

    Accepts a visitor to perform double-dispatch traversal of the AST.

    visitor: ISqlVisitor
    The visitor instance handling the node.
  • propertyDescending
    public bool Descending { get; init; }

    If `true`, sorts in descending order; otherwise ascending.

  • propertyOrderByColumn
    public string OrderByColumn { get; init; }

    The column used to determine the sort order for pagination.

  • propertyPageNumber
    public int PageNumber { get; init; }

    The 1-based page number.

  • propertyPageSize
    public int PageSize { get; init; }

    The maximum number of rows per page.

EricksonLopez.SqlBuilder.Analyzers#

27
class

BatchSizeExceedsMaxAnalyzer

Assembly: EricksonLopez.SqlBuilder.Analyzers
public class BatchSizeExceedsMaxAnalyzer : DiagnosticAnalyzer
Inherits: DiagnosticAnalyzer

Detects when `.WithBatchSize(n)` is called with a value that exceeds the known maximum for the target database provider (ELSB006).

Remarks:

SQL Server limits the total number of parameters to 2100 per statement. For a table with N columns, the safe maximum batch size is floor(2100 / N). Other providers have different limits: - SQL Server: 2100 parameters total - MySQL/MariaDB: 65535 parameters total - PostgreSQL: 65535 parameters total - SQLite: 999 parameters total (default, configurable) This analyzer flags statically-detectable violations. Dynamic batch sizes require a runtime guard.

Members (3)

  • methodInitialize
    public override void Initialize(AnalysisContext context)

    Inherits documentation from base type or interface.

    context: AnalysisContext
  • propertySupportedDiagnostics
    public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics { get; }

    Inherits documentation from base type or interface.

  • fieldDiagnosticId
    public const string DiagnosticId

    Represents the diagnostic identifier for ELSB006.

class

CartesianJoinAnalyzer

Assembly: EricksonLopez.SqlBuilder.Analyzers
public class CartesianJoinAnalyzer : DiagnosticAnalyzer
Inherits: DiagnosticAnalyzer

Detects join clauses that are missing an ON condition, which would produce a Cartesian product.

Remarks:

Emits diagnostic `ESQL024` when a `RawJoin` call or a strongly-typed join method receives an empty or whitespace ON clause. CROSS JOIN patterns are intentionally excluded.

Members (3)

  • methodInitialize
    public override void Initialize(AnalysisContext context)

    Inherits documentation from base type or interface.

    context: AnalysisContext
  • propertySupportedDiagnostics
    public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics { get; }

    Inherits documentation from base type or interface.

  • fieldDiagnosticId
    public const string DiagnosticId

    Gets the diagnostic identifier emitted by this analyzer.

class

DapperCompilerAnalyzer

Assembly: EricksonLopez.SqlBuilder.Analyzers
public class DapperCompilerAnalyzer : DiagnosticAnalyzer
Inherits: DiagnosticAnalyzer

Analyzes invocations of Dapper extensions to ensure a compiler is registered.

Members (3)

  • methodInitialize
    public override void Initialize(AnalysisContext context)

    Inherits documentation from base type or interface.

    context: AnalysisContext
  • propertySupportedDiagnostics
    public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics { get; }

    Inherits documentation from base type or interface.

  • fieldDiagnosticId
    public const string DiagnosticId

    Gets the diagnostic identifier emitted when a Dapper execution call uses a compiler that has not been registered.

class

DeleteWithoutWhereAnalyzer

Assembly: EricksonLopez.SqlBuilder.Analyzers
public class DeleteWithoutWhereAnalyzer : DiagnosticAnalyzer
Inherits: DiagnosticAnalyzer

Analyzes DELETE statements to ensure they have a WHERE clause (ESQL001). Analyzes UPDATE statements to ensure they have a WHERE clause (ESQL003).

Members (4)

  • methodInitialize
    public override void Initialize(AnalysisContext context)

    Inherits documentation from base type or interface.

    context: AnalysisContext
  • propertySupportedDiagnostics
    public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics { get; }

    Inherits documentation from base type or interface.

  • fieldDeleteDiagnosticId
    public const string DeleteDiagnosticId

    Gets the diagnostic identifier emitted when a DELETE query has no WHERE clause.

  • fieldUpdateDiagnosticId
    public const string UpdateDiagnosticId

    Gets the diagnostic identifier emitted when an UPDATE query has no WHERE clause.

class

DeleteWithoutWhereCodeFix

Assembly: EricksonLopez.SqlBuilder.Analyzers
public class DeleteWithoutWhereCodeFix : CodeFixProvider
Inherits: CodeFixProvider

Provides a code fix to append a .Where() clause or acknowledge the unbounded operation.

Members (3)

  • methodGetFixAllProvider
    public sealed override FixAllProvider GetFixAllProvider()

    Inherits documentation from base type or interface.

  • methodRegisterCodeFixesAsync
    public sealed override async Task RegisterCodeFixesAsync(CodeFixContext context)

    Inherits documentation from base type or interface.

    context: CodeFixContext
  • propertyFixableDiagnosticIds
    public sealed override ImmutableArray<string> FixableDiagnosticIds { get; }

    Inherits documentation from base type or interface.

class

DialectSpecificOverloadAnalyzer

Assembly: EricksonLopez.SqlBuilder.Analyzers
public class DialectSpecificOverloadAnalyzer : DiagnosticAnalyzer
Inherits: DiagnosticAnalyzer

Warns when a method decorated with `[RequiresCapability]` is invoked without a compiler known to support the required dialect capability.

Remarks:

Emits diagnostic `ESQL020` as a warning for each call site. A more precise implementation may inspect the `Build` call to determine the actual compiler being used.

Members (3)

  • methodInitialize
    public override void Initialize(AnalysisContext context)

    Inherits documentation from base type or interface.

    context: AnalysisContext
  • propertySupportedDiagnostics
    public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics { get; }

    Inherits documentation from base type or interface.

  • fieldDiagnosticId
    public const string DiagnosticId

    Gets the diagnostic identifier emitted by this analyzer.

class

DynamicIdentifierAnalyzer

Assembly: EricksonLopez.SqlBuilder.Analyzers
public class DynamicIdentifierAnalyzer : DiagnosticAnalyzer
Inherits: DiagnosticAnalyzer

Detects usage of dynamic SQL identifiers (table names, column names) constructed via string concatenation or interpolation without an explicit allowlist, which can lead to SQL injection vulnerabilities (ELSB004).

Remarks:

Safe alternatives: - Use strongly-typed entity models: `Sql.From<T>()` - Validate against an explicit allowlist before passing to `RawJoin`, `OrderBy(FormattableString)`, etc.

Members (3)

  • methodInitialize
    public override void Initialize(AnalysisContext context)

    Inherits documentation from base type or interface.

    context: AnalysisContext
  • propertySupportedDiagnostics
    public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics { get; }

    Inherits documentation from base type or interface.

  • fieldDiagnosticId
    public const string DiagnosticId

    Represents the diagnostic identifier for ELSB004.

class

JoinConditionAnalyzer

Assembly: EricksonLopez.SqlBuilder.Analyzers
public class JoinConditionAnalyzer : DiagnosticAnalyzer
Inherits: DiagnosticAnalyzer

Analyzes JOIN clauses to ensure conditions reference both tables.

Members (3)

  • methodInitialize
    public override void Initialize(AnalysisContext context)

    Inherits documentation from base type or interface.

    context: AnalysisContext
  • propertySupportedDiagnostics
    public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics { get; }

    Inherits documentation from base type or interface.

  • fieldDiagnosticId
    public const string DiagnosticId

    Gets the diagnostic identifier emitted when a JOIN clause is missing its ON condition.

class

LargeOffsetAnalyzer

Assembly: EricksonLopez.SqlBuilder.Analyzers
public class LargeOffsetAnalyzer : DiagnosticAnalyzer
Inherits: DiagnosticAnalyzer

Analyzes queries for large OFFSET values which degrade performance.

Members (3)

  • methodInitialize
    public override void Initialize(AnalysisContext context)

    Inherits documentation from base type or interface.

    context: AnalysisContext
  • propertySupportedDiagnostics
    public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics { get; }

    Inherits documentation from base type or interface.

  • fieldDiagnosticId
    public const string DiagnosticId

    Gets the diagnostic identifier emitted when a query uses a large OFFSET value that may degrade performance.

class

LikeWildcardAnalyzer

Assembly: EricksonLopez.SqlBuilder.Analyzers
public class LikeWildcardAnalyzer : DiagnosticAnalyzer
Inherits: DiagnosticAnalyzer

Analyzes LIKE queries for missing wildcard characters.

Members (4)

  • methodInitialize
    public override void Initialize(AnalysisContext context)

    Inherits documentation from base type or interface.

    context: AnalysisContext
  • propertySupportedDiagnostics
    public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics { get; }

    Inherits documentation from base type or interface.

  • fieldDiagnosticIdLeadingWildcard
    public const string DiagnosticIdLeadingWildcard

    Gets the diagnostic identifier emitted when LIKE is used with a leading wildcard that prevents index use.

  • fieldDiagnosticIdNoWildcard
    public const string DiagnosticIdNoWildcard

    Gets the diagnostic identifier emitted when LIKE is used without any wildcard character.

class

MergeQueryAnalyzer

Assembly: EricksonLopez.SqlBuilder.Analyzers
public class MergeQueryAnalyzer : DiagnosticAnalyzer
Inherits: DiagnosticAnalyzer

Detects usage of `Sql.Merge<T>()` or `MergeQuery<T>` and warns to use dialect-native `OnConflict()` or `Sql.Raw()` instead (ESQL026 / ADR-025).

Members (3)

  • methodInitialize
    public override void Initialize(AnalysisContext context)

    Inherits documentation from base type or interface.

    context: AnalysisContext
  • propertySupportedDiagnostics
    public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics { get; }

    Inherits documentation from base type or interface.

  • fieldDiagnosticId
    public const string DiagnosticId

    Represents the diagnostic identifier for ESQL026.

class

MissingColumnAnalyzer

Assembly: EricksonLopez.SqlBuilder.Analyzers
public class MissingColumnAnalyzer : DiagnosticAnalyzer
Inherits: DiagnosticAnalyzer

Analyzes queries for missing columns in strongly-typed entities.

Members (3)

  • methodInitialize
    public override void Initialize(AnalysisContext context)

    Inherits documentation from base type or interface.

    context: AnalysisContext
  • propertySupportedDiagnostics
    public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics { get; }

    Inherits documentation from base type or interface.

  • fieldDiagnosticId
    public const string DiagnosticId

    Gets the diagnostic identifier emitted when a SELECT references a column that does not exist on the entity.

class

MissingIndexAnalyzer

Assembly: EricksonLopez.SqlBuilder.Analyzers
public class MissingIndexAnalyzer : DiagnosticAnalyzer
Inherits: DiagnosticAnalyzer

Analyzes WHERE clauses to warn if filtering by an unindexed column.

Members (3)

  • methodInitialize
    public override void Initialize(AnalysisContext context)

    Inherits documentation from base type or interface.

    context: AnalysisContext
  • propertySupportedDiagnostics
    public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics { get; }

    Inherits documentation from base type or interface.

  • fieldDiagnosticId
    public const string DiagnosticId

    Gets the diagnostic identifier emitted when a WHERE clause filters on a column that lacks a database index.

class

MissingSourceGeneratorAnalyzer

Assembly: EricksonLopez.SqlBuilder.Analyzers
public class MissingSourceGeneratorAnalyzer : DiagnosticAnalyzer
Inherits: DiagnosticAnalyzer

ESQL021 — Warns when a type is annotated with [SqlEntity] but the Source Generator package (EricksonLopez.SqlBuilder.SourceGenerators) is not referenced. Without the generator, the library falls back to reflection-based metadata which: 1. Breaks NativeAOT publishing. 2. Degrades startup performance. 3. May silently produce incorrect column names in trimmed builds.

Members (3)

  • methodInitialize
    public override void Initialize(AnalysisContext context)

    Inherits documentation from base type or interface.

    context: AnalysisContext
  • propertySupportedDiagnostics
    public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics { get; }

    Inherits documentation from base type or interface.

  • fieldDiagnosticId
    public const string DiagnosticId

    Gets the diagnostic identifier emitted when a `[SqlEntity]` type is missing the Source Generator package reference.

class

QueryPerformanceAnalyzer

Assembly: EricksonLopez.SqlBuilder.Analyzers
public class QueryPerformanceAnalyzer : DiagnosticAnalyzer
Inherits: DiagnosticAnalyzer

Analyzes IN clauses for excessive argument counts.

Members (3)

  • methodInitialize
    public override void Initialize(AnalysisContext context)

    Inherits documentation from base type or interface.

    context: AnalysisContext
  • propertySupportedDiagnostics
    public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics { get; }

    Inherits documentation from base type or interface.

  • fieldDiagnosticId
    public const string DiagnosticId

    Gets the diagnostic identifier emitted when a query exhibits a known performance anti-pattern.

class

RawStringOverloadAnalyzer

Assembly: EricksonLopez.SqlBuilder.Analyzers
public class RawStringOverloadAnalyzer : DiagnosticAnalyzer
Inherits: DiagnosticAnalyzer

Detects usage of the unsafe `Sql.Raw(string sql, ...)` overload and warns to use `Sql.Raw(FormattableString)` instead to prevent SQL injection vulnerabilities (ESQL011).

Members (3)

  • methodInitialize
    public override void Initialize(AnalysisContext context)

    Inherits documentation from base type or interface.

    context: AnalysisContext
  • propertySupportedDiagnostics
    public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics { get; }

    Inherits documentation from base type or interface.

  • fieldDiagnosticId
    public const string DiagnosticId

    Represents the diagnostic identifier for ESQL011.

class

RedundantWhereAnalyzer

Assembly: EricksonLopez.SqlBuilder.Analyzers
public class RedundantWhereAnalyzer : DiagnosticAnalyzer
Inherits: DiagnosticAnalyzer

Analyzes WHERE clauses to detect redundant conditions (e.g. 1 = 1).

Members (3)

  • methodInitialize
    public override void Initialize(AnalysisContext context)

    Inherits documentation from base type or interface.

    context: AnalysisContext
  • propertySupportedDiagnostics
    public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics { get; }

    Inherits documentation from base type or interface.

  • fieldDiagnosticId
    public const string DiagnosticId

    Gets the diagnostic identifier emitted when a WHERE clause condition is always true or always false.

class

RetryInsideTransactionAnalyzer

Assembly: EricksonLopez.SqlBuilder.Analyzers
public class RetryInsideTransactionAnalyzer : DiagnosticAnalyzer
Inherits: DiagnosticAnalyzer

Detects when a Polly resilience pipeline's `ExecuteAsync` lambda contains a direct call to `CommitAsync` on an `IUnitOfWork`, which is an anti-pattern that can cause data corruption on retry (ESQL005).

Remarks:

The correct pattern is to wrap the entire transactional unit (BeginUnitOfWork → Execute → Commit) inside the retry lambda. Wrapping only the commit is dangerous because a retry can re-execute the commit on a transaction that was already partially committed. See ADR-016 for the correct pattern.

Members (3)

  • methodInitialize
    public override void Initialize(AnalysisContext context)

    Inherits documentation from base type or interface.

    context: AnalysisContext
  • propertySupportedDiagnostics
    public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics { get; }

    Inherits documentation from base type or interface.

  • fieldDiagnosticId
    public const string DiagnosticId

    Represents the diagnostic identifier for ESQL012.

class

SchemaValidator

Assembly: EricksonLopez.SqlBuilder.Analyzers
public sealed class SchemaValidator

Provides base support for schema-aware validation in analyzers. Reads 'sqlbuilder-schema.json' from AdditionalFiles if provided (opt-in).

Members (3)

  • methodIsTableValid
    public bool IsTableValid(string tableName)

    Determines whether the specified table exists in the schema.

    tableName: string
    The table name to validate.

    Returns: `true` if the table is valid or schema validation is inactive; otherwise, `false`.

  • methodLoad
    public static SchemaValidator Load(AnalyzerOptions options)

    Loads schema validation settings from analyzer options.

    options: AnalyzerOptions
    The analyzer options containing additional files.

    Returns: A configured `SchemaValidator` instance.

  • propertyIsActive
    public bool IsActive { get; private set; }

    Gets a value indicating whether schema validation is active.

class

SelectStarAnalyzer

Assembly: EricksonLopez.SqlBuilder.Analyzers
public class SelectStarAnalyzer : DiagnosticAnalyzer
Inherits: DiagnosticAnalyzer

Analyzes queries for explicit use of '*' which is not recommended.

Members (3)

  • methodInitialize
    public override void Initialize(AnalysisContext context)

    Inherits documentation from base type or interface.

    context: AnalysisContext
  • propertySupportedDiagnostics
    public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics { get; }

    Inherits documentation from base type or interface.

  • fieldDiagnosticId
    public const string DiagnosticId

    Gets the diagnostic identifier emitted when a SELECT * projection is used without an explicit column list.

class

SelectStarCodeFix

Assembly: EricksonLopez.SqlBuilder.Analyzers
public class SelectStarCodeFix : CodeFixProvider
Inherits: CodeFixProvider

Provides a code fix to replace '*' with specific columns.

Members (3)

  • methodGetFixAllProvider
    public override FixAllProvider GetFixAllProvider()

    Inherits documentation from base type or interface.

  • methodRegisterCodeFixesAsync
    public override async Task RegisterCodeFixesAsync(CodeFixContext context)

    Inherits documentation from base type or interface.

    context: CodeFixContext
  • propertyFixableDiagnosticIds
    public override ImmutableArray<string> FixableDiagnosticIds { get; }

    Inherits documentation from base type or interface.

class

SqlKataMigrationAnalyzer

Assembly: EricksonLopez.SqlBuilder.Analyzers
public class SqlKataMigrationAnalyzer : DiagnosticAnalyzer
Inherits: DiagnosticAnalyzer

Detects usages of the legacy SqlKata `new Query(...)` pattern and suggests migrating them to the equivalent `Sql.From(...)` call.

Remarks:

Diagnostic ID: `ESQL025`. Severity: Info. A companion `SqlKataMigrationCodeFixProvider` is available to apply the migration automatically.

Members (3)

  • methodInitialize
    public override void Initialize(AnalysisContext context)

    Inherits documentation from base type or interface.

    context: AnalysisContext
  • propertySupportedDiagnostics
    public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics { get; }

    Inherits documentation from base type or interface.

  • fieldDiagnosticId
    public const string DiagnosticId

    Gets the diagnostic identifier emitted by this analyzer.

class

SqlKataMigrationCodeFixProvider

Assembly: EricksonLopez.SqlBuilder.Analyzers
public class SqlKataMigrationCodeFixProvider : CodeFixProvider
Inherits: CodeFixProvider

Provides a code fix that replaces legacy SqlKata `new Query(...)` instantiations with the equivalent `Sql.From(...)` call, as reported by `SqlKataMigrationAnalyzer`.

Members (3)

  • methodGetFixAllProvider
    public sealed override FixAllProvider GetFixAllProvider()

    Inherits documentation from base type or interface.

  • methodRegisterCodeFixesAsync
    public sealed override async Task RegisterCodeFixesAsync(CodeFixContext context)

    Inherits documentation from base type or interface.

    context: CodeFixContext
  • propertyFixableDiagnosticIds
    public sealed override ImmutableArray<string> FixableDiagnosticIds { get; }

    Gets the diagnostic IDs this provider can fix.

class

SyncOnUiThreadAnalyzer

Assembly: EricksonLopez.SqlBuilder.Analyzers
public class SyncOnUiThreadAnalyzer : DiagnosticAnalyzer
Inherits: DiagnosticAnalyzer

Detects synchronous database execution methods called in contexts where an asynchronous alternative is available, helping prevent UI thread blocking.

Remarks:

Diagnostic ID: `ESQL023`. Severity: Warning. Emits a warning when `ToResult`, `ToPagedList`, or `ToStream` are invoked synchronously. Use the corresponding `*Async` overloads instead.

Members (3)

  • methodInitialize
    public override void Initialize(AnalysisContext context)

    Inherits documentation from base type or interface.

    context: AnalysisContext
  • propertySupportedDiagnostics
    public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics { get; }

    Inherits documentation from base type or interface.

  • fieldDiagnosticId
    public const string DiagnosticId

    Gets the diagnostic identifier emitted by this analyzer.

class

TypeMapRegistrationAnalyzer

Assembly: EricksonLopez.SqlBuilder.Analyzers
public class TypeMapRegistrationAnalyzer : DiagnosticAnalyzer
Inherits: DiagnosticAnalyzer

Detects usages of `SqlMapper.AddTypeMap` and reminds consumers to verify that all required Dapper type maps are registered at application startup.

Remarks:

Diagnostic ID: `ESQL022`. Severity: Info. Missing type map registrations can cause runtime mapping errors when reading custom value types from query results.

Members (3)

  • methodInitialize
    public override void Initialize(AnalysisContext context)

    Inherits documentation from base type or interface.

    context: AnalysisContext
  • propertySupportedDiagnostics
    public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics { get; }

    Inherits documentation from base type or interface.

  • fieldDiagnosticId
    public const string DiagnosticId

    Gets the diagnostic identifier emitted by this analyzer.

class

UnsafeStringConcatenationAnalyzer

Assembly: EricksonLopez.SqlBuilder.Analyzers
public class UnsafeStringConcatenationAnalyzer : DiagnosticAnalyzer
Inherits: DiagnosticAnalyzer

Analyzes Raw SQL queries for unsafe string concatenation that could lead to SQL injection.

Members (3)

  • methodInitialize
    public override void Initialize(AnalysisContext context)

    Inherits documentation from base type or interface.

    context: AnalysisContext
  • propertySupportedDiagnostics
    public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics { get; }

    Inherits documentation from base type or interface.

  • fieldDiagnosticId
    public const string DiagnosticId

    Gets the diagnostic identifier emitted when raw string concatenation is used to build a SQL fragment, risking injection.

class

UnsafeStringConcatenationCodeFix

Assembly: EricksonLopez.SqlBuilder.Analyzers
public class UnsafeStringConcatenationCodeFix : CodeFixProvider
Inherits: CodeFixProvider

Provides a code fix to convert unsafe string concatenation to safe string interpolation.

Members (3)

  • methodGetFixAllProvider
    public override FixAllProvider GetFixAllProvider()

    Inherits documentation from base type or interface.

  • methodRegisterCodeFixesAsync
    public override async Task RegisterCodeFixesAsync(CodeFixContext context)

    Inherits documentation from base type or interface.

    context: CodeFixContext
  • propertyFixableDiagnosticIds
    public override ImmutableArray<string> FixableDiagnosticIds { get; }

    Inherits documentation from base type or interface.

EricksonLopez.SqlBuilder.Annotations#

7
class

DatabaseGeneratedAttribute

Assembly: EricksonLopez.SqlBuilder.Abstractions
public class DatabaseGeneratedAttribute : Attribute
Inherits: Attribute

Specifies that a property's value is generated by the database (e.g., identity or default values).

Members (0)

This type declares 0 public members (e.g. marker interface or empty enum/record).

class

GeneratedColumnAttribute

Assembly: EricksonLopez.SqlBuilder.Abstractions
public class GeneratedColumnAttribute : Attribute
Inherits: Attribute

Specifies that a property represents a computed or generated column in the database.

Members (0)

This type declares 0 public members (e.g. marker interface or empty enum/record).

interface

ISqlEntity

Assembly: EricksonLopez.SqlBuilder.Abstractions
public interface ISqlEntity

Defines the contract for an entity that is mapped to a SQL database table.

Members (7)

  • methodGetAllColumnNames
    string[] GetAllColumnNames()

    Gets all column names mapped to the entity properties, including generated ones.

    Returns: An array of all column names.

  • methodGetAllValues
    object?[] GetAllValues()

    Gets all current values of the entity properties, including generated ones.

    Returns: An array of all property values.

  • methodGetColumnNames
    string[] GetColumnNames()

    Gets the column names mapped to the entity properties, excluding generated ones.

    Returns: An array of column names.

  • methodGetIndexedColumns
    string[] GetIndexedColumns()

    Gets the names of the columns that are indexed.

    Returns: An array of indexed column names.

  • methodGetPropertyMap
    IReadOnlyDictionary<string, string> GetPropertyMap()

    Gets a mapping from property names to their corresponding database column names.

    Returns: A dictionary of property-to-column mappings.

  • methodGetTableName
    string GetTableName()

    Gets the name of the mapped database table.

    Returns: The table name.

  • methodGetValues
    object?[] GetValues()

    Gets the current values of the entity properties, excluding generated ones.

    Returns: An array of property values.

class

IndexedAttribute

Assembly: EricksonLopez.SqlBuilder.Abstractions
public class IndexedAttribute : Attribute
Inherits: Attribute

Specifies that a property represents a column that is indexed in the database.

Members (0)

This type declares 0 public members (e.g. marker interface or empty enum/record).

class

PostgreSqlCompositeTypeAttribute

Assembly: EricksonLopez.SqlBuilder.Abstractions
public class PostgreSqlCompositeTypeAttribute : Attribute
Inherits: Attribute

Specifies that a class represents a PostgreSQL composite type.

Members (2)

  • constructorPostgreSqlCompositeTypeAttribute
    public PostgreSqlCompositeTypeAttribute(string typeName)

    Initializes a new instance of the `PostgreSqlCompositeTypeAttribute` class.

    typeName: string
    The name of the composite type.
  • propertyTypeName
    public string TypeName { get; }

    Gets the name of the composite type.

class

PostgreSqlEnumAttribute

Assembly: EricksonLopez.SqlBuilder.Abstractions
public class PostgreSqlEnumAttribute : Attribute
Inherits: Attribute

Specifies that an enum or property represents a PostgreSQL enum type.

Members (2)

  • constructorPostgreSqlEnumAttribute
    public PostgreSqlEnumAttribute(string typeName)

    Initializes a new instance of the `PostgreSqlEnumAttribute` class.

    typeName: string
    The name of the enum type.
  • propertyTypeName
    public string TypeName { get; }

    Gets the name of the enum type in PostgreSQL.

class

SqlEntityAttribute

Assembly: EricksonLopez.SqlBuilder.Abstractions
public class SqlEntityAttribute : Attribute
Inherits: Attribute

Specifies that a class is a SQL entity mapped to a specific table.

Members (2)

  • constructorSqlEntityAttribute
    public SqlEntityAttribute(string tableName)

    Initializes a new instance of the `SqlEntityAttribute` class.

    tableName: string
    The name of the database table.
  • propertyTableName
    public string TableName { get; }

    Gets the name of the database table.

EricksonLopez.SqlBuilder.Aot#

2
class

AotConnectionExtensions

Assembly: EricksonLopez.SqlBuilder.Aot
public static class AotConnectionExtensions

Provides NativeAOT-compatible extension methods on `IDbConnection` that compile SQL builder queries and execute them in a single fluent call, with no reflection.

Remarks:

All methods accept a `mapper` delegate obtained from the source-generated `GetReaderParser()` method on any `[SqlEntity]` type:

var results = await connection.AotQueryAsync(
    Sql.From<Order>().Where(o => o.CustomerId == customerId),
    compiler,
    Order.GetReaderParser());

This differs from the Dapper-based execution path in that it operates purely over ADO.NET primitives, making it safe for NativeAOT, Blazor WASM, and other trim-unfriendly runtimes.

Members (13)

  • methodAotExecuteAsync
    public static Task<int> AotExecuteAsync(this IDbConnection connection, ISqlQuery query, ISqlCompiler compiler, IDbTransaction? transaction = null, int commandTimeout = 30, CancellationToken cancellationToken = default)

    Compiles and executes a non-query statement (INSERT, UPDATE, DELETE), returning rows affected.

    connection: this IDbConnection
    An open `IDbConnection`.
    query: ISqlQuery
    The query to compile and execute.
    compiler: ISqlCompiler
    The SQL compiler for the target provider.
    transaction: IDbTransaction?
    An optional `IDbTransaction`.
    commandTimeout: int
    Command timeout in seconds.
    cancellationToken: CancellationToken
    A token that can be used to cancel the asynchronous operation.

    Returns: A task representing the asynchronous operation. The task result contains the number of rows affected.

  • methodAotExecuteAsync
    public static Task<int> AotExecuteAsync(this IDbConnection connection, SqlResult result, IDbTransaction? transaction = null, int commandTimeout = 30, CancellationToken cancellationToken = default)

    Executes a pre-compiled `SqlResult` non-query — useful when the compiled SQL is cached.

    connection: this IDbConnection
    An open database connection.
    result: SqlResult
    The pre-compiled SQL result.
    transaction: IDbTransaction?
    An optional database transaction.
    commandTimeout: int
    Command timeout in seconds.
    cancellationToken: CancellationToken
    A token that can be used to cancel the asynchronous operation.

    Returns: A task representing the asynchronous operation. The task result contains the number of rows affected.

  • methodAotQueryAsync<T>
    public static Task<IReadOnlyList<T>> AotQueryAsync<T>(this IDbConnection connection, ISqlQuery query, ISqlCompiler compiler, Func<IDataReader, T> mapper, IDbTransaction? transaction = null, int commandTimeout = 30, CancellationToken cancellationToken = default)

    Compiles the query and executes it, returning all results mapped via the source-generated `mapper`. No reflection is used.

    connection: this IDbConnection
    An open `IDbConnection`.
    query: ISqlQuery
    The SQL query to compile and execute.
    compiler: ISqlCompiler
    The `ISqlCompiler` for the target provider.
    mapper: Func<IDataReader, T>
    A factory function that maps one `IDataReader` row to an entity. Obtain via `MyEntity.GetReaderParser()` (source-generated).
    transaction: IDbTransaction?
    An optional `IDbTransaction`.
    commandTimeout: int
    Command timeout in seconds (default: 30).
    cancellationToken: CancellationToken
    A token that can be used to cancel the asynchronous operation.

    Returns: A task representing the asynchronous operation. The task result contains all matched entities.

    Type parameters: T: The entity type to map.

  • methodAotQueryAsync<T>
    public static Task<IReadOnlyList<T>> AotQueryAsync<T>(this IDbConnection connection, ISqlQuery query, ISqlCompiler compiler, IDbTransaction? transaction = null, int commandTimeout = 30, CancellationToken cancellationToken = default) where T : class, EricksonLopez.SqlBuilder.Abstractions.Metadata.IStaticEntityMetadata<T>, new()

    Compiles and executes the query, automatically resolving the source-generated `IDataReader` parser from `T` with zero reflection.

    connection: this IDbConnection
    An open `IDbConnection`.
    query: ISqlQuery
    The SQL query to compile and execute.
    compiler: ISqlCompiler
    The `ISqlCompiler` for the target provider.
    transaction: IDbTransaction?
    An optional `IDbTransaction`.
    commandTimeout: int
    Command timeout in seconds (default: 30).
    cancellationToken: CancellationToken
    A token that can be used to cancel the asynchronous operation.

    Returns: A task representing the asynchronous operation. The task result contains all matched entities mapped via the source-generated parser.

    Type parameters: T: The entity type implementing `Metadata.IStaticEntityMetadata<T>`.

  • methodAotQueryAsync<T>
    public static Task<IReadOnlyList<T>> AotQueryAsync<T>(this IDbConnection connection, SqlResult result, Func<IDataReader, T> mapper, IDbTransaction? transaction = null, int commandTimeout = 30, CancellationToken cancellationToken = default)

    Executes a pre-compiled `SqlResult` without re-compiling — useful when the same compiled SQL is reused multiple times.

    connection: this IDbConnection
    An open database connection.
    result: SqlResult
    The pre-compiled SQL result.
    mapper: Func<IDataReader, T>
    The row mapper function.
    transaction: IDbTransaction?
    An optional database transaction.
    commandTimeout: int
    Command timeout in seconds.
    cancellationToken: CancellationToken
    A token that can be used to cancel the asynchronous operation.

    Returns: A task representing the asynchronous operation. The task result contains all matched entities.

    Type parameters: T: The entity type.

  • methodAotQueryAsync<T>
    public static Task<IReadOnlyList<T>> AotQueryAsync<T>(this IDbConnection connection, SqlResult result, IDbTransaction? transaction = null, int commandTimeout = 30, CancellationToken cancellationToken = default) where T : class, EricksonLopez.SqlBuilder.Abstractions.Metadata.IStaticEntityMetadata<T>, new()

    Executes a pre-compiled `SqlResult` without re-compiling, automatically resolving the source-generated parser.

    connection: this IDbConnection
    An open database connection.
    result: SqlResult
    The pre-compiled SQL result.
    transaction: IDbTransaction?
    An optional database transaction.
    commandTimeout: int
    Command timeout in seconds.
    cancellationToken: CancellationToken
    A token that can be used to cancel the asynchronous operation.

    Returns: A task representing the asynchronous operation. The task result contains all matched entities.

    Type parameters: T: The entity type.

  • methodAotQueryFirstOrDefaultAsync<T>
    public static Task<T?> AotQueryFirstOrDefaultAsync<T>(this IDbConnection connection, ISqlQuery query, ISqlCompiler compiler, Func<IDataReader, T> mapper, IDbTransaction? transaction = null, int commandTimeout = 30, CancellationToken cancellationToken = default) where T : class

    Compiles and executes the query, returning the first match or `null`.

    connection: this IDbConnection
    An open database connection.
    query: ISqlQuery
    The SQL query to compile and execute.
    compiler: ISqlCompiler
    The SQL compiler for the target provider.
    mapper: Func<IDataReader, T>
    The row mapper function.
    transaction: IDbTransaction?
    An optional database transaction.
    commandTimeout: int
    Command timeout in seconds.
    cancellationToken: CancellationToken
    A token that can be used to cancel the asynchronous operation.

    Returns: A task representing the asynchronous operation. The task result contains the first matched entity, or `null` if empty.

    Type parameters: T: The entity type.

  • methodAotQueryFirstOrDefaultAsync<T>
    public static Task<T?> AotQueryFirstOrDefaultAsync<T>(this IDbConnection connection, ISqlQuery query, ISqlCompiler compiler, IDbTransaction? transaction = null, int commandTimeout = 30, CancellationToken cancellationToken = default) where T : class, EricksonLopez.SqlBuilder.Abstractions.Metadata.IStaticEntityMetadata<T>, new()

    Compiles and executes the query, automatically resolving the source-generated parser, returning the first match or `null`.

    connection: this IDbConnection
    An open database connection.
    query: ISqlQuery
    The SQL query to compile and execute.
    compiler: ISqlCompiler
    The SQL compiler for the target provider.
    transaction: IDbTransaction?
    An optional database transaction.
    commandTimeout: int
    Command timeout in seconds.
    cancellationToken: CancellationToken
    A token that can be used to cancel the asynchronous operation.

    Returns: A task representing the asynchronous operation. The task result contains the first matched entity, or `null` if empty.

    Type parameters: T: The entity type.

  • methodAotQueryFirstOrDefaultAsync<T>
    public static Task<T?> AotQueryFirstOrDefaultAsync<T>(this IDbConnection connection, SqlResult result, IDbTransaction? transaction = null, int commandTimeout = 30, CancellationToken cancellationToken = default) where T : class, EricksonLopez.SqlBuilder.Abstractions.Metadata.IStaticEntityMetadata<T>, new()

    Executes a pre-compiled `SqlResult` without re-compiling, automatically resolving the source-generated parser, returning the first match or `null`.

    connection: this IDbConnection
    An open database connection.
    result: SqlResult
    The pre-compiled SQL result.
    transaction: IDbTransaction?
    An optional database transaction.
    commandTimeout: int
    Command timeout in seconds.
    cancellationToken: CancellationToken
    A token that can be used to cancel the asynchronous operation.

    Returns: A task representing the asynchronous operation. The task result contains the first matched entity, or `null` if empty.

    Type parameters: T: The entity type.

  • methodAotQueryScalarAsync<TScalar>
    public static Task<TScalar?> AotQueryScalarAsync<TScalar>(this IDbConnection connection, ISqlQuery query, ISqlCompiler compiler, IDbTransaction? transaction = null, int commandTimeout = 30, CancellationToken cancellationToken = default)

    Compiles the query and returns a scalar value (first column, first row).

    connection: this IDbConnection
    An open database connection.
    query: ISqlQuery
    The SQL query to compile and execute.
    compiler: ISqlCompiler
    The SQL compiler for the target provider.
    transaction: IDbTransaction?
    An optional database transaction.
    commandTimeout: int
    Command timeout in seconds.
    cancellationToken: CancellationToken
    A token that can be used to cancel the asynchronous operation.

    Returns: A task representing the asynchronous operation. The task result contains the scalar result value, or `default` if empty.

    Type parameters: TScalar: The scalar result type.

  • methodAotQuerySingleAsync<T>
    public static Task<T> AotQuerySingleAsync<T>(this IDbConnection connection, ISqlQuery query, ISqlCompiler compiler, Func<IDataReader, T> mapper, IDbTransaction? transaction = null, int commandTimeout = 30, CancellationToken cancellationToken = default)

    Compiles and executes the query, returning exactly one result or throwing.

    connection: this IDbConnection
    An open database connection.
    query: ISqlQuery
    The SQL query to compile and execute.
    compiler: ISqlCompiler
    The SQL compiler for the target provider.
    mapper: Func<IDataReader, T>
    The row mapper function.
    transaction: IDbTransaction?
    An optional database transaction.
    commandTimeout: int
    Command timeout in seconds.
    cancellationToken: CancellationToken
    A token that can be used to cancel the asynchronous operation.

    Returns: A task representing the asynchronous operation. The task result contains the single matched entity.

    Type parameters: T: The entity type.

  • methodAotQuerySingleAsync<T>
    public static Task<T> AotQuerySingleAsync<T>(this IDbConnection connection, ISqlQuery query, ISqlCompiler compiler, IDbTransaction? transaction = null, int commandTimeout = 30, CancellationToken cancellationToken = default) where T : class, EricksonLopez.SqlBuilder.Abstractions.Metadata.IStaticEntityMetadata<T>, new()

    Compiles and executes the query, automatically resolving the source-generated parser, returning exactly one result or throwing.

    connection: this IDbConnection
    An open database connection.
    query: ISqlQuery
    The SQL query to compile and execute.
    compiler: ISqlCompiler
    The SQL compiler for the target provider.
    transaction: IDbTransaction?
    An optional database transaction.
    commandTimeout: int
    Command timeout in seconds.
    cancellationToken: CancellationToken
    A token that can be used to cancel the asynchronous operation.

    Returns: A task representing the asynchronous operation. The task result contains the single matched entity.

    Type parameters: T: The entity type.

  • methodAotQuerySingleAsync<T>
    public static Task<T> AotQuerySingleAsync<T>(this IDbConnection connection, SqlResult result, IDbTransaction? transaction = null, int commandTimeout = 30, CancellationToken cancellationToken = default) where T : class, EricksonLopez.SqlBuilder.Abstractions.Metadata.IStaticEntityMetadata<T>, new()

    Executes a pre-compiled `SqlResult` without re-compiling, automatically resolving the source-generated parser, returning exactly one result or throwing.

    connection: this IDbConnection
    An open database connection.
    result: SqlResult
    The pre-compiled SQL result.
    transaction: IDbTransaction?
    An optional database transaction.
    commandTimeout: int
    Command timeout in seconds.
    cancellationToken: CancellationToken
    A token that can be used to cancel the asynchronous operation.

    Returns: A task representing the asynchronous operation. The task result contains the single matched entity.

    Type parameters: T: The entity type.

class

AotQueryExecutor

Assembly: EricksonLopez.SqlBuilder.Aot
public static class AotQueryExecutor

Provides a reflection-free, NativeAOT-compatible query execution layer over `IDbConnection` using source-generated entity mappers produced by `[SqlEntity]` and the SQL Builder DSL.

Remarks:

Unlike Dapper-based execution, this executor makes no use of runtime IL generation, `Reflection.Emit`, or `DynamicMethod`. All entity mapping is delegated to the compile-time `Parser` class generated by `SqlEntityGenerator` for each `[SqlEntity]` type. Use `AotQueryExecutor` as the execution backend when targeting environments that cannot JIT-compile code at runtime: NativeAOT, Blazor WASM (without interpreter), and constrained mobile platforms.

Members (5)

  • methodExecuteAsync
    public static async Task<int> ExecuteAsync(IDbConnection connection, SqlResult result, IDbTransaction? transaction = null, int commandTimeout = 30, CancellationToken cancellationToken = default)

    Executes a non-query SQL statement (INSERT, UPDATE, DELETE) and returns the number of rows affected.

    connection: IDbConnection
    An open database connection.
    result: SqlResult
    The compiled SQL query and parameters.
    transaction: IDbTransaction?
    An optional database transaction.
    commandTimeout: int
    The command timeout in seconds.
    cancellationToken: CancellationToken
    A token that can be used to cancel the asynchronous operation.

    Returns: A task representing the asynchronous operation. The task result contains the number of rows affected.

  • methodQueryAsync<T>
    public static async Task<IReadOnlyList<T>> QueryAsync<T>(IDbConnection connection, SqlResult result, Func<IDataReader, T> mapper, IDbTransaction? transaction = null, int commandTimeout = 30, CancellationToken cancellationToken = default)

    Executes the compiled SQL query against the connection and materializes results using a source-generated entity mapper — with no reflection.

    connection: IDbConnection
    An open `IDbConnection`.
    result: SqlResult
    The compiled SQL + parameters from `ISqlCompiler.Compile(ISqlQuery)`.
    mapper: Func<IDataReader, T>
    A `Func<IDataReader, T>` factory, typically obtained from `MyEntity.GetReaderParser()` or `MyEntity.FromReader`.
    transaction: IDbTransaction?
    An optional `IDbTransaction`.
    commandTimeout: int
    Optional command timeout in seconds.
    cancellationToken: CancellationToken
    A token that can be used to cancel the asynchronous operation.

    Returns: A task representing the asynchronous operation. The task result contains an enumerable of mapped `T` instances.

    Type parameters: T: The entity type. Must have a source-generated `GetReaderParser()` method produced by `SqlEntityGenerator`.

  • methodQueryFirstOrDefaultAsync<T>
    public static async Task<T?> QueryFirstOrDefaultAsync<T>(IDbConnection connection, SqlResult result, Func<IDataReader, T> mapper, IDbTransaction? transaction = null, int commandTimeout = 30, CancellationToken cancellationToken = default) where T : class

    Executes the SQL query and returns the first result, or `null` if none.

    connection: IDbConnection
    An open database connection.
    result: SqlResult
    The compiled SQL query and parameters.
    mapper: Func<IDataReader, T>
    The row mapper function.
    transaction: IDbTransaction?
    An optional database transaction.
    commandTimeout: int
    The command timeout in seconds.
    cancellationToken: CancellationToken
    A token that can be used to cancel the asynchronous operation.

    Returns: A task representing the asynchronous operation. The task result contains the first mapped entity, or `null` if the result set is empty.

    Type parameters: T: The entity type.

  • methodQueryScalarAsync<TScalar>
    public static async Task<TScalar?> QueryScalarAsync<TScalar>(IDbConnection connection, SqlResult result, IDbTransaction? transaction = null, int commandTimeout = 30, CancellationToken cancellationToken = default)

    Executes the SQL query and returns the first column of the first row, cast to `TScalar`. Returns the default value if the result set is empty or the value is `DBNull`.

    connection: IDbConnection
    An open database connection.
    result: SqlResult
    The compiled SQL query and parameters.
    transaction: IDbTransaction?
    An optional database transaction.
    commandTimeout: int
    The command timeout in seconds.
    cancellationToken: CancellationToken
    A token that can be used to cancel the asynchronous operation.

    Returns: A task representing the asynchronous operation. The task result contains the scalar result value, or `default` if empty.

    Type parameters: TScalar: The type of the scalar result.

  • methodQuerySingleAsync<T>
    public static async Task<T> QuerySingleAsync<T>(IDbConnection connection, SqlResult result, Func<IDataReader, T> mapper, IDbTransaction? transaction = null, int commandTimeout = 30, CancellationToken cancellationToken = default)

    Executes the SQL query and returns a single result, throwing if none or more than one are found.

    connection: IDbConnection
    An open database connection.
    result: SqlResult
    The compiled SQL query and parameters.
    mapper: Func<IDataReader, T>
    The row mapper function.
    transaction: IDbTransaction?
    An optional database transaction.
    commandTimeout: int
    The command timeout in seconds.
    cancellationToken: CancellationToken
    A token that can be used to cancel the asynchronous operation.

    Returns: A task representing the asynchronous operation. The task result contains the single mapped entity.

    Type parameters: T: The entity type. Exceptions: InvalidOperationException: The query returned no results or more than one result

EricksonLopez.SqlBuilder.Builders#

2
class

CaseExpressionBuilder

Assembly: EricksonLopez.SqlBuilder
public sealed class CaseExpressionBuilder

Provides a fluent builder for constructing SQL CASE expressions.

Remarks:

Usage example:

var caseExpr = new CaseExpressionBuilder()
    .When("status = {0}", 1).Then("'Active'")
    .When("status = {0}", 2).Then("'Inactive'")
    .Else("'Unknown'")
    .As("status_label")
    .Build();

var query = Sql.From<User>().SelectCase(caseExpr);

Evaluates conditional branches sequentially until a matching branch is found.

Members (6)

  • methodAs
    public CaseExpressionBuilder As(string alias)

    Sets the column alias for the CASE expression result (AS alias).

    alias: string
    The alias name.

    Returns: This builder for fluent chaining.

  • methodBuild
    public CaseNode Build()

    Builds and returns the `CaseNode` AST node.

    Returns: A `CaseNode` representing the complete CASE expression.

    Exceptions: InvalidOperationException: No WHEN branches have been added to the CASE expression

  • methodElse
    public CaseExpressionBuilder Else(string elseSql, params object?[] parameters)

    Sets the ELSE result of the CASE expression.

    elseSql: string
    The SQL result for the ELSE clause.
    parameters: params object?[]
    Optional parameters for the ELSE result.

    Returns: This builder for fluent chaining.

  • methodThen
    public CaseExpressionBuilder Then(string thenSql, params object?[] parameters)

    Adds a THEN result to the preceding WHEN condition.

    thenSql: string
    The SQL result expression (e.g., `"'Active'"` or `"{0}"`).
    parameters: params object?[]
    Optional parameters for the result expression.

    Returns: This builder for fluent chaining.

    Exceptions: InvalidOperationException: `When(string, object?[])` was not called prior to `Then(string, object?[])`

  • methodWhen
    public CaseExpressionBuilder When(string whenSql, params object?[] parameters)

    Adds a WHEN condition to the CASE expression.

    whenSql: string
    The SQL condition (supports `{0}` parameter placeholders).
    parameters: params object?[]
    Optional parameters for the condition.

    Returns: This builder for fluent chaining. Call `Then` next.

  • methodimplicit operator CaseNode
    public static implicit operator CaseNode(CaseExpressionBuilder builder)

    Converts a `CaseExpressionBuilder` instance to a `CaseNode`.

    builder: CaseExpressionBuilder
    The builder instance to convert.

    Returns: The compiled `CaseNode` AST node.

interface

ISqlRenderer

Assembly: EricksonLopez.SqlBuilder.Abstractions
public interface ISqlRenderer

Defines a contract for rendering SQL operations based on entity metadata and selected column masks. Dialect-specific renderers provide optimized, AOT-compatible SQL generation.

Members (7)

  • methodRenderBulkInsert<T>
    EricksonLopez.SqlBuilder.Builders.Bulk.Operations.BulkSqlResult RenderBulkInsert<T>(IEnumerable<T> entities, List<EricksonLopez.SqlBuilder.ColumnSelection.IColumnSelectionRule<T>> rules, int batchSize) where T : IStaticEntityMetadata<T>

    Renders a batch of bulk INSERT statements for a collection of entities.

    entities: IEnumerable<T>
    The collection of entities to insert.
    rules: List<EricksonLopez.SqlBuilder.ColumnSelection.IColumnSelectionRule<T>>
    The column selection rules applied to the operation.
    batchSize: int
    The maximum number of entities to process per batch.

    Returns: A `Operations.BulkSqlResult` containing the generated batches.

    Type parameters: T: The type of the entities.

  • methodRenderBulkInsertIgnore<T>
    EricksonLopez.SqlBuilder.Builders.Bulk.Operations.BulkSqlResult RenderBulkInsertIgnore<T>(IEnumerable<T> entities, List<EricksonLopez.SqlBuilder.ColumnSelection.IColumnSelectionRule<T>> rules, int batchSize) where T : IStaticEntityMetadata<T>

    Renders a batch of bulk INSERT IGNORE statements for a collection of entities.

    entities: IEnumerable<T>
    The collection of entities to insert.
    rules: List<EricksonLopez.SqlBuilder.ColumnSelection.IColumnSelectionRule<T>>
    The column selection rules applied to the operation.
    batchSize: int
    The maximum number of entities to process per batch.

    Returns: A `Operations.BulkSqlResult` containing the generated batches.

    Type parameters: T: The type of the entities.

  • methodRenderBulkMerge<T>
    EricksonLopez.SqlBuilder.Builders.Bulk.Operations.BulkSqlResult RenderBulkMerge<T>(IEnumerable<T> entities, List<EricksonLopez.SqlBuilder.ColumnSelection.IColumnSelectionRule<T>> rules, int batchSize) where T : IStaticEntityMetadata<T>

    Renders a batch of bulk MERGE statements for a collection of entities.

    entities: IEnumerable<T>
    The collection of entities to merge.
    rules: List<EricksonLopez.SqlBuilder.ColumnSelection.IColumnSelectionRule<T>>
    The column selection rules applied to the operation.
    batchSize: int
    The maximum number of entities to process per batch.

    Returns: A `Operations.BulkSqlResult` containing the generated batches.

    Type parameters: T: The type of the entities.

  • methodRenderBulkUpdate<T>
    EricksonLopez.SqlBuilder.Builders.Bulk.Operations.BulkSqlResult RenderBulkUpdate<T>(IEnumerable<T> entities, List<EricksonLopez.SqlBuilder.ColumnSelection.IColumnSelectionRule<T>> rules, int batchSize) where T : IStaticEntityMetadata<T>

    Renders a batch of bulk UPDATE statements for a collection of entities.

    entities: IEnumerable<T>
    The collection of entities to update.
    rules: List<EricksonLopez.SqlBuilder.ColumnSelection.IColumnSelectionRule<T>>
    The column selection rules applied to the operation.
    batchSize: int
    The maximum number of entities to process per batch.

    Returns: A `Operations.BulkSqlResult` containing the generated batches.

    Type parameters: T: The type of the entities.

  • methodRenderBulkUpsert<T>
    EricksonLopez.SqlBuilder.Builders.Bulk.Operations.BulkSqlResult RenderBulkUpsert<T>(IEnumerable<T> entities, List<EricksonLopez.SqlBuilder.ColumnSelection.IColumnSelectionRule<T>> rules, int batchSize) where T : IStaticEntityMetadata<T>

    Renders a batch of bulk UPSERT statements for a collection of entities.

    entities: IEnumerable<T>
    The collection of entities to upsert.
    rules: List<EricksonLopez.SqlBuilder.ColumnSelection.IColumnSelectionRule<T>>
    The column selection rules applied to the operation.
    batchSize: int
    The maximum number of entities to process per batch.

    Returns: A `Operations.BulkSqlResult` containing the generated batches.

    Type parameters: T: The type of the entities.

  • methodRenderInsert<T>
    SqlResult RenderInsert<T>(T entity, Span<bool> insertMask) where T : IStaticEntityMetadata<T>

    Renders an INSERT statement for a single entity.

    entity: T
    The entity instance.
    insertMask: Span<bool>
    A span representing which columns to include in the INSERT.

    Returns: A `SqlResult` containing the generated SQL and parameters.

    Type parameters: T: The type of the entity.

  • methodRenderUpdate<T>
    SqlResult RenderUpdate<T>(T entity, Span<bool> setMask, Span<bool> whereMask) where T : IStaticEntityMetadata<T>

    Renders an UPDATE statement for a single entity.

    entity: T
    The entity instance.
    setMask: Span<bool>
    A span representing which columns to include in the SET clause.
    whereMask: Span<bool>
    A span representing which columns to use in the WHERE clause (usually primary keys).

    Returns: A `SqlResult` containing the generated SQL and parameters.

    Type parameters: T: The type of the entity.

EricksonLopez.SqlBuilder.Builders.Bulk#

3
class

BulkBuilder<T>

Assembly: EricksonLopez.SqlBuilder
public sealed class BulkBuilder<T> where T : IStaticEntityMetadata<T>

Provides a fluent API for configuring and constructing highly optimized AOT-compatible bulk SQL operations.

Remarks:

Type parameters: T: The type of the entities, which must implement `IStaticEntityMetadata<T>`.

Members (9)

  • methodExcludeGenerated
    public BulkBuilder<T> ExcludeGenerated()

    Configures the bulk operation to exclude database-generated columns (e.g., identity columns, computed columns).

    Returns: The current `BulkBuilder<T>` instance for fluent chaining.

    This rule is applied by default upon creation of the `BulkBuilder<T>`.

  • methodIgnoreNulls
    public BulkBuilder<T> IgnoreNulls()

    Configures the bulk operation to exclude properties that have null values from the SQL statement.

    Returns: The current `BulkBuilder<T>` instance for fluent chaining.

  • methodInsert
    public IBulkOperation<T> Insert()

    Finalizes the configuration and creates a bulk INSERT operation.

    Returns: A new `IBulkOperation<T>` configured for insertion.

  • methodInsertIgnore
    public IBulkOperation<T> InsertIgnore()

    Finalizes the configuration and creates a bulk INSERT IGNORE operation.

    Returns: A new `IBulkOperation<T>` configured for insert-ignore.

  • methodMerge
    public IBulkOperation<T> Merge()

    Finalizes the configuration and creates a bulk MERGE operation.

    Returns: A new `IBulkOperation<T>` configured for merging.

  • methodOnly
    public BulkBuilder<T> Only(params int[] columns)

    Configures the bulk operation to include only the specified columns.

    columns: params int[]
    An array of integer identifiers representing the columns to include.

    Returns: The current `BulkBuilder<T>` instance for fluent chaining.

  • methodUpdate
    public IBulkOperation<T> Update()

    Finalizes the configuration and creates a bulk UPDATE operation.

    Returns: A new `IBulkOperation<T>` configured for updating.

  • methodUpsert
    public IBulkOperation<T> Upsert()

    Finalizes the configuration and creates a bulk UPSERT (insert or update) operation.

    Returns: A new `IBulkOperation<T>` configured for upserting.

  • methodWithBatchSize
    public BulkBuilder<T> WithBatchSize(int batchSize)

    Configures the maximum number of entities to process in a single bulk batch.

    batchSize: int
    The maximum number of entities per batch. Default is 5000.

    Returns: The current `BulkBuilder<T>` instance for fluent chaining.

class

BulkInsertResult<T>

Assembly: EricksonLopez.SqlBuilder.Abstractions
public sealed class BulkInsertResult<T>

Represents the result of a native bulk INSERT operation.

Remarks:

Type parameters: T: The type of entity inserted.

Members (4)

  • constructorBulkInsertResult
    public BulkInsertResult(int rowsAffected, IReadOnlyList<T> insertedEntities)

    Initializes a new instance of `BulkInsertResult<T>`.

    rowsAffected: int
    The number of rows inserted.
    insertedEntities: IReadOnlyList<T>
    The entities with their generated identities. Pass an empty list if identities were not requested.
  • methodWithoutIdentities
    public static BulkInsertResult<T> WithoutIdentities(int rowsAffected)

    Creates a `BulkInsertResult<T>` for operations that do not return identity values.

    rowsAffected: int
    The number of rows inserted.

    Returns: A new `BulkInsertResult<T>` instance with an empty entity list.

  • propertyInsertedEntities
    public IReadOnlyList<T> InsertedEntities { get; }

    Gets the collection of inserted entities with their identity columns populated.

    This collection is only populated when `BulkOptions.ReturnIdentities` was set to `true` on the originating operation. Otherwise, returns an empty list.

  • propertyRowsAffected
    public int RowsAffected { get; }

    Gets the total number of rows that were inserted.

class

BulkOptions

Assembly: EricksonLopez.SqlBuilder.Abstractions
public sealed class BulkOptions

Represents configuration options for native bulk insert operations.

Members (4)

  • propertyBatchSize
    public int BatchSize { get; set; }

    Gets or sets the maximum number of rows to process in a single batch.

    A value of `0` means process all rows in a single server round-trip. Default is `0` (single batch).

  • propertyDefault
    public static BulkOptions Default { get; }

    Gets the default `BulkOptions` instance with all default values.

  • propertyReturnIdentities
    public bool ReturnIdentities { get; set; }

    Gets or sets a value indicating whether the database-generated identity values should be read back and populated on the inserted entities.

    When `true`, the operation will execute an additional query to retrieve the generated identity values and fill them into the returned entities. Default is `false`.

  • propertyTimeoutSeconds
    public int TimeoutSeconds { get; set; }

    Gets or sets the number of seconds for the operation to complete before it times out.

    A value of `0` means no timeout. Default is `30` seconds.

EricksonLopez.SqlBuilder.Builders.Bulk.Operations#

3
class

BulkSqlResult

Assembly: EricksonLopez.SqlBuilder.Abstractions
public sealed class BulkSqlResult

Represents the result of a bulk SQL compilation, which may be split into multiple execution batches.

Members (2)

  • constructorBulkSqlResult
    public BulkSqlResult(IReadOnlyList<SqlResult> batches)

    Initializes a new instance of the `BulkSqlResult` class.

    batches: IReadOnlyList<SqlResult>
    The list of compiled SQL batches.
  • propertyBatches
    public IReadOnlyList<SqlResult> Batches { get; }

    Gets the list of generated SQL batches, where each batch represents a single SQL command.

interface

IBulkOperation<T>

Assembly: EricksonLopez.SqlBuilder.Abstractions
public interface IBulkOperation<T>

Defines a contract for constructing a bulk SQL operation and delegating its compilation to a dialect-specific renderer.

Remarks:

Type parameters: T: The type of the entities involved in the bulk operation.

Members (1)

  • methodBuild
    BulkSqlResult Build(ISqlRenderer dialect)

    Builds and compiles the bulk SQL operation using the provided renderer.

    dialect: ISqlRenderer
    The dialect-specific SQL renderer.

    Returns: A `BulkSqlResult` containing the generated execution batches.

interface

IEntitySource<T>

Assembly: EricksonLopez.SqlBuilder.Abstractions
public interface IEntitySource<T>

Exposes the underlying entities associated with a bulk operation.

Remarks:

Type parameters: T: The entity type.

Members (1)

  • propertyEntities
    IEnumerable<T> Entities { get; }

    Gets the entities involved in the bulk operation.

EricksonLopez.SqlBuilder.Builders.Insert#

1
class

InsertBuilder<T>

Assembly: EricksonLopez.SqlBuilder
public class InsertBuilder<T> where T : IStaticEntityMetadata<T>

Provides a builder for constructing AOT-compatible, single-entity INSERT queries dynamically based on entity metadata.

Remarks:

Type parameters: T: The type of the entity to insert, which must implement `IStaticEntityMetadata<T>`.

Members (7)

  • constructorInsertBuilder
    public InsertBuilder(T entity)

    Initializes a new instance of the `InsertBuilder<T>` class using the specified entity.

    entity: T
    The entity containing the data to insert.
  • methodAddRule
    public void AddRule(IColumnSelectionRule<T> rule)

    Adds a custom column selection rule to the insert operation.

    rule: IColumnSelectionRule<T>
    The rule that dictates whether a column is included or excluded.
  • methodBuild
    public SqlResult Build(ISqlRenderer dialect)

    Finalizes the configuration and compiles the insert query using the specified renderer.

    dialect: ISqlRenderer
    The SQL renderer specific to the target database provider.

    Returns: The compiled SQL query string and its parameters.

    Exceptions: InvalidOperationException: No columns are selected for the insert operation

  • methodExcept
    public InsertBuilder<T> Except(params int[] columns)

    Configures the insert operation to explicitly exclude the specified columns.

    columns: params int[]
    An array of integer identifiers representing the columns to exclude.

    Returns: The current `InsertBuilder<T>` instance for fluent chaining.

  • methodIgnoreNulls
    public InsertBuilder<T> IgnoreNulls()

    Configures the insert operation to exclude properties that have `null` values.

    Returns: The current `InsertBuilder<T>` instance for fluent chaining.

  • methodOnly
    public InsertBuilder<T> Only(params int[] columns)

    Configures the insert operation to include only the specified columns.

    columns: params int[]
    An array of integer identifiers representing the columns to include.

    Returns: The current `InsertBuilder<T>` instance for fluent chaining.

  • propertyEntity
    public T Entity { get; }

    Gets the entity instance being inserted.

EricksonLopez.SqlBuilder.Builders.Update#

1
class

UpdateBuilder<T>

Assembly: EricksonLopez.SqlBuilder
public class UpdateBuilder<T> where T : IStaticEntityMetadata<T>

Provides a builder for constructing AOT-compatible, single-entity UPDATE queries dynamically based on entity metadata.

Remarks:

By default, primary keys are excluded from the SET clause and automatically mapped to the WHERE clause. Type parameters: T: The type of the entity to update, which must implement `IStaticEntityMetadata<T>`.

Members (7)

  • constructorUpdateBuilder
    public UpdateBuilder(T entity)

    Initializes a new instance of the `UpdateBuilder<T>` class using the specified entity.

    entity: T
    The entity containing the modifications.
  • methodAddRule
    public void AddRule(IColumnSelectionRule<T> rule)

    Adds a custom column selection rule to the update operation.

    rule: IColumnSelectionRule<T>
    The rule that dictates whether a column is included or excluded.
  • methodBuild
    public SqlResult Build(ISqlRenderer dialect)

    Finalizes the configuration and compiles the update query using the specified renderer.

    dialect: ISqlRenderer
    The SQL renderer specific to the target database provider.

    Returns: The compiled SQL query string and its parameters.

    Exceptions: InvalidOperationException: No columns are selected for the SET clause, or no primary keys could be identified for the WHERE clause

  • methodExcept
    public UpdateBuilder<T> Except(params int[] columns)

    Configures the update operation to explicitly exclude the specified columns from the SET clause.

    columns: params int[]
    An array of integer identifiers representing the columns to exclude.

    Returns: The current `UpdateBuilder<T>` instance for fluent chaining.

  • methodIgnoreNulls
    public UpdateBuilder<T> IgnoreNulls()

    Configures the update operation to exclude properties that have `null` values.

    Returns: The current `UpdateBuilder<T>` instance for fluent chaining.

  • methodOnly
    public UpdateBuilder<T> Only(params int[] columns)

    Configures the update operation to include only the specified columns in the SET clause.

    columns: params int[]
    An array of integer identifiers representing the columns to update.

    Returns: The current `UpdateBuilder<T>` instance for fluent chaining.

  • propertyEntity
    public T Entity { get; }

    Gets the entity instance containing the updated state.

EricksonLopez.SqlBuilder.ColumnSelection#

4
struct

ColumnSelectionContext<TEntity>

Assembly: EricksonLopez.SqlBuilder.Abstractions
public ref struct ColumnSelectionContext<TEntity> where TEntity : IStaticEntityMetadata<TEntity>

Provides contextual information during the execution of column selection rules.

Remarks:

Type parameters: TEntity: The type of the entity whose columns are being processed.

Members (10)

  • constructorColumnSelectionContext
    public ColumnSelectionContext(TEntity entity, SqlOperation operation, Span<bool> includedColumns, TEntity? snapshot = default)

    Initializes a new instance of the `ColumnSelectionContext<TEntity>` struct.

    entity: TEntity
    The primary entity instance.
    operation: SqlOperation
    The SQL operation context.
    includedColumns: Span<bool>
    The bitmask tracking column inclusion.
    snapshot: TEntity?
    An optional snapshot of the entity for diff comparisons.
  • methodAreEqual
    public bool AreEqual(int index)

    Determines whether the value of the specified column index is equal to the value in the snapshot.

    index: int
    The zero-based index of the column.

    Returns: `true` if the current value matches the snapshot; otherwise, `false`.

  • methodExclude
    public void Exclude(ColumnToken token)

    Explicitly excludes a specific column from the final SQL statement.

    token: ColumnToken
    The token representing the column to exclude.
  • methodInclude
    public void Include(ColumnToken token)

    Explicitly includes a specific column in the final SQL statement.

    token: ColumnToken
    The token representing the column to include.
  • methodIsDefault
    public bool IsDefault(int index)

    Determines whether the value of the specified column index is its default value.

    index: int
    The zero-based index of the column.

    Returns: `true` if the column value is its default value; otherwise, `false`.

  • methodIsNull
    public bool IsNull(int index)

    Determines whether the value of the specified column index is null.

    index: int
    The zero-based index of the column.

    Returns: `true` if the column value is `null`; otherwise, `false`.

  • propertyEntity
    public TEntity Entity { get; }

    Gets the entity instance being evaluated.

  • propertyIncludedColumns
    public Span<bool> IncludedColumns { get; }

    Gets a mutable span representing a bitmask of columns. True indicates inclusion, False indicates exclusion.

  • propertyOperation
    public SqlOperation Operation { get; }

    Gets the type of SQL operation being built (e.g., Insert, Update).

  • propertySnapshot
    public TEntity? Snapshot { get; }

    Gets an optional snapshot entity representing the original state for diff-based updates.

struct

ColumnSelectionEngine<TEntity>

Assembly: EricksonLopez.SqlBuilder
public ref struct ColumnSelectionEngine<TEntity> where TEntity : IStaticEntityMetadata<TEntity>

Provides a high-performance, allocation-free engine for executing column selection rules.

Remarks:

Type parameters: TEntity: The type of the entity whose columns are being selected.

Members (1)

  • methodSelectColumns
    public static void SelectColumns(TEntity entity, SqlOperation operation, ReadOnlySpan<IColumnSelectionRule<TEntity>> rules, Span<bool> resultMask)

    Executes a set of column selection rules in phase order to determine the final bitmask of included columns.

    entity: TEntity
    The entity instance containing the data.
    operation: SqlOperation
    The SQL operation being performed (e.g., Insert, Update).
    rules: ReadOnlySpan<IColumnSelectionRule<TEntity>>
    The span of rules to apply.
    resultMask: Span<bool>
    A pre-allocated bitmask span that will be mutated to reflect the final selection.

    Exceptions: ArgumentException: `resultMask` length does not match `TEntity.ColumnCount`

interface

IColumnSelectionRule<TEntity>

Assembly: EricksonLopez.SqlBuilder.Abstractions
public interface IColumnSelectionRule<TEntity> where TEntity : IStaticEntityMetadata<TEntity>

Defines a contract for rules that determine which entity columns are included in a SQL statement.

Remarks:

Type parameters: TEntity: The type of the entity being processed.

Members (2)

  • methodApply
    void Apply(ref ColumnSelectionContext<TEntity> context)

    Applies the selection logic to the given execution context.

    context: ref ColumnSelectionContext<TEntity>
    A reference to the context containing the entity and the current selection mask.
  • propertyPhase
    RulePhase Phase { get; }

    Gets the execution phase indicating when this rule should be evaluated by the engine.

enum

RulePhase

Assembly: EricksonLopez.SqlBuilder.Abstractions
public enum RulePhase : byte

Defines the sequence phases in which column selection rules are evaluated. Rules in lower phases execute before rules in higher phases.

Members (4)

  • fieldPhase1Baseline
    Phase1Baseline = 0

    Specifies the initial phase establishing the baseline selection (e.g., OnlyColumnsRule).

  • fieldPhase2Structural
    Phase2Structural = 1

    Specifies the phase evaluating structural metadata attributes (e.g., ExcludeGenerated, ExcludePrimaryKeys).

  • fieldPhase3ValueBased
    Phase3ValueBased = 2

    Specifies the phase evaluating runtime property values (e.g., IgnoreNulls, IgnoreDefaults).

  • fieldPhase4Overrides
    Phase4Overrides = 3

    Specifies the final phase applying explicit user overrides (e.g., ExceptColumnsRule).

EricksonLopez.SqlBuilder.ColumnSelection.Rules#

5
struct

ExceptColumnsRule<TEntity>

Assembly: EricksonLopez.SqlBuilder
public readonly struct ExceptColumnsRule<TEntity> : IColumnSelectionRule<TEntity> where TEntity : IStaticEntityMetadata<TEntity>
Implements: IColumnSelectionRule<TEntity>

Represents a column selection rule that explicitly excludes specific columns from the SQL operation.

Remarks:

Type parameters: TEntity: The type of the entity being processed.

Members (3)

  • constructorExceptColumnsRule
    public ExceptColumnsRule(int[] deniedIndexes)

    Initializes a new instance of the `ExceptColumnsRule<TEntity>` struct.

    deniedIndexes: int[]
    An array of integer identifiers representing the columns to exclude.
  • methodApply
    public void Apply(ref ColumnSelectionContext<TEntity> context)

    Applies the selection logic to the given execution context.

    context: ref ColumnSelectionContext<TEntity>
    A reference to the context containing the entity and the current selection mask.
  • propertyPhase
    public RulePhase Phase { get; }

    Gets the execution phase indicating when this rule should be evaluated by the engine.

struct

ExcludeGeneratedRule<TEntity>

Assembly: EricksonLopez.SqlBuilder
public readonly struct ExcludeGeneratedRule<TEntity> : IColumnSelectionRule<TEntity> where TEntity : IStaticEntityMetadata<TEntity>
Implements: IColumnSelectionRule<TEntity>

Represents a column selection rule that automatically excludes database-generated columns (such as identity or computed columns) from the SQL operation.

Remarks:

Type parameters: TEntity: The type of the entity being processed.

Members (2)

  • methodApply
    public void Apply(ref ColumnSelectionContext<TEntity> context)

    Applies the selection logic to the given execution context.

    context: ref ColumnSelectionContext<TEntity>
    A reference to the context containing the entity and the current selection mask.
  • propertyPhase
    public RulePhase Phase { get; }

    Gets the execution phase indicating when this rule should be evaluated by the engine.

struct

ExcludePrimaryKeysRule<TEntity>

Assembly: EricksonLopez.SqlBuilder
public readonly struct ExcludePrimaryKeysRule<TEntity> : IColumnSelectionRule<TEntity> where TEntity : IStaticEntityMetadata<TEntity>
Implements: IColumnSelectionRule<TEntity>

Represents a column selection rule that automatically excludes primary key columns from the SQL operation.

Remarks:

Type parameters: TEntity: The type of the entity being processed.

Members (2)

  • methodApply
    public void Apply(ref ColumnSelectionContext<TEntity> context)

    Applies the selection logic to the given execution context.

    context: ref ColumnSelectionContext<TEntity>
    A reference to the context containing the entity and the current selection mask.
  • propertyPhase
    public RulePhase Phase { get; }

    Gets the execution phase indicating when this rule should be evaluated by the engine.

struct

IgnoreNullsRule<TEntity>

Assembly: EricksonLopez.SqlBuilder
public readonly struct IgnoreNullsRule<TEntity> : IColumnSelectionRule<TEntity> where TEntity : IStaticEntityMetadata<TEntity>
Implements: IColumnSelectionRule<TEntity>

Represents a column selection rule that dynamically excludes any columns whose underlying property value is `null`.

Remarks:

Type parameters: TEntity: The type of the entity being processed.

Members (2)

  • methodApply
    public void Apply(ref ColumnSelectionContext<TEntity> context)

    Applies the selection logic to the given execution context.

    context: ref ColumnSelectionContext<TEntity>
    A reference to the context containing the entity and the current selection mask.
  • propertyPhase
    public RulePhase Phase { get; }

    Gets the execution phase indicating when this rule should be evaluated by the engine.

struct

OnlyColumnsRule<TEntity>

Assembly: EricksonLopez.SqlBuilder
public readonly struct OnlyColumnsRule<TEntity> : IColumnSelectionRule<TEntity> where TEntity : IStaticEntityMetadata<TEntity>
Implements: IColumnSelectionRule<TEntity>

Represents a column selection rule that acts as a whitelist, excluding any columns not explicitly specified.

Remarks:

Type parameters: TEntity: The type of the entity being processed.

Members (3)

  • constructorOnlyColumnsRule
    public OnlyColumnsRule(int[] allowedIndexes)

    Initializes a new instance of the `OnlyColumnsRule<TEntity>` struct.

    allowedIndexes: int[]
    An array of integer identifiers representing the only columns to include.
  • methodApply
    public void Apply(ref ColumnSelectionContext<TEntity> context)

    Applies the selection logic to the given execution context.

    context: ref ColumnSelectionContext<TEntity>
    A reference to the context containing the entity and the current selection mask.
  • propertyPhase
    public RulePhase Phase { get; }

    Gets the execution phase indicating when this rule should be evaluated by the engine.

EricksonLopez.SqlBuilder.Dapper#

11
struct

BoundSelectQuery<T>

Assembly: EricksonLopez.SqlBuilder.Dapper
public readonly struct BoundSelectQuery<T> : IAstQuery where T : class, new()
Implements: IAstQuery

Represents a select query bound to an open database connection.

Remarks:

Type parameters: T: The entity type.

Members (16)

  • constructorBoundSelectQuery
    public BoundSelectQuery(SelectQuery<T> query, IDbConnection connection)

    Initializes a new instance of the `BoundSelectQuery<T>` class.

    query: SelectQuery<T>
    The underlying select query.
    connection: IDbConnection
    The bound database connection.

    Exceptions: ArgumentNullException: `query` or `connection` is `null`

  • methodAnd
    public BoundSelectQuery<T> And(System.Linq.Expressions.Expression<Func<T, bool>> predicate)

    Appends an AND predicate to the WHERE clause.

    predicate: System.Linq.Expressions.Expression<Func<T, bool>>
    The filter condition.

    Returns: A new `BoundSelectQuery<T>` with the predicate applied.

  • methodBuild
    public SqlResult Build(ISqlCompiler compiler)

    Inherits documentation from `ISqlQuery.Build`.

    compiler: ISqlCompiler
  • methodOr
    public BoundSelectQuery<T> Or(System.Linq.Expressions.Expression<Func<T, bool>> predicate)

    Appends an OR predicate to the WHERE clause.

    predicate: System.Linq.Expressions.Expression<Func<T, bool>>
    The filter condition.

    Returns: A new `BoundSelectQuery<T>` with the predicate applied.

  • methodOrderBy
    public BoundSelectQuery<T> OrderBy(System.Linq.Expressions.Expression<Func<T, object>> keySelector)

    Adds an ORDER BY clause in ascending order.

    keySelector: System.Linq.Expressions.Expression<Func<T, object>>
    The key selector expression.

    Returns: A new `BoundSelectQuery<T>` with the ordering applied.

  • methodOrderByDescending
    public BoundSelectQuery<T> OrderByDescending(System.Linq.Expressions.Expression<Func<T, object>> keySelector)

    Adds an ORDER BY clause in descending order.

    keySelector: System.Linq.Expressions.Expression<Func<T, object>>
    The key selector expression.

    Returns: A new `BoundSelectQuery<T>` with the ordering applied.

  • methodPaginate
    public BoundSelectQuery<T> Paginate(int pageNumber, int pageSize)

    Applies LIMIT/OFFSET pagination to the query.

    pageNumber: int
    The 1-based page number.
    pageSize: int
    The number of records per page.

    Returns: A new `BoundSelectQuery<T>` with pagination applied.

  • methodProjectTo<TResult>
    public BoundSelectQuery<TResult> ProjectTo<TResult>() where TResult : class, new()

    Projects this query to a different result type.

    Returns: A new `BoundSelectQuery<TResult>` instance.

    Type parameters: TResult: The target projection type.

  • methodToPagedListAsync
    public Task<Result<IPagedList<T>>> ToPagedListAsync(int pageNumber, int pageSize, IDbTransaction? transaction = null)

    Executes the query with pagination and returns a `Result<T>` containing the paged list, or an error.

    pageNumber: int
    The 1-based page number.
    pageSize: int
    The number of items per page.
    transaction: IDbTransaction?
    An optional database transaction.

    Returns: A task representing the asynchronous operation. The task result contains a `Result<T>` with the paginated list.

  • methodToResultAsync
    public Task<Result<IReadOnlyList<T>>> ToResultAsync(IDbTransaction? transaction = null)

    Executes the query and returns a `Result<T>` containing a read-only list of items, or an error.

    transaction: IDbTransaction?
    An optional database transaction.

    Returns: A task representing the asynchronous operation. The task result contains a `Result<T>` with the query results.

  • methodToStreamAsync
    public IAsyncEnumerable<T> ToStreamAsync(IDbTransaction? transaction = null, CancellationToken cancellationToken = default)

    Executes the query and returns an unbuffered asynchronous stream of items.

    transaction: IDbTransaction?
    An optional database transaction.
    cancellationToken: CancellationToken
    A token that can be used to cancel the asynchronous operation.

    Returns: An asynchronous stream of items.

  • methodWhere
    public BoundSelectQuery<T> Where(FormattableString condition)

    Adds a raw WHERE condition to the query.

    condition: FormattableString
    The raw SQL condition.

    Returns: A new `BoundSelectQuery<T>` with the condition applied.

  • methodWhere
    public BoundSelectQuery<T> Where(System.Linq.Expressions.Expression<Func<T, bool>> predicate)

    Inherits documentation from `SelectQuery<T>.Where(Expression<Func<T, bool>>)`.

    predicate: System.Linq.Expressions.Expression<Func<T, bool>>
  • propertyConnection
    public IDbConnection Connection { get; }

    Gets the database connection bound to this query.

  • propertyQuery
    public SelectQuery<T> Query { get; }

    Gets the underlying select query.

  • propertyTag
    public string? Tag { get; }

    Inherits documentation from base type or interface.

class

ConnectionSqlExtensions

Assembly: EricksonLopez.SqlBuilder.Dapper
public static class ConnectionSqlExtensions

Provides extension methods on `IDbConnection` for starting a fluent SQL builder chain.

Members (6)

  • methodPaginate<T>
    public static SelectQuery<T> Paginate<T>(this SelectQuery<T> query, int pageNumber, int pageSize) where T : class, new()

    Applies pagination limits to the specified select query.

    query: this SelectQuery<T>
    The query to paginate.
    pageNumber: int
    The 1-based page number.
    pageSize: int
    The number of records per page.

    Returns: The paginated query.

    Type parameters: T: The type of the query result.

  • methodProjectTo<T, TResult>
    public static SelectQuery<TResult> ProjectTo<T, TResult>(this SelectQuery<T> query) where T : class, new() where TResult : class, new()

    Projects a select query to a different result type while preserving the query structure.

    query: this SelectQuery<T>
    The query to project.

    Returns: A new `SelectQuery<TResult>` instance.

    Type parameters: T: The original entity type.; TResult: The new target projection type.

  • methodSql
    public static SqlBuilderConnectionContext Sql(this IDbConnection connection)

    Initiates a SQL builder context on the current connection.

    connection: this IDbConnection
    The database connection.

    Returns: A `SqlBuilderConnectionContext` bound to the connection.

  • methodToPagedListAsync<T>
    public static async Task<Result<IPagedList<T>>> ToPagedListAsync<T>(this SelectQuery<T> query, IDbConnection connection, int pageNumber, int pageSize, IDbTransaction? transaction = null) where T : class, new()

    Executes a paginated query asynchronously, including a total count calculation, and returns a `Result<T>` with `IPagedList<T>`.

    query: this SelectQuery<T>
    The query to execute.
    connection: IDbConnection
    The database connection.
    pageNumber: int
    The 1-based page number.
    pageSize: int
    The number of items per page.
    transaction: IDbTransaction?
    An optional transaction.

    Returns: A task representing the asynchronous operation. The task result contains a `Result<T>` with the paginated list, or an error.

    Type parameters: T: The type of the returned items.

  • methodToResultAsync<T>
    public static async Task<Result<IReadOnlyList<T>>> ToResultAsync<T>(this SelectQuery<T> query, IDbConnection connection, IDbTransaction? transaction = null) where T : class, new()

    Executes the select query asynchronously and returns a standardized `Result<T>`.

    query: this SelectQuery<T>
    The query to execute.
    connection: IDbConnection
    The database connection.
    transaction: IDbTransaction?
    An optional transaction.

    Returns: A task representing the asynchronous operation. The task result contains a `Result<T>` with a read-only list of items, or an error.

    Type parameters: T: The type of the returned items.

  • methodToStreamAsync<T>
    public static IAsyncEnumerable<T> ToStreamAsync<T>(this SelectQuery<T> query, IDbConnection connection, IDbTransaction? transaction = null, CancellationToken cancellationToken = default) where T : class, new()

    Executes the select query asynchronously and returns an unbuffered asynchronous stream of items.

    query: this SelectQuery<T>
    The query to execute.
    connection: IDbConnection
    The database connection.
    transaction: IDbTransaction?
    An optional transaction.
    cancellationToken: CancellationToken
    A token that can be used to cancel the asynchronous operation.

    Returns: An asynchronous stream of items.

    Type parameters: T: The type of the returned items.

class

DapperConcurrencyExtensions

Assembly: EricksonLopez.SqlBuilder.Dapper
public static class DapperConcurrencyExtensions

Extension methods for optimistic concurrency execution with Dapper.

Members (2)

  • methodExecuteWithConcurrencyCheckAsync<T>
    public static Task<int> ExecuteWithConcurrencyCheckAsync<T>(this IDbConnection connection, EricksonLopez.SqlBuilder.Abstractions.ISqlQuery query, IDbTransaction? transaction = null, int? commandTimeout = null) where T : class

    Executes an UPDATE query compiled with `WithConcurrencyToken` and throws `Abstractions.DbConcurrencyException` if the update affects zero rows. Uses the connection's registered compiler automatically.

    connection: this IDbConnection
    The database connection (must have a registered compiler via `DapperExtensions.RegisterCompiler`).
    query: EricksonLopez.SqlBuilder.Abstractions.ISqlQuery
    The UPDATE query including a `WithConcurrencyToken` node.
    transaction: IDbTransaction?
    Optional transaction.
    commandTimeout: int?
    Optional command timeout in seconds.

    Returns: A task representing the asynchronous operation. The task result contains the number of rows affected (always >= 1 on success).

    Type parameters: T: The entity type being updated. Exceptions: Abstractions.DbConcurrencyException: Zero rows are affected, indicating a concurrency conflict

  • methodExecuteWithConcurrencyCheckAsync<T>
    public static async Task<int> ExecuteWithConcurrencyCheckAsync<T>(this IDbConnection connection, EricksonLopez.SqlBuilder.Abstractions.ISqlQuery query, ISqlCompiler compiler, IDbTransaction? transaction = null, int? commandTimeout = null) where T : class

    Executes an UPDATE query compiled with `WithConcurrencyToken` and throws `Abstractions.DbConcurrencyException` if the update affects zero rows.

    connection: this IDbConnection
    The database connection.
    query: EricksonLopez.SqlBuilder.Abstractions.ISqlQuery
    The UPDATE query. Must include a `WithConcurrencyToken` node.
    compiler: ISqlCompiler
    The SQL compiler for the target dialect.
    transaction: IDbTransaction?
    Optional transaction.
    commandTimeout: int?
    Optional command timeout in seconds.

    Returns: A task representing the asynchronous operation. The task result contains the number of rows affected (always >= 1 on success).

    Type parameters: T: The entity type being updated. Exceptions: Abstractions.DbConcurrencyException: Zero rows are affected, indicating a concurrency conflict Example:

    await connection.ExecuteWithConcurrencyCheckAsync<User>(
        Sql.Update<User>()
           .Set(u => u.Name, "Alice")
           .Where(u => u.Id == userId)
           .WithConcurrencyToken(u => u.Version, currentVersion),
        sqlServerCompiler);
class

DapperExtensions

Assembly: EricksonLopez.SqlBuilder.Dapper
public static class DapperExtensions

Provides extension methods for `IDbConnection` to seamlessly integrate EricksonLopez.SqlBuilder with Dapper.

Members (15)

  • methodBulkDeleteAsync<T>
    public static Task<int> BulkDeleteAsync<T>(this IDbConnection connection, ISqlQuery query, IEnumerable<T> entities, IDbTransaction? transaction = null, CancellationToken cancellationToken = default)

    Bulk deletes a collection of entities using the specified template query.

    connection: this IDbConnection
    The database connection to execute against.
    query: ISqlQuery
    The DELETE query template used as the SQL command text.
    entities: IEnumerable<T>
    The collection of entities parameterizing the delete conditions.
    transaction: IDbTransaction?
    An optional transaction to participate in.
    cancellationToken: CancellationToken
    A token that can be used to cancel the asynchronous operation.

    Returns: A task representing the asynchronous operation. The task result contains the total number of rows affected.

    Type parameters: T: The entity type to delete.

  • methodBulkInsertAsync<T>
    public static Task<int> BulkInsertAsync<T>(this IDbConnection connection, IEnumerable<T> entities, IDbTransaction? transaction = null, CancellationToken cancellationToken = default) where T : class, new()

    Bulk inserts a collection of entities using the most appropriate registered native strategy, falling back to a parameterized batch insert.

    connection: this IDbConnection
    The database connection to execute against.
    entities: IEnumerable<T>
    The collection of entities to insert.
    transaction: IDbTransaction?
    An optional transaction to participate in.
    cancellationToken: CancellationToken
    A token that can be used to cancel the asynchronous operation.

    Returns: A task representing the asynchronous operation. The task result contains the total number of rows inserted.

    Type parameters: T: The entity type to insert. Must have a default constructor and be a reference type.

  • methodBulkUpdateAsync<T>
    public static Task<int> BulkUpdateAsync<T>(this IDbConnection connection, ISqlQuery query, IEnumerable<T> entities, IDbTransaction? transaction = null, CancellationToken cancellationToken = default)

    Bulk updates a collection of entities using the specified template query.

    connection: this IDbConnection
    The database connection to execute against.
    query: ISqlQuery
    The UPDATE query template used as the SQL command text.
    entities: IEnumerable<T>
    The collection of entities whose values parameterize the update.
    transaction: IDbTransaction?
    An optional transaction to participate in.
    cancellationToken: CancellationToken
    A token that can be used to cancel the asynchronous operation.

    Returns: A task representing the asynchronous operation. The task result contains the total number of rows affected.

    Type parameters: T: The entity type to update.

  • methodExecute
    public static int Execute(this IDbConnection connection, ISqlQuery query, IDbTransaction? transaction = null)

    Synchronously executes a non-query SQL command and returns the number of rows affected.

    connection: this IDbConnection
    The database connection to execute against.
    query: ISqlQuery
    The SQL query to compile and execute.
    transaction: IDbTransaction?
    An optional transaction to participate in.

    Returns: The number of rows affected.

  • methodExecuteAsync
    public static Task<int> ExecuteAsync(this IDbConnection connection, ISqlQuery query, IDbTransaction? transaction = null, CancellationToken cancellationToken = default)

    Asynchronously executes a non-query SQL command and returns the number of rows affected.

    connection: this IDbConnection
    The database connection to execute against.
    query: ISqlQuery
    The SQL query to compile and execute.
    transaction: IDbTransaction?
    An optional transaction to participate in.
    cancellationToken: CancellationToken
    A token that can be used to cancel the asynchronous operation.

    Returns: A task representing the asynchronous operation. The task result contains the number of rows affected.

  • methodGetCompiler
    public static ISqlCompiler GetCompiler(IDbConnection connection)

    Retrieves the `ISqlCompiler` registered for the specified connection's runtime type.

    connection: IDbConnection
    The active database connection whose concrete type is used to look up the compiler.

    Returns: The registered `ISqlCompiler` for the connection type.

    Exceptions: InvalidOperationException: No compiler has been registered for the connection type via `RegisterCompiler<TConnection>`

  • methodQuery<T>
    public static IEnumerable<T> Query<T>(this IDbConnection connection, ISqlQuery query, IDbTransaction? transaction = null)

    Synchronously executes a query and maps the results to strongly typed objects.

    connection: this IDbConnection
    The database connection to execute against.
    query: ISqlQuery
    The SQL query to compile and execute.
    transaction: IDbTransaction?
    An optional transaction to participate in.

    Returns: A collection of `T` instances.

    Type parameters: T: The type to map each result row to.

  • methodQueryAotAsync<T>
    public static Task<IEnumerable<T>> QueryAotAsync<T>(this IDbConnection connection, ISqlQuery query, System.Func<IDataReader, T> mapper, IDbTransaction? transaction = null, CancellationToken cancellationToken = default)

    Asynchronously executes a query without reflection-based mapping, delegating row hydration to the provided delegate.

    connection: this IDbConnection
    The database connection to execute against.
    query: ISqlQuery
    The SQL query to compile and execute.
    mapper: System.Func<IDataReader, T>
    A reflection-free delegate that reads a single row and produces a `T` instance.
    transaction: IDbTransaction?
    An optional transaction to participate in.
    cancellationToken: CancellationToken
    A token that can be used to cancel the asynchronous operation.

    Returns: A task representing the asynchronous operation. The task result contains the collection of mapped instances.

    Suitable for AOT (Ahead-of-Time) compiled environments or scenarios where reflection is undesirable. Use alongside `SqlEntityGenerator` source-generated mappers for maximum performance. Type parameters: T: The type produced by the `mapper` delegate.

  • methodQueryAsync<T>
    public static Task<IEnumerable<T>> QueryAsync<T>(this IDbConnection connection, ISqlQuery query, IDbTransaction? transaction = null, CancellationToken cancellationToken = default)

    Asynchronously executes a query and maps the results to strongly typed objects.

    connection: this IDbConnection
    The database connection to execute against.
    query: ISqlQuery
    The SQL query to compile and execute.
    transaction: IDbTransaction?
    An optional transaction to participate in.
    cancellationToken: CancellationToken
    A token that can be used to cancel the asynchronous operation.

    Returns: A task representing the asynchronous operation. The task result contains the collection of mapped `T` instances.

    Type parameters: T: The type to map each result row to.

  • methodQueryFirstOrDefaultAotAsync<T>
    public static Task<T?> QueryFirstOrDefaultAotAsync<T>(this IDbConnection connection, ISqlQuery query, System.Func<IDataReader, T> mapper, IDbTransaction? transaction = null, CancellationToken cancellationToken = default)

    Asynchronously executes a query without reflection-based mapping and returns the first result, or `default` if the result set is empty.

    connection: this IDbConnection
    The database connection to execute against.
    query: ISqlQuery
    The SQL query to compile and execute.
    mapper: System.Func<IDataReader, T>
    A reflection-free delegate that reads a single row and produces a `T` instance.
    transaction: IDbTransaction?
    An optional transaction to participate in.
    cancellationToken: CancellationToken
    A token that can be used to cancel the asynchronous operation.

    Returns: A task representing the asynchronous operation. The task result contains the first mapped instance, or `default` if the result set is empty.

    Type parameters: T: The type produced by the `mapper` delegate.

  • methodQuerySequentialAsync<T>
    public static Task<IEnumerable<T>> QuerySequentialAsync<T>(this IDbConnection connection, ISqlQuery query, System.Func<IDataReader, T> mapper, IDbTransaction? transaction = null, CancellationToken cancellationToken = default)

    Asynchronously executes a query using `CommandBehavior.SequentialAccess` and maps rows using a custom reader delegate.

    connection: this IDbConnection
    The database connection to execute against.
    query: ISqlQuery
    The SQL query to compile and execute.
    mapper: System.Func<IDataReader, T>
    A delegate that reads a single row from the `IDataReader` and produces a `T` instance.
    transaction: IDbTransaction?
    An optional transaction to participate in.
    cancellationToken: CancellationToken
    A token that can be used to cancel the asynchronous operation.

    Returns: A task representing the asynchronous operation. The task result contains the collection of mapped instances.

    `CommandBehavior.SequentialAccess` reduces memory pressure when reading rows with large binary or text columns, as columns must be read in ordinal order. Type parameters: T: The type produced by the `mapper` delegate.

  • methodQueryStreamAsync<T>
    public static async IAsyncEnumerable<T> QueryStreamAsync<T>(this IDbConnection connection, ISqlQuery query, IDbTransaction? transaction = null, CancellationToken cancellationToken = default)

    Asynchronously executes a query and yields results as an unbuffered asynchronous stream.

    connection: this IDbConnection
    The database connection to execute against. Must derive from `Common.DbConnection`.
    query: ISqlQuery
    The SQL query to compile and execute.
    transaction: IDbTransaction?
    An optional transaction to participate in.
    cancellationToken: CancellationToken
    A token that can be used to cancel the asynchronous enumeration.

    Returns: An asynchronous stream of `T` instances.

    Rows are streamed directly from the database as they become available, making the operation suitable for processing large result sets without buffering all rows in memory. Requires the connection to be a `Common.DbConnection`. Type parameters: T: The type to map each result row to. Exceptions: NotSupportedException: `connection` does not inherit from `Common.DbConnection`

  • methodRegisterBulkStrategy
    public static void RegisterBulkStrategy(IBulkStrategy strategy)

    Registers a native bulk strategy for a specific database provider.

    strategy: IBulkStrategy
    The bulk strategy implementation to register (e.g., a `SqlBulkCopy` or `NpgsqlBinaryImporter` wrapper).

    Registered strategies are evaluated in registration order when `BulkInsertAsync<T>` is called. The first strategy whose `IBulkStrategy.CanHandle` returns `true` is used.

  • methodRegisterCompiler<TConnection>
    public static void RegisterCompiler<TConnection>(System.Func<ISqlCompiler> compilerFactory) where TConnection : IDbConnection

    Registers an ISqlCompiler factory for a specific IDbConnection type. This allows the extension methods to dynamically resolve the correct SQL dialect at runtime.

    compilerFactory: System.Func<ISqlCompiler>
    A factory function that returns an instance of the specific ISqlCompiler.

    Type parameters: TConnection: The specific type of IDbConnection (e.g., SqlConnection, NpgsqlConnection).

  • methodRegisterTypeHandler<T>
    public static void RegisterTypeHandler<T>(EricksonLopez.SqlBuilder.Abstractions.ITypeHandler handler)

    Registers a custom type handler with both `SqlBuilder.Sql` and Dapper's `SqlMapper` simultaneously.

    handler: EricksonLopez.SqlBuilder.Abstractions.ITypeHandler
    The handler implementation responsible for reading and writing values of type `T`.

    Type parameters: T: The type for which the handler is registered.

class

DapperMultiMappingExtensions

Assembly: EricksonLopez.SqlBuilder.Dapper
public static class DapperMultiMappingExtensions

Provides multi-mapping extension methods for `IDbConnection`, allowing split-on multi-entity mapping using `ISqlQuery` objects.

Remarks:

These wrappers cover Dapper's built-in 2-7 entity overloads. Cancellation support is provided by wrapping the call in a task and observing the token.

Members (12)

  • methodQuery<TFirst, TSecond, TReturn>
    public static IEnumerable<TReturn> Query<TFirst, TSecond, TReturn>(this IDbConnection connection, ISqlQuery query, Func<TFirst, TSecond, TReturn> map, string splitOn = "", IDbTransaction? transaction = null, bool buffered = true)

    Synchronously executes a JOIN query and maps results to two entity types.

    connection: this IDbConnection
    The database connection to execute the query against.
    query: ISqlQuery
    The SQL query to compile and execute.
    map: Func<TFirst, TSecond, TReturn>
    The mapping function that combines the two entities into the aggregate return type.
    splitOn: string
    The column name that marks the start of the second entity.
    transaction: IDbTransaction?
    An optional database transaction to participate in.
    buffered: bool
    A value indicating whether to buffer the results in memory before returning.

    Returns: A collection of `TReturn` instances resulting from the multi-entity mapping.

    Type parameters: TFirst: The first entity type representing the left side of the split.; TSecond: The second entity type.; TReturn: The returned aggregate type.

  • methodQuery<TFirst, TSecond, TThird, TFourth, TFifth, TReturn>
    public static IEnumerable<TReturn> Query<TFirst, TSecond, TThird, TFourth, TFifth, TReturn>(this IDbConnection connection, ISqlQuery query, Func<TFirst, TSecond, TThird, TFourth, TFifth, TReturn> map, string splitOn = "", IDbTransaction? transaction = null, bool buffered = true)

    Synchronously executes a JOIN query and maps results to five entity types.

    connection: this IDbConnection
    The database connection to execute the query against.
    query: ISqlQuery
    The SQL query to compile and execute.
    map: Func<TFirst, TSecond, TThird, TFourth, TFifth, TReturn>
    The mapping function that combines the five entities into the aggregate return type.
    splitOn: string
    The column names that mark the start of each subsequent entity.
    transaction: IDbTransaction?
    An optional database transaction to participate in.
    buffered: bool
    A value indicating whether to buffer the results in memory before returning.

    Returns: A collection of `TReturn` instances resulting from the multi-entity mapping.

    Type parameters: TFirst: The first entity type representing the left side of the split.; TSecond: The second entity type.; TThird: The third entity type.; TFourth: The fourth entity type.; TFifth: The fifth entity type.; TReturn: The returned aggregate type.

  • methodQuery<TFirst, TSecond, TThird, TFourth, TFifth, TSixth, TReturn>
    public static IEnumerable<TReturn> Query<TFirst, TSecond, TThird, TFourth, TFifth, TSixth, TReturn>(this IDbConnection connection, ISqlQuery query, Func<TFirst, TSecond, TThird, TFourth, TFifth, TSixth, TReturn> map, string splitOn = "", IDbTransaction? transaction = null, bool buffered = true)

    Synchronously executes a JOIN query and maps results to six entity types.

    connection: this IDbConnection
    The database connection to execute the query against.
    query: ISqlQuery
    The SQL query to compile and execute.
    map: Func<TFirst, TSecond, TThird, TFourth, TFifth, TSixth, TReturn>
    The mapping function that combines the six entities into the aggregate return type.
    splitOn: string
    The column names that mark the start of each subsequent entity.
    transaction: IDbTransaction?
    An optional database transaction to participate in.
    buffered: bool
    A value indicating whether to buffer the results in memory before returning.

    Returns: A collection of `TReturn` instances resulting from the multi-entity mapping.

    Type parameters: TFirst: The first entity type representing the left side of the split.; TSecond: The second entity type.; TThird: The third entity type.; TFourth: The fourth entity type.; TFifth: The fifth entity type.; TSixth: The sixth entity type.; TReturn: The returned aggregate type.

  • methodQuery<TFirst, TSecond, TThird, TFourth, TFifth, TSixth, TSeventh, TReturn>
    public static IEnumerable<TReturn> Query<TFirst, TSecond, TThird, TFourth, TFifth, TSixth, TSeventh, TReturn>(this IDbConnection connection, ISqlQuery query, Func<TFirst, TSecond, TThird, TFourth, TFifth, TSixth, TSeventh, TReturn> map, string splitOn = "", IDbTransaction? transaction = null, bool buffered = true)

    Synchronously executes a JOIN query and maps results to seven entity types. This is the maximum typed overload supported by Dapper.

    connection: this IDbConnection
    The database connection to execute the query against.
    query: ISqlQuery
    The SQL query to compile and execute.
    map: Func<TFirst, TSecond, TThird, TFourth, TFifth, TSixth, TSeventh, TReturn>
    The mapping function that combines the seven entities into the aggregate return type.
    splitOn: string
    The column names that mark the start of each subsequent entity.
    transaction: IDbTransaction?
    An optional database transaction to participate in.
    buffered: bool
    A value indicating whether to buffer the results in memory before returning.

    Returns: A collection of `TReturn` instances resulting from the multi-entity mapping.

    Type parameters: TFirst: The first entity type representing the left side of the split.; TSecond: The second entity type.; TThird: The third entity type.; TFourth: The fourth entity type.; TFifth: The fifth entity type.; TSixth: The sixth entity type.; TSeventh: The seventh entity type.; TReturn: The returned aggregate type.

  • methodQuery<TFirst, TSecond, TThird, TFourth, TReturn>
    public static IEnumerable<TReturn> Query<TFirst, TSecond, TThird, TFourth, TReturn>(this IDbConnection connection, ISqlQuery query, Func<TFirst, TSecond, TThird, TFourth, TReturn> map, string splitOn = "", IDbTransaction? transaction = null, bool buffered = true)

    Synchronously executes a JOIN query and maps results to four entity types.

    connection: this IDbConnection
    The database connection to execute the query against.
    query: ISqlQuery
    The SQL query to compile and execute.
    map: Func<TFirst, TSecond, TThird, TFourth, TReturn>
    The mapping function that combines the four entities into the aggregate return type.
    splitOn: string
    The column names that mark the start of each subsequent entity.
    transaction: IDbTransaction?
    An optional database transaction to participate in.
    buffered: bool
    A value indicating whether to buffer the results in memory before returning.

    Returns: A collection of `TReturn` instances resulting from the multi-entity mapping.

    Type parameters: TFirst: The first entity type representing the left side of the split.; TSecond: The second entity type.; TThird: The third entity type.; TFourth: The fourth entity type.; TReturn: The returned aggregate type.

  • methodQuery<TFirst, TSecond, TThird, TReturn>
    public static IEnumerable<TReturn> Query<TFirst, TSecond, TThird, TReturn>(this IDbConnection connection, ISqlQuery query, Func<TFirst, TSecond, TThird, TReturn> map, string splitOn = "", IDbTransaction? transaction = null, bool buffered = true)

    Synchronously executes a JOIN query and maps results to three entity types.

    connection: this IDbConnection
    The database connection to execute the query against.
    query: ISqlQuery
    The SQL query to compile and execute.
    map: Func<TFirst, TSecond, TThird, TReturn>
    The mapping function that combines the three entities into the aggregate return type.
    splitOn: string
    The column names that mark the start of each subsequent entity.
    transaction: IDbTransaction?
    An optional database transaction to participate in.
    buffered: bool
    A value indicating whether to buffer the results in memory before returning.

    Returns: A collection of `TReturn` instances resulting from the multi-entity mapping.

    Type parameters: TFirst: The first entity type representing the left side of the split.; TSecond: The second entity type.; TThird: The third entity type.; TReturn: The returned aggregate type.

  • methodQueryAsync<TFirst, TSecond, TReturn>
    public static async Task<IEnumerable<TReturn>> QueryAsync<TFirst, TSecond, TReturn>(this IDbConnection connection, ISqlQuery query, Func<TFirst, TSecond, TReturn> map, string splitOn = "", IDbTransaction? transaction = null, bool buffered = true, CancellationToken cancellationToken = default)

    Asynchronously executes a JOIN query and maps results to two entity types.

    connection: this IDbConnection
    The database connection to execute the query against.
    query: ISqlQuery
    The SQL query to compile and execute.
    map: Func<TFirst, TSecond, TReturn>
    The mapping function that combines the two entities into the aggregate return type.
    splitOn: string
    The column name that marks the start of the second entity.
    transaction: IDbTransaction?
    An optional database transaction to participate in.
    buffered: bool
    A value indicating whether to buffer the results in memory before returning.
    cancellationToken: CancellationToken
    A token that can be used to cancel the asynchronous operation.

    Returns: A task representing the asynchronous operation. The task result contains a collection of `TReturn` instances.

    Type parameters: TFirst: The first entity type representing the left side of the split.; TSecond: The second entity type.; TReturn: The returned aggregate type.

  • methodQueryAsync<TFirst, TSecond, TThird, TFourth, TFifth, TReturn>
    public static async Task<IEnumerable<TReturn>> QueryAsync<TFirst, TSecond, TThird, TFourth, TFifth, TReturn>(this IDbConnection connection, ISqlQuery query, Func<TFirst, TSecond, TThird, TFourth, TFifth, TReturn> map, string splitOn = "", IDbTransaction? transaction = null, bool buffered = true, CancellationToken cancellationToken = default)

    Asynchronously executes a JOIN query and maps results to five entity types.

    connection: this IDbConnection
    The database connection to execute the query against.
    query: ISqlQuery
    The SQL query to compile and execute.
    map: Func<TFirst, TSecond, TThird, TFourth, TFifth, TReturn>
    The mapping function that combines the five entities into the aggregate return type.
    splitOn: string
    The column names that mark the start of each subsequent entity.
    transaction: IDbTransaction?
    An optional database transaction to participate in.
    buffered: bool
    A value indicating whether to buffer the results in memory before returning.
    cancellationToken: CancellationToken
    A token that can be used to cancel the asynchronous operation.

    Returns: A task representing the asynchronous operation. The task result contains a collection of `TReturn` instances.

    Type parameters: TFirst: The first entity type representing the left side of the split.; TSecond: The second entity type.; TThird: The third entity type.; TFourth: The fourth entity type.; TFifth: The fifth entity type.; TReturn: The returned aggregate type.

  • methodQueryAsync<TFirst, TSecond, TThird, TFourth, TFifth, TSixth, TReturn>
    public static async Task<IEnumerable<TReturn>> QueryAsync<TFirst, TSecond, TThird, TFourth, TFifth, TSixth, TReturn>(this IDbConnection connection, ISqlQuery query, Func<TFirst, TSecond, TThird, TFourth, TFifth, TSixth, TReturn> map, string splitOn = "", IDbTransaction? transaction = null, bool buffered = true, CancellationToken cancellationToken = default)

    Asynchronously executes a JOIN query and maps results to six entity types.

    connection: this IDbConnection
    The database connection to execute the query against.
    query: ISqlQuery
    The SQL query to compile and execute.
    map: Func<TFirst, TSecond, TThird, TFourth, TFifth, TSixth, TReturn>
    The mapping function that combines the six entities into the aggregate return type.
    splitOn: string
    The column names that mark the start of each subsequent entity.
    transaction: IDbTransaction?
    An optional database transaction to participate in.
    buffered: bool
    A value indicating whether to buffer the results in memory before returning.
    cancellationToken: CancellationToken
    A token that can be used to cancel the asynchronous operation.

    Returns: A task representing the asynchronous operation. The task result contains a collection of `TReturn` instances.

    Type parameters: TFirst: The first entity type representing the left side of the split.; TSecond: The second entity type.; TThird: The third entity type.; TFourth: The fourth entity type.; TFifth: The fifth entity type.; TSixth: The sixth entity type.; TReturn: The returned aggregate type.

  • methodQueryAsync<TFirst, TSecond, TThird, TFourth, TFifth, TSixth, TSeventh, TReturn>
    public static async Task<IEnumerable<TReturn>> QueryAsync<TFirst, TSecond, TThird, TFourth, TFifth, TSixth, TSeventh, TReturn>(this IDbConnection connection, ISqlQuery query, Func<TFirst, TSecond, TThird, TFourth, TFifth, TSixth, TSeventh, TReturn> map, string splitOn = "", IDbTransaction? transaction = null, bool buffered = true, CancellationToken cancellationToken = default)

    Asynchronously executes a JOIN query and maps results to seven entity types. This is the maximum typed overload supported by Dapper.

    connection: this IDbConnection
    The database connection to execute the query against.
    query: ISqlQuery
    The SQL query to compile and execute.
    map: Func<TFirst, TSecond, TThird, TFourth, TFifth, TSixth, TSeventh, TReturn>
    The mapping function that combines the seven entities into the aggregate return type.
    splitOn: string
    The column names that mark the start of each subsequent entity.
    transaction: IDbTransaction?
    An optional database transaction to participate in.
    buffered: bool
    A value indicating whether to buffer the results in memory before returning.
    cancellationToken: CancellationToken
    A token that can be used to cancel the asynchronous operation.

    Returns: A task representing the asynchronous operation. The task result contains a collection of `TReturn` instances.

    Type parameters: TFirst: The first entity type representing the left side of the split.; TSecond: The second entity type.; TThird: The third entity type.; TFourth: The fourth entity type.; TFifth: The fifth entity type.; TSixth: The sixth entity type.; TSeventh: The seventh entity type.; TReturn: The returned aggregate type.

  • methodQueryAsync<TFirst, TSecond, TThird, TFourth, TReturn>
    public static async Task<IEnumerable<TReturn>> QueryAsync<TFirst, TSecond, TThird, TFourth, TReturn>(this IDbConnection connection, ISqlQuery query, Func<TFirst, TSecond, TThird, TFourth, TReturn> map, string splitOn = "", IDbTransaction? transaction = null, bool buffered = true, CancellationToken cancellationToken = default)

    Asynchronously executes a JOIN query and maps results to four entity types.

    connection: this IDbConnection
    The database connection to execute the query against.
    query: ISqlQuery
    The SQL query to compile and execute.
    map: Func<TFirst, TSecond, TThird, TFourth, TReturn>
    The mapping function that combines the four entities into the aggregate return type.
    splitOn: string
    The column names that mark the start of each subsequent entity.
    transaction: IDbTransaction?
    An optional database transaction to participate in.
    buffered: bool
    A value indicating whether to buffer the results in memory before returning.
    cancellationToken: CancellationToken
    A token that can be used to cancel the asynchronous operation.

    Returns: A task representing the asynchronous operation. The task result contains a collection of `TReturn` instances.

    Type parameters: TFirst: The first entity type representing the left side of the split.; TSecond: The second entity type.; TThird: The third entity type.; TFourth: The fourth entity type.; TReturn: The returned aggregate type.

  • methodQueryAsync<TFirst, TSecond, TThird, TReturn>
    public static async Task<IEnumerable<TReturn>> QueryAsync<TFirst, TSecond, TThird, TReturn>(this IDbConnection connection, ISqlQuery query, Func<TFirst, TSecond, TThird, TReturn> map, string splitOn = "", IDbTransaction? transaction = null, bool buffered = true, CancellationToken cancellationToken = default)

    Asynchronously executes a JOIN query and maps results to three entity types.

    connection: this IDbConnection
    The database connection to execute the query against.
    query: ISqlQuery
    The SQL query to compile and execute.
    map: Func<TFirst, TSecond, TThird, TReturn>
    The mapping function that combines the three entities into the aggregate return type.
    splitOn: string
    The column names that mark the start of each subsequent entity.
    transaction: IDbTransaction?
    An optional database transaction to participate in.
    buffered: bool
    A value indicating whether to buffer the results in memory before returning.
    cancellationToken: CancellationToken
    A token that can be used to cancel the asynchronous operation.

    Returns: A task representing the asynchronous operation. The task result contains a collection of `TReturn` instances.

    Type parameters: TFirst: The first entity type representing the left side of the split.; TSecond: The second entity type.; TThird: The third entity type.; TReturn: The returned aggregate type.

class

DapperPaginationExtensions

Assembly: EricksonLopez.SqlBuilder.Dapper
public static class DapperPaginationExtensions

Provides extension methods on `Data.IDbConnection` for executing paginated SQL queries.

Members (1)

  • methodQueryPagedAsync<T>
    public static async Task<IPagedList<T>> QueryPagedAsync<T>(this IDbConnection connection, SelectQuery<T> query, PaginationParameters parameters, bool countTotal = true, IDbTransaction? transaction = null, CancellationToken cancellationToken = default) where T : class, new()

    Executes a `SelectQuery<T>` with pagination, returning a `PagedList<T>`. If `countTotal` is true, it will execute a separate COUNT query first.

    connection: this IDbConnection
    The database connection.
    query: SelectQuery<T>
    The base select query to paginate.
    parameters: PaginationParameters
    The pagination parameters (page number, page size).
    countTotal: bool
    If `true`, executes a COUNT query to populate total count metadata.
    transaction: IDbTransaction?
    An optional transaction.
    cancellationToken: CancellationToken
    A token that can be used to cancel the asynchronous operation.

    Returns: A task representing the asynchronous operation. The task result contains a `IPagedList<T>` with the requested page and optional total count.

    Type parameters: T: The type of the returned items.

interface

IBulkStrategy

Assembly: EricksonLopez.SqlBuilder.Dapper
public interface IBulkStrategy

Defines a native strategy for performing bulk insert operations against a specific database provider.

Remarks:

Implement this interface to provide a native bulk mechanism (e.g., `SqlBulkCopy`, `NpgsqlBinaryImporter`) as an alternative to parameterized batch inserts. Register instances via `DapperExtensions.RegisterBulkStrategy`.

Members (2)

  • methodBulkInsertAsync<T>
    Task<int> BulkInsertAsync<T>(IDbConnection connection, IEnumerable<T> entities, IDbTransaction? transaction = null, CancellationToken cancellationToken = default) where T : class, new()

    Asynchronously inserts a collection of entities using a native bulk mechanism.

    connection: IDbConnection
    The database connection to use for the bulk insert.
    entities: IEnumerable<T>
    The collection of entities to insert.
    transaction: IDbTransaction?
    An optional transaction to participate in.
    cancellationToken: CancellationToken
    A token that can be used to cancel the asynchronous operation.

    Returns: A task representing the asynchronous operation. The task result contains the total number of rows inserted.

    Type parameters: T: The entity type to insert. Must have a default constructor and be a reference type.

  • methodCanHandle
    bool CanHandle(IDbConnection connection)

    Determines whether this strategy can handle the specified connection.

    connection: IDbConnection
    The active database connection to evaluate.

    Returns: `true` if this strategy supports the connection type; otherwise, `false`.

class

JsonbTypeHandler<T>

Assembly: EricksonLopez.SqlBuilder.Dapper
public sealed class JsonbTypeHandler<T> : SqlMapper.TypeHandler<T>
Inherits: SqlMapper.TypeHandler<T>

Provides a Dapper type handler for PostgreSQL JSONB columns that serializes and deserializes objects using `JsonSerializer`.

Remarks:

Type parameters: T: The type of object to serialize and deserialize.

Members (2)

  • methodParse
    public override T? Parse(object value)

    Deserializes a JSONB string value from the database back to an instance of `T`.

    value: object
    The raw database value containing the JSON string.

    Returns: The deserialized instance of `T`, or the default value when `value` is `null` or `DBNull`.

  • methodSetValue
    public override void SetValue(IDbDataParameter parameter, T? value)

    Serializes the value to a JSON string and assigns it to the parameter, also setting the JSONB database type.

    parameter: IDbDataParameter
    The database parameter to configure.
    value: T?
    The value to serialize as JSONB. When `null`, sets `DBNull.Value`.
class

PostgreSqlTypeHandlerRegistrar

Assembly: EricksonLopez.SqlBuilder.Dapper
public static class PostgreSqlTypeHandlerRegistrar

Convenience methods for registering PostgreSQL specific type handlers.

Members (2)

  • methodRegisterJsonbHandler<T>
    public static void RegisterJsonbHandler<T>()

    Registers a JSONB type handler for the specified type. Call once per type at application startup.

    Type parameters: T: The CLR type to associate with the JSONB handler.

  • methodRegisterJsonbHandlers
    public static void RegisterJsonbHandlers(params Action[] registrations)

    Executes a sequence of handler registration delegates, each registering a JSONB type handler.

    registrations: params Action[]
    One or more registration delegates, typically produced by calls to `RegisterJsonbHandler<T>`.
struct

SqlBuilderConnectionContext

Assembly: EricksonLopez.SqlBuilder.Dapper
public readonly struct SqlBuilderConnectionContext

Encapsulates a database connection with its default SQL compiler.

Members (7)

  • constructorSqlBuilderConnectionContext
    public SqlBuilderConnectionContext(IDbConnection connection)

    Initializes a new instance of the `SqlBuilderConnectionContext` struct.

    connection: IDbConnection
    The database connection to bind to this context.
  • methodDelete<T>
    public EricksonLopez.SqlBuilder.Abstractions.IDeleteFromBuilder<T> Delete<T>() where T : class, new()

    Creates a DELETE query builder for the specified entity type.

    Returns: A delete builder instance.

    Type parameters: T: The entity type.

  • methodInsert<T>
    public InsertQuery<T> Insert<T>(T entity) where T : class, new()

    Creates an INSERT query for the specified entity.

    entity: T
    The entity to insert.

    Returns: A new `InsertQuery<T>` instance.

    Type parameters: T: The entity type.

  • methodSelect<T>
    public BoundSelectQuery<T> Select<T>() where T : class, new()

    Starts a SELECT query for the specified entity type.

    Returns: A bound select query.

    Type parameters: T: The entity type.

  • methodUpdate<T>
    public EricksonLopez.SqlBuilder.Abstractions.IUpdateSetBuilder<T> Update<T>() where T : class, new()

    Creates an UPDATE query builder for the specified entity type.

    Returns: An update builder instance.

    Type parameters: T: The entity type.

  • methodUpdate<T>
    public EricksonLopez.SqlBuilder.Abstractions.IUpdateSetBuilder<T> Update<T>(T entity) where T : class, new()

    Creates an UPDATE query builder initialized with the values of the specified entity.

    entity: T
    The entity containing modified values.

    Returns: An update builder instance.

    Type parameters: T: The entity type.

  • propertyConnection
    public IDbConnection Connection { get; }

    Gets the underlying database connection.

class

SqlBuilderDapperBulkExtensions

Assembly: EricksonLopez.SqlBuilder.Dapper
public static class SqlBuilderDapperBulkExtensions

Provides Dapper extension methods for executing bulk SQL operations.

Members (1)

  • methodExecuteBulkAsync
    public static async Task<int> ExecuteBulkAsync(this IDbConnection connection, BulkSqlResult bulkResult, IDbTransaction? transaction = null, int? commandTimeout = null)

    Executes a Bulk operation asynchronously by iterating over its generated batches.

    connection: this IDbConnection
    The database connection used to execute each batch.
    bulkResult: BulkSqlResult
    The `BulkSqlResult` containing the generated SQL batches and their parameters.
    transaction: IDbTransaction?
    An optional transaction to execute within.
    commandTimeout: int?
    An optional command timeout in seconds applied to each batch.

    Returns: A task representing the asynchronous operation. The task result contains the total number of rows affected across all batches.

EricksonLopez.SqlBuilder.Dapper.Aot#

1
class

AotDapperExtensions

Assembly: EricksonLopez.SqlBuilder.Dapper.Aot
public static class AotDapperExtensions

Provides extension methods on `IDbConnection` for zero-reflection, NativeAOT-compatible SQL execution seamlessly integrated with source-generated entity parsers and pre-compiled `SqlResult`.

Members (8)

  • methodAotExecuteAsync
    public static Task<int> AotExecuteAsync(this IDbConnection connection, ISqlQuery query, ISqlCompiler compiler, IDbTransaction? transaction = null, int commandTimeout = 30, CancellationToken cancellationToken = default)

    Compiles and executes a non-query command (INSERT, UPDATE, DELETE) asynchronously without reflection.

    connection: this IDbConnection
    The database connection.
    query: ISqlQuery
    The SQL query AST builder.
    compiler: ISqlCompiler
    The dialect compiler.
    transaction: IDbTransaction?
    An optional database transaction.
    commandTimeout: int
    The command timeout in seconds.
    cancellationToken: CancellationToken
    A token that can be used to cancel the asynchronous operation.

    Returns: A task representing the asynchronous operation. The task result contains the number of rows affected.

    Exceptions: ArgumentNullException: `connection`, `query`, or `compiler` is `null`

  • methodAotExecuteAsync
    public static Task<int> AotExecuteAsync(this IDbConnection connection, SqlResult result, IDbTransaction? transaction = null, int commandTimeout = 30, CancellationToken cancellationToken = default)

    Executes a pre-compiled non-query command (INSERT, UPDATE, DELETE) asynchronously without reflection.

    connection: this IDbConnection
    The database connection.
    result: SqlResult
    The pre-compiled SQL result.
    transaction: IDbTransaction?
    An optional database transaction.
    commandTimeout: int
    The command timeout in seconds.
    cancellationToken: CancellationToken
    A token that can be used to cancel the asynchronous operation.

    Returns: A task representing the asynchronous operation. The task result contains the number of rows affected.

    Exceptions: ArgumentNullException: `connection` or `result` is `null`

  • methodAotExecuteScalarAsync<T>
    public static Task<T?> AotExecuteScalarAsync<T>(this IDbConnection connection, ISqlQuery query, ISqlCompiler compiler, IDbTransaction? transaction = null, int commandTimeout = 30, CancellationToken cancellationToken = default)

    Compiles and executes a query and returns a single scalar value asynchronously without reflection.

    connection: this IDbConnection
    The database connection.
    query: ISqlQuery
    The SQL query AST builder.
    compiler: ISqlCompiler
    The dialect compiler.
    transaction: IDbTransaction?
    An optional database transaction.
    commandTimeout: int
    The command timeout in seconds.
    cancellationToken: CancellationToken
    A token that can be used to cancel the asynchronous operation.

    Returns: A task representing the asynchronous operation. The task result contains the scalar result converted to `T`, or `default`.

    Type parameters: T: The scalar return type. Exceptions: ArgumentNullException: `connection`, `query`, or `compiler` is `null`

  • methodAotExecuteScalarAsync<T>
    public static Task<T?> AotExecuteScalarAsync<T>(this IDbConnection connection, SqlResult result, IDbTransaction? transaction = null, int commandTimeout = 30, CancellationToken cancellationToken = default)

    Executes a pre-compiled query and returns a single scalar value asynchronously without reflection.

    connection: this IDbConnection
    The database connection.
    result: SqlResult
    The pre-compiled SQL result.
    transaction: IDbTransaction?
    An optional database transaction.
    commandTimeout: int
    The command timeout in seconds.
    cancellationToken: CancellationToken
    A token that can be used to cancel the asynchronous operation.

    Returns: A task representing the asynchronous operation. The task result contains the scalar result converted to `T`, or `default`.

    Type parameters: T: The scalar return type. Exceptions: ArgumentNullException: `connection` or `result` is `null`

  • methodAotQueryAsync<T>
    public static Task<IReadOnlyList<T>> AotQueryAsync<T>(this IDbConnection connection, ISqlQuery query, ISqlCompiler compiler, Func<IDataReader, T> mapper, IDbTransaction? transaction = null, int commandTimeout = 30, CancellationToken cancellationToken = default)

    Compiles and executes a query asynchronously without reflection, mapping rows to `T` via the provided reader parser.

    connection: this IDbConnection
    The database connection.
    query: ISqlQuery
    The SQL query AST builder.
    compiler: ISqlCompiler
    The dialect compiler.
    mapper: Func<IDataReader, T>
    The reader parser delegate.
    transaction: IDbTransaction?
    An optional database transaction.
    commandTimeout: int
    The command timeout in seconds.
    cancellationToken: CancellationToken
    A token that can be used to cancel the asynchronous operation.

    Returns: A task representing the asynchronous operation. The task result contains a read-only list of mapped `T` instances.

    Type parameters: T: The result entity type. Exceptions: ArgumentNullException: `connection`, `query`, `compiler`, or `mapper` is `null`

  • methodAotQueryAsync<T>
    public static Task<IReadOnlyList<T>> AotQueryAsync<T>(this IDbConnection connection, SqlResult result, Func<IDataReader, T> mapper, IDbTransaction? transaction = null, int commandTimeout = 30, CancellationToken cancellationToken = default)

    Executes a pre-compiled query asynchronously without reflection, mapping rows to `T` via the provided reader parser.

    connection: this IDbConnection
    The database connection.
    result: SqlResult
    The pre-compiled SQL result.
    mapper: Func<IDataReader, T>
    The reader parser delegate.
    transaction: IDbTransaction?
    An optional database transaction.
    commandTimeout: int
    The command timeout in seconds.
    cancellationToken: CancellationToken
    A token that can be used to cancel the asynchronous operation.

    Returns: A task representing the asynchronous operation. The task result contains a read-only list of mapped `T` instances.

    Type parameters: T: The result entity type. Exceptions: ArgumentNullException: `connection`, `result`, or `mapper` is `null`

  • methodAotQueryFirstOrDefaultAsync<T>
    public static async Task<T?> AotQueryFirstOrDefaultAsync<T>(this IDbConnection connection, ISqlQuery query, ISqlCompiler compiler, Func<IDataReader, T> mapper, IDbTransaction? transaction = null, int commandTimeout = 30, CancellationToken cancellationToken = default)

    Compiles and executes a query asynchronously without reflection, returning the first row mapped to `T` or default.

    connection: this IDbConnection
    The database connection.
    query: ISqlQuery
    The SQL query AST builder.
    compiler: ISqlCompiler
    The dialect compiler.
    mapper: Func<IDataReader, T>
    The reader parser delegate.
    transaction: IDbTransaction?
    An optional database transaction.
    commandTimeout: int
    The command timeout in seconds.
    cancellationToken: CancellationToken
    A token that can be used to cancel the asynchronous operation.

    Returns: A task representing the asynchronous operation. The task result contains the first mapped `T` instance, or `default` if empty.

    Type parameters: T: The result entity type. Exceptions: ArgumentNullException: `connection`, `query`, `compiler`, or `mapper` is `null`

  • methodAotQueryFirstOrDefaultAsync<T>
    public static async Task<T?> AotQueryFirstOrDefaultAsync<T>(this IDbConnection connection, SqlResult result, Func<IDataReader, T> mapper, IDbTransaction? transaction = null, int commandTimeout = 30, CancellationToken cancellationToken = default)

    Executes a pre-compiled query asynchronously without reflection, returning the first row mapped to `T` or default.

    connection: this IDbConnection
    The database connection.
    result: SqlResult
    The pre-compiled SQL result.
    mapper: Func<IDataReader, T>
    The reader parser delegate.
    transaction: IDbTransaction?
    An optional database transaction.
    commandTimeout: int
    The command timeout in seconds.
    cancellationToken: CancellationToken
    A token that can be used to cancel the asynchronous operation.

    Returns: A task representing the asynchronous operation. The task result contains the first mapped `T` instance, or `default` if empty.

    Type parameters: T: The result entity type. Exceptions: ArgumentNullException: `connection`, `result`, or `mapper` is `null`

EricksonLopez.SqlBuilder.Filters#

2
class

FilterExtensions

Assembly: EricksonLopez.SqlBuilder
public static class FilterExtensions

Provides extension methods for applying `ISqlFilter<TEntity>` instances to queries.

Members (2)

  • methodApplyFilter<TEntity>
    public static SelectQuery<TEntity> ApplyFilter<TEntity>(this SelectQuery<TEntity> query, ISqlFilter<TEntity>? filter) where TEntity : class, new()

    Applies the specified filter to the query.

    query: this SelectQuery<TEntity>
    The query to modify.
    filter: ISqlFilter<TEntity>?
    The filter to apply, or `null` to skip filtering.

    Returns: A new `SelectQuery<TEntity>` instance containing the applied filter, or the original query if the filter is null.

    Type parameters: TEntity: The type of the entity being queried.

  • methodApplyFilters<TEntity>
    public static SelectQuery<TEntity> ApplyFilters<TEntity>(this SelectQuery<TEntity> query, params ISqlFilter<TEntity>[] filters) where TEntity : class, new()

    Applies a collection of filters sequentially to the query.

    query: this SelectQuery<TEntity>
    The query to modify.
    filters: params ISqlFilter<TEntity>[]
    An array of filters to apply. Null filters in the array are ignored.

    Returns: A new `SelectQuery<TEntity>` instance containing all applied filters.

    Type parameters: TEntity: The type of the entity being queried.

interface

ISqlFilter<TEntity>

Assembly: EricksonLopez.SqlBuilder
public interface ISqlFilter<TEntity> where TEntity : class, new()

Defines a contract for applying modular, reusable filtering logic to a `SelectQuery<TEntity>`.

Remarks:

Type parameters: TEntity: The type of the entity being queried.

Members (1)

  • methodApply
    SelectQuery<TEntity> Apply(SelectQuery<TEntity> query)

    Applies the filtering logic to the specified query.

    query: SelectQuery<TEntity>
    The query to modify.

    Returns: A new `SelectQuery<TEntity>` instance containing the applied filters.

EricksonLopez.SqlBuilder.MariaDb#

3
class

MariaDbCompiler

Assembly: EricksonLopez.SqlBuilder.MariaDb
public class MariaDbCompiler : MySqlCompiler
Inherits: MySqlCompiler

Provides MariaDB-specific compilation and dialect rules.

Remarks:

`MariaDbCompiler` extends `MySqlCompiler` with native MariaDB features: - Native `RETURNING` clause support (MariaDB 10.5+). All MySQL-compatible features are inherited: backtick quoting, `LIMIT/OFFSET`, `ON DUPLICATE KEY UPDATE`, multi-table DELETE/UPDATE with JOINs, and `NULLS FIRST/LAST` emulation via `CASE WHEN`.

Members (0)

This type declares 0 public members (e.g. marker interface or empty enum/record).

class

MariaDbExtensions

Assembly: EricksonLopez.SqlBuilder.MariaDb
public static class MariaDbExtensions

Provides extension methods for MariaDB-specific SQL features.

Remarks:

MariaDB uses the same backtick identifier quoting and SQL syntax as MySQL, so these extensions mirror those found in `MySqlExtensions` but are namespaced to `MariaDb` for clarity and discoverability.

Members (6)

  • methodBuildOnDuplicateKeyUpdate
    public static string BuildOnDuplicateKeyUpdate(params string[] columns)

    Generates the raw `ON DUPLICATE KEY UPDATE` assignment string for a set of columns.

    columns: params string[]
    The columns to update on conflict.

    Returns: The formatted SQL assignment clause.

    Example:

    MariaDbExtensions.BuildOnDuplicateKeyUpdate("name", "email", "updated_at")
    // → "`name` = VALUES(`name`), `email` = VALUES(`email`), `updated_at` = VALUES(`updated_at`)"
  • methodPage<T>
    public static SelectQuery<T> Page<T>(this SelectQuery<T> query, int pageNumber, int pageSize) where T : class, new()

    Appends `LIMIT / OFFSET` pagination for a given 1-based page number and page size.

    query: this SelectQuery<T>
    The SELECT query to paginate.
    pageNumber: int
    The 1-based page number (values ≤ 0 default to page 1).
    pageSize: int
    The number of rows per page (values ≤ 0 default to 10).

    Returns: A new `SelectQuery<T>` with the LIMIT and OFFSET applied.

    Type parameters: T: The entity type.

  • methodSelectJsonArrayAgg<T>
    public static SelectQuery<T> SelectJsonArrayAgg<T>(this SelectQuery<T> query, string column, string alias) where T : class, new()

    Adds a SELECT clause using `JSON_ARRAYAGG` to aggregate column values into a JSON array. Generates: `JSON_ARRAYAGG(`column`) AS `alias``.

    query: this SelectQuery<T>
    The SQL query AST builder.
    column: string
    The column to aggregate into a JSON array.
    alias: string
    The alias name for the aggregated column.

    Returns: A new `SelectQuery<T>` with the JSON_ARRAYAGG selection applied.

    Type parameters: T: The entity type.

  • methodSelectJsonObjectAgg<T>
    public static SelectQuery<T> SelectJsonObjectAgg<T>(this SelectQuery<T> query, string keyColumn, string valueColumn, string alias) where T : class, new()

    Adds a SELECT clause using `JSON_OBJECTAGG` to aggregate key-value pairs into a JSON object. Generates: `JSON_OBJECTAGG(`keyColumn`, `valueColumn`) AS `alias``.

    query: this SelectQuery<T>
    The SQL query AST builder.
    keyColumn: string
    The column whose values will become JSON keys.
    valueColumn: string
    The column whose values will become JSON property values.
    alias: string
    The alias name for the aggregated column.

    Returns: A new `SelectQuery<T>` with the JSON_OBJECTAGG selection applied.

    Type parameters: T: The entity type.

  • methodWhereFullText<T>
    public static SelectQuery<T> WhereFullText<T>(this SelectQuery<T> query, string searchTerm, params string[] columns) where T : class, new()

    Adds a `WHERE MATCH AGAINST` full-text search clause. Generates: `WHERE MATCH(`col1`, `col2`) AGAINST (@p0 IN BOOLEAN MODE)`.

    query: this SelectQuery<T>
    The SQL query AST builder.
    searchTerm: string
    The full-text search query string.
    columns: params string[]
    The columns included in the full-text search index.

    Returns: A new `SelectQuery<T>` with the full-text search condition applied.

    The full-text index must exist on the specified columns. Example DDL: `CREATE FULLTEXT INDEX ft_products ON products(name, description);`. Type parameters: T: The entity type.

  • methodWhereJsonExtract<T>
    public static SelectQuery<T> WhereJsonExtract<T>(this SelectQuery<T> query, string column, string path, object value) where T : class, new()

    Adds a raw WHERE clause using MariaDB `JSON_EXTRACT` function. Generates: `WHERE JSON_EXTRACT(`column`, '$.path') = @p0`.

    query: this SelectQuery<T>
    The SQL query AST builder.
    column: string
    The column name containing the JSON document.
    path: string
    The JSON path expression (e.g. `"$.status"`).
    value: object
    The expected value to match.

    Returns: A new `SelectQuery<T>` with the JSON_EXTRACT condition applied.

    Type parameters: T: The entity type. Example:

    query.WhereJsonExtract("metadata", "$.status", "active")
    // → WHERE JSON_EXTRACT(`metadata`, '$.status') = @p0
class

MariaDbRenderer

Assembly: EricksonLopez.SqlBuilder.MariaDb
public class MariaDbRenderer : MySqlRenderer
Inherits: MySqlRenderer

Provides AOT-optimized SQL rendering for MariaDB.

Remarks:

Inherits from `MySqlRenderer`. MariaDB uses the same bulk operation strategy as MySQL (via `MySqlConnector`), so all bulk methods delegate to the MySQL renderer behavior.

Members (6)

  • constructorMariaDbRenderer
    public MariaDbRenderer(ISqlCompiler compiler)

    Initializes a new instance of the `MariaDbRenderer` class.

    compiler: ISqlCompiler
    The MariaDB compiler instance.
  • methodRenderBulkInsert<T>
    public override BulkSqlResult RenderBulkInsert<T>(IEnumerable<T> entities, List<EricksonLopez.SqlBuilder.ColumnSelection.IColumnSelectionRule<T>> rules, int batchSize)

    Inherits documentation from base type or interface.

    entities: IEnumerable<T>
    rules: List<EricksonLopez.SqlBuilder.ColumnSelection.IColumnSelectionRule<T>>
    batchSize: int
  • methodRenderBulkInsertIgnore<T>
    public override BulkSqlResult RenderBulkInsertIgnore<T>(IEnumerable<T> entities, List<EricksonLopez.SqlBuilder.ColumnSelection.IColumnSelectionRule<T>> rules, int batchSize)

    Inherits documentation from base type or interface.

    entities: IEnumerable<T>
    rules: List<EricksonLopez.SqlBuilder.ColumnSelection.IColumnSelectionRule<T>>
    batchSize: int
  • methodRenderBulkMerge<T>
    public override BulkSqlResult RenderBulkMerge<T>(IEnumerable<T> entities, List<EricksonLopez.SqlBuilder.ColumnSelection.IColumnSelectionRule<T>> rules, int batchSize)

    Inherits documentation from base type or interface.

    entities: IEnumerable<T>
    rules: List<EricksonLopez.SqlBuilder.ColumnSelection.IColumnSelectionRule<T>>
    batchSize: int
  • methodRenderBulkUpdate<T>
    public override BulkSqlResult RenderBulkUpdate<T>(IEnumerable<T> entities, List<EricksonLopez.SqlBuilder.ColumnSelection.IColumnSelectionRule<T>> rules, int batchSize)

    Inherits documentation from base type or interface.

    entities: IEnumerable<T>
    rules: List<EricksonLopez.SqlBuilder.ColumnSelection.IColumnSelectionRule<T>>
    batchSize: int
  • methodRenderBulkUpsert<T>
    public override BulkSqlResult RenderBulkUpsert<T>(IEnumerable<T> entities, List<EricksonLopez.SqlBuilder.ColumnSelection.IColumnSelectionRule<T>> rules, int batchSize)

    Inherits documentation from base type or interface.

    entities: IEnumerable<T>
    rules: List<EricksonLopez.SqlBuilder.ColumnSelection.IColumnSelectionRule<T>>
    batchSize: int

EricksonLopez.SqlBuilder.Metadata#

6
enum

ColumnFlags

Assembly: EricksonLopez.SqlBuilder
public enum ColumnFlags

Specifies the characteristics of a database column mapped from an entity property.

Members (6)

  • fieldComputed
    Computed = 1<<4

    Indicates that the column is a computed column.

  • fieldGenerated
    Generated = 1<<1

    Indicates that the column value is generated by the database upon insertion.

  • fieldGeneratedAlways
    GeneratedAlways = 1<<3

    Indicates that the column is always generated by the database (e.g. Identity).

  • fieldNone
    None = 0

    Indicates no special characteristics.

  • fieldNullable
    Nullable = 1<<2

    Indicates that the column allows null values.

  • fieldPrimaryKey
    PrimaryKey = 1<<0

    Indicates that the column is part of the primary key.

class

ColumnMetadata

Assembly: EricksonLopez.SqlBuilder
public sealed class ColumnMetadata

Represents metadata for a single entity property mapped to a database column.

Members (4)

  • constructorColumnMetadata
    public ColumnMetadata(string columnName, string propertyName, ColumnFlags flags)

    Initializes a new instance of the `ColumnMetadata` class.

    columnName: string
    The name of the database column.
    propertyName: string
    The name of the entity property.
    flags: ColumnFlags
    The characteristics of the column.
  • propertyColumnName
    public string ColumnName { get; }

    Gets the name of the column in the database.

  • propertyFlags
    public ColumnFlags Flags { get; }

    Gets the bitwise flags describing the column's characteristics.

  • propertyPropertyName
    public string PropertyName { get; }

    Gets the name of the property on the entity class.

record

ColumnToken

Assembly: EricksonLopez.SqlBuilder
public readonly record struct ColumnToken(int Index, string Name)

Represents a lightweight identifier for a specific column within an entity's metadata structure.

Members (3)

  • constructorColumnToken
    public ColumnToken(int Index, string Name)

    Initializes a new instance of ColumnToken.

    Index: int
    The zero-based index of the column in the entity's metadata array.
    Name: string
    The name of the column.
  • propertyIndex
    public int Index { get; init; }

    The zero-based index of the column in the entity's metadata array.

  • propertyName
    public string Name { get; init; }

    The name of the column.

class

EntityMetadataResolver

Assembly: EricksonLopez.SqlBuilder
public static class EntityMetadataResolver

Provides efficient and AOT-friendly access to entity metadata generated by the Source Generator.

Members (1)

  • methodGet<T>
    public static IEntityMetadata<T> Get<T>() where T : IEntityMetadataProvider<T>

    Retrieves the static metadata instance for the specified entity type.

    Returns: The `IEntityMetadata<T>` instance associated with the entity.

    By utilizing `IEntityMetadataProvider<T>`, the JIT/AOT compiler can completely devirtualize and inline this call, achieving a Zero-Cost Abstraction. Type parameters: T: The type of the entity whose metadata is being retrieved.

interface

IEntityMetadataProvider<T>

Assembly: EricksonLopez.SqlBuilder
public interface IEntityMetadataProvider<T>

Defines a contract for entity types that expose AOT-compatible static metadata.

Remarks:

Type parameters: T: The entity type.

Members (1)

  • propertyMetadata
    static abstract IEntityMetadata<T> Metadata { get; }

    Gets the static, AOT-optimized metadata instance for the entity type.

interface

IEntityMetadata<T>

Assembly: EricksonLopez.SqlBuilder
public interface IEntityMetadata<T>

Defines the structure of metadata required to perform zero-allocation SQL operations on an entity type.

Remarks:

Type parameters: T: The type of the entity this metadata describes.

Members (6)

  • methodExtractColumnArrays
    void ExtractColumnArrays(ReadOnlySpan<T> entities, ReadOnlySpan<bool> activeColumns, EricksonLopez.SqlBuilder.Abstractions.IParameterManager parameters)

    Transposes a batch of entities into individual column arrays and registers them with the parameter manager.

    entities: ReadOnlySpan<T>
    A read-only span containing the batch of entities to transpose.
    activeColumns: ReadOnlySpan<bool>
    A bitmask span indicating which columns to include in the extraction.
    parameters: EricksonLopez.SqlBuilder.Abstractions.IParameterManager
    The parameter manager where the resulting arrays will be registered.

    Supports highly optimized bulk operations based on parametric arrays (e.g., PostgreSQL UNNEST).

  • methodGetBoxedValue
    object? GetBoxedValue(T entity, int columnIndex)

    Retrieves the value of the specified column from the given entity instance, boxed as an object.

    entity: T
    The entity instance to extract the value from.
    columnIndex: int
    The index of the column within the `Columns` span.

    Returns: The property value as an `object`.

  • methodIsDefault
    bool IsDefault(T entity, int columnIndex)

    Determines whether the value of the specified column for the given entity instance is its default value.

    entity: T
    The entity instance to inspect.
    columnIndex: int
    The index of the column within the `Columns` span.

    Returns: `true` if the property value equals the default for its type; otherwise, `false`.

  • methodIsNull
    bool IsNull(T entity, int columnIndex)

    Determines whether the value of the specified column for the given entity instance is `null`.

    entity: T
    The entity instance to inspect.
    columnIndex: int
    The index of the column within the `Columns` span.

    Returns: `true` if the property value is null; otherwise, `false`.

  • propertyColumns
    ReadOnlySpan<ColumnMetadata> Columns { get; }

    Gets a read-only span of metadata for all columns mapped to the entity.

  • propertyTableName
    string TableName { get; }

    Gets the name of the database table associated with the entity.

EricksonLopez.SqlBuilder.MySql#

5
class

MySqlBatchStrategy

Assembly: EricksonLopez.SqlBuilder.MySql
public static class MySqlBatchStrategy

Provides a high-performance native bulk INSERT strategy for MySQL using multi-row `INSERT INTO ... VALUES (...), (...)` batch statements via `MySqlBulkCopy`.

Remarks:

`MySqlBulkCopy` uses the MySQL LOAD DATA LOCAL INFILE protocol internally, which is the fastest available insertion path for large datasets in MySQL/MariaDB. For smaller datasets, falls back to multi-row INSERT batching. Requires `MySqlConnection` from the `MySqlConnector` package.

Members (2)

  • methodBulkInsertAsync<T>
    public static Task<BulkInsertResult<T>> BulkInsertAsync<T>(IDbConnection connection, IEnumerable<T> entities, BulkOptions? options = null, IDbTransaction? transaction = null, CancellationToken cancellationToken = default) where T : IStaticEntityMetadata<T>

    Bulk-inserts a collection of entities using a generic database connection.

    connection: IDbConnection
    An open database connection (must be a `MySqlConnection`).
    entities: IEnumerable<T>
    The entities to insert.
    options: BulkOptions?
    Optional bulk operation options.
    transaction: IDbTransaction?
    An optional database transaction.
    cancellationToken: CancellationToken
    A token that can be used to cancel the asynchronous operation.

    Returns: A task representing the asynchronous operation. The task result contains a `BulkInsertResult<T>` with the total number of rows inserted.

    Type parameters: T: The entity type. Must implement `IStaticEntityMetadata<T>`. Exceptions: InvalidOperationException: `connection` is not a `MySqlConnection`

  • methodBulkInsertAsync<T>
    public static async Task<BulkInsertResult<T>> BulkInsertAsync<T>(MySqlConnection connection, IEnumerable<T> entities, BulkOptions? options = null, MySqlTransaction? transaction = null, CancellationToken cancellationToken = default) where T : IStaticEntityMetadata<T>

    Bulk-inserts a collection of entities into the MySQL table associated with `T` using `MySqlBulkCopy`.

    connection: MySqlConnection
    An open `MySqlConnection`.
    entities: IEnumerable<T>
    The entities to insert.
    options: BulkOptions?
    Optional bulk operation options.
    transaction: MySqlTransaction?
    An optional open `MySqlTransaction` to enlist.
    cancellationToken: CancellationToken
    A token that can be used to cancel the asynchronous operation.

    Returns: A task representing the asynchronous operation. The task result contains a `BulkInsertResult<T>` with the total number of rows inserted.

    Type parameters: T: The entity type. Must implement `IStaticEntityMetadata<T>`. Exceptions: ArgumentNullException: `connection` or `entities` is `null`

class

MySqlBulkMergeStrategy

Assembly: EricksonLopez.SqlBuilder.MySql
public static class MySqlBulkMergeStrategy

Provides a high-performance native bulk MERGE (INSERT + UPDATE) strategy for MySQL/MariaDB using `INSERT INTO ... ON DUPLICATE KEY UPDATE`.

Remarks:

MySQL and MariaDB support `ON DUPLICATE KEY UPDATE` as a native upsert mechanism. This strategy builds multi-row INSERT statements with upsert semantics.

Members (2)

  • methodBulkMergeAsync<T>
    public static Task<BulkInsertResult<T>> BulkMergeAsync<T>(IDbConnection connection, IEnumerable<T> entities, BulkOptions? options = null, IDbTransaction? transaction = null, CancellationToken cancellationToken = default) where T : IStaticEntityMetadata<T>

    Bulk-merges a collection of entities using a generic database connection.

    connection: IDbConnection
    An open database connection (must be a `MySqlConnection`).
    entities: IEnumerable<T>
    The entities to merge.
    options: BulkOptions?
    Optional bulk options (batch size, timeout).
    transaction: IDbTransaction?
    An optional database transaction.
    cancellationToken: CancellationToken
    A token that can be used to cancel the asynchronous operation.

    Returns: A task representing the asynchronous operation. The task result contains a `BulkInsertResult<T>` with total rows affected.

    Type parameters: T: The entity type. Must implement `IStaticEntityMetadata<T>`. Exceptions: InvalidOperationException: `connection` is not a `MySqlConnection`

  • methodBulkMergeAsync<T>
    public static async Task<BulkInsertResult<T>> BulkMergeAsync<T>(MySqlConnection connection, IEnumerable<T> entities, BulkOptions? options = null, MySqlTransaction? transaction = null, CancellationToken cancellationToken = default) where T : IStaticEntityMetadata<T>

    Bulk-merges a collection of entities into the MySQL table associated with `T` using `INSERT INTO ... VALUES (...) ON DUPLICATE KEY UPDATE ...`.

    connection: MySqlConnection
    An open `MySqlConnection`.
    entities: IEnumerable<T>
    The entities to merge.
    options: BulkOptions?
    Optional bulk options (batch size, timeout).
    transaction: MySqlTransaction?
    An optional `MySqlTransaction`.
    cancellationToken: CancellationToken
    A token that can be used to cancel the asynchronous operation.

    Returns: A task representing the asynchronous operation. The task result contains a `BulkInsertResult<T>` with total rows affected.

    Type parameters: T: The entity type. Must implement `IStaticEntityMetadata<T>`. Exceptions: ArgumentNullException: `connection` or `entities` is `null`

class

MySqlCompiler

Assembly: EricksonLopez.SqlBuilder.MySql
public class MySqlCompiler : SqlCompilerBase
Inherits: SqlCompilerBase

Provides MySQL specific compilation and dialect rules.

Members (3)

  • constructorMySqlCompiler
    public MySqlCompiler()

    Initializes a new instance of the `MySqlCompiler` class.

  • methodEscapeIdentifier
    public override string EscapeIdentifier(string identifier)

    Escapes a raw SQL identifier string.

    identifier: string
    The raw identifier to escape.

    Returns: The escaped identifier string.

  • methodEscapeIdentifier
    public override void EscapeIdentifier(System.Text.StringBuilder sb, System.ReadOnlySpan<char> identifier)

    Escapes a raw identifier span and appends it directly to the provided `StringBuilder`.

    sb: System.Text.StringBuilder
    The string builder to append the escaped identifier to.
    identifier: System.ReadOnlySpan<char>
    The raw identifier span.
class

MySqlExtensions

Assembly: EricksonLopez.SqlBuilder.MySql
public static class MySqlExtensions

Provides extension methods for MySQL-specific SQL features.

Members (6)

  • methodBuildOnDuplicateKeyUpdate
    public static string BuildOnDuplicateKeyUpdate(params string[] columns)

    Generates the raw ON DUPLICATE KEY UPDATE assignment string for a set of columns.

    columns: params string[]
    The columns to update on conflict.

    Returns: The formatted SQL assignment clause.

  • methodPage<T>
    public static SelectQuery<T> Page<T>(this SelectQuery<T> query, int pageNumber, int pageSize) where T : class, new()

    Appends LIMIT / OFFSET pagination for a given 1-based page number and page size.

    query: this SelectQuery<T>
    The SQL query AST builder.
    pageNumber: int
    The 1-based page number.
    pageSize: int
    The number of items per page.

    Returns: A new `SelectQuery<T>` with the LIMIT and OFFSET applied.

    Type parameters: T: The entity type.

  • methodSelectJsonArrayAgg<T>
    public static SelectQuery<T> SelectJsonArrayAgg<T>(this SelectQuery<T> query, string column, string alias) where T : class, new()

    Adds a SELECT clause using JSON_ARRAYAGG to aggregate column values into a JSON array.

    query: this SelectQuery<T>
    The SQL query AST builder.
    column: string
    The column to aggregate into a JSON array.
    alias: string
    The alias name for the aggregated column.

    Returns: A new `SelectQuery<T>` with the JSON_ARRAYAGG selection applied.

    Type parameters: T: The entity type.

  • methodSelectJsonObjectAgg<T>
    public static SelectQuery<T> SelectJsonObjectAgg<T>(this SelectQuery<T> query, string keyColumn, string valueColumn, string alias) where T : class, new()

    Adds a SELECT clause using JSON_OBJECTAGG to aggregate key-value pairs into a JSON object.

    query: this SelectQuery<T>
    The SQL query AST builder.
    keyColumn: string
    The column whose values will become JSON keys.
    valueColumn: string
    The column whose values will become JSON property values.
    alias: string
    The alias name for the aggregated column.

    Returns: A new `SelectQuery<T>` with the JSON_OBJECTAGG selection applied.

    Type parameters: T: The entity type.

  • methodWhereFullText<T>
    public static SelectQuery<T> WhereFullText<T>(this SelectQuery<T> query, string searchTerm, params string[] columns) where T : class, new()

    Adds a WHERE MATCH AGAINST full-text search clause in boolean mode.

    query: this SelectQuery<T>
    The SQL query AST builder.
    searchTerm: string
    The full-text search query string.
    columns: params string[]
    The columns included in the full-text search index.

    Returns: A new `SelectQuery<T>` with the full-text search condition applied.

    Type parameters: T: The entity type.

  • methodWhereJsonExtract<T>
    public static SelectQuery<T> WhereJsonExtract<T>(this SelectQuery<T> query, string column, string path, object value) where T : class, new()

    Adds a raw WHERE clause using MySQL JSON_EXTRACT function.

    query: this SelectQuery<T>
    The SQL query AST builder.
    column: string
    The column name containing the JSON document.
    path: string
    The JSON path expression (e.g. `"$.status"`).
    value: object
    The expected value to match.

    Returns: A new `SelectQuery<T>` with the JSON_EXTRACT condition applied.

    Type parameters: T: The entity type.

class

MySqlRenderer

Assembly: EricksonLopez.SqlBuilder.MySql
public class MySqlRenderer : AotSqlRendererBase
Inherits: AotSqlRendererBase

Provides AOT-optimized SQL rendering for MySQL.

Members (6)

  • constructorMySqlRenderer
    public MySqlRenderer(ISqlCompiler compiler)

    Initializes a new instance of the `MySqlRenderer` class.

    compiler: ISqlCompiler
    The SQL compiler associated with this renderer.
  • methodRenderBulkInsert<T>
    public override BulkSqlResult RenderBulkInsert<T>(IEnumerable<T> entities, List<EricksonLopez.SqlBuilder.ColumnSelection.IColumnSelectionRule<T>> rules, int batchSize)

    Renders a batch of bulk INSERT statements for a collection of entities.

    entities: IEnumerable<T>
    The collection of entities to insert.
    rules: List<EricksonLopez.SqlBuilder.ColumnSelection.IColumnSelectionRule<T>>
    The column selection rules applied to the operation.
    batchSize: int
    The maximum number of entities to process per batch.

    Returns: A `Operations.BulkSqlResult` containing the generated batches.

    Type parameters: T: The type of the entities.

  • methodRenderBulkInsertIgnore<T>
    public override BulkSqlResult RenderBulkInsertIgnore<T>(IEnumerable<T> entities, List<EricksonLopez.SqlBuilder.ColumnSelection.IColumnSelectionRule<T>> rules, int batchSize)

    Renders a batch of bulk INSERT IGNORE statements for a collection of entities.

    entities: IEnumerable<T>
    The collection of entities to insert.
    rules: List<EricksonLopez.SqlBuilder.ColumnSelection.IColumnSelectionRule<T>>
    The column selection rules applied to the operation.
    batchSize: int
    The maximum number of entities to process per batch.

    Returns: A `Operations.BulkSqlResult` containing the generated batches.

    Type parameters: T: The type of the entities.

  • methodRenderBulkMerge<T>
    public override BulkSqlResult RenderBulkMerge<T>(IEnumerable<T> entities, List<EricksonLopez.SqlBuilder.ColumnSelection.IColumnSelectionRule<T>> rules, int batchSize)

    Renders a batch of bulk MERGE statements for a collection of entities.

    entities: IEnumerable<T>
    The collection of entities to merge.
    rules: List<EricksonLopez.SqlBuilder.ColumnSelection.IColumnSelectionRule<T>>
    The column selection rules applied to the operation.
    batchSize: int
    The maximum number of entities to process per batch.

    Returns: A `Operations.BulkSqlResult` containing the generated batches.

    Type parameters: T: The type of the entities.

  • methodRenderBulkUpdate<T>
    public override BulkSqlResult RenderBulkUpdate<T>(IEnumerable<T> entities, List<EricksonLopez.SqlBuilder.ColumnSelection.IColumnSelectionRule<T>> rules, int batchSize)

    Renders a batch of bulk UPDATE statements for a collection of entities.

    entities: IEnumerable<T>
    The collection of entities to update.
    rules: List<EricksonLopez.SqlBuilder.ColumnSelection.IColumnSelectionRule<T>>
    The column selection rules applied to the operation.
    batchSize: int
    The maximum number of entities to process per batch.

    Returns: A `Operations.BulkSqlResult` containing the generated batches.

    Type parameters: T: The type of the entities.

  • methodRenderBulkUpsert<T>
    public override BulkSqlResult RenderBulkUpsert<T>(IEnumerable<T> entities, List<EricksonLopez.SqlBuilder.ColumnSelection.IColumnSelectionRule<T>> rules, int batchSize)

    Renders a batch of bulk UPSERT statements for a collection of entities.

    entities: IEnumerable<T>
    The collection of entities to upsert.
    rules: List<EricksonLopez.SqlBuilder.ColumnSelection.IColumnSelectionRule<T>>
    The column selection rules applied to the operation.
    batchSize: int
    The maximum number of entities to process per batch.

    Returns: A `Operations.BulkSqlResult` containing the generated batches.

    Type parameters: T: The type of the entities.

EricksonLopez.SqlBuilder.OpenTelemetry#

1
class

SqlBuilderInstrumentation

Assembly: EricksonLopez.SqlBuilder.OpenTelemetry
public static class SqlBuilderInstrumentation

Provides OpenTelemetry instrumentation support for SQL query tracing.

Members (3)

  • methodResolveDbSystem
    public static string ResolveDbSystem(ISqlCompiler? compiler)

    Resolves the OpenTelemetry standard `db.system` attribute from the compiler implementation.

    compiler: ISqlCompiler?
    The SQL compiler instance.

    Returns: The standardized database system identifier (e.g., `"mssql"`, `"postgresql"`, `"mysql"`, `"sqlite"`, `"oracle"`).

  • methodStartQueryActivity
    public static Activity? StartQueryActivity(ISqlQuery query, string databaseName = "", ISqlCompiler? compiler = null)

    Starts an OpenTelemetry `Activity` representing the execution of the specified SQL query.

    query: ISqlQuery
    The SQL query being executed.
    databaseName: string
    The name of the target database. Defaults to `"Unknown"` when not provided.
    compiler: ISqlCompiler?
    The optional SQL compiler to deduce the dialect-specific `db.system` semantic tag.

    Returns: The started `Activity` if there is an active listener for the source; otherwise, `null`.

  • fieldActivitySourceName
    public const string ActivitySourceName

    Gets the name of the `Diagnostics.ActivitySource` used to emit SQL query traces.

EricksonLopez.SqlBuilder.Oracle#

5
class

OracleBulkCopyStrategy

Assembly: EricksonLopez.SqlBuilder.Oracle
public static class OracleBulkCopyStrategy

Provides a high-performance native bulk INSERT strategy for Oracle Database using `OracleBulkCopy` (Oracle Direct Path load API).

Remarks:

This strategy streams entities directly through `OracleEntityDataReader<T>` into `OracleBulkCopy` without intermediate `DataTable` materialization or runtime reflection. Requires an `OracleConnection` from `Oracle.ManagedDataAccess.Core`.

Members (5)

  • methodBulkInsert<T>
    public static BulkInsertResult<T> BulkInsert<T>(IDbConnection connection, IEnumerable<T> entities, BulkOptions? options = null, IDbTransaction? transaction = null, Action<OracleBulkCopy>? configure = null) where T : IStaticEntityMetadata<T>

    Synchronously bulk-inserts a collection of entities using a generic database connection.

    connection: IDbConnection
    A database connection (must be an `OracleConnection`).
    entities: IEnumerable<T>
    The entities to insert.
    options: BulkOptions?
    Optional bulk operation options.
    transaction: IDbTransaction?
    An optional database transaction (must be an `OracleTransaction` if provided).
    configure: Action<OracleBulkCopy>?
    An optional delegate to configure the `OracleBulkCopy` instance before execution.

    Returns: A `BulkInsertResult<T>` containing the total number of rows inserted.

    Type parameters: T: The entity type. Must implement `IStaticEntityMetadata<T>`. Exceptions: ArgumentNullException: `connection` or `entities` is `null`.; InvalidOperationException: `connection` is not an `OracleConnection`, or `transaction` is not an `OracleTransaction`.

  • methodBulkInsert<T>
    public static BulkInsertResult<T> BulkInsert<T>(OracleConnection connection, IEnumerable<T> entities, BulkOptions? options = null, OracleTransaction? transaction = null, Action<OracleBulkCopy>? configure = null) where T : IStaticEntityMetadata<T>

    Synchronously bulk-inserts a collection of entities into the Oracle table associated with `T` using `OracleBulkCopy`.

    connection: OracleConnection
    An `OracleConnection` instance.
    entities: IEnumerable<T>
    The entities to insert.
    options: BulkOptions?
    Optional bulk operation options. Defaults to `BulkOptions.Default`.
    transaction: OracleTransaction?
    An optional `OracleTransaction` associated with `connection`.
    configure: Action<OracleBulkCopy>?
    An optional delegate to configure the `OracleBulkCopy` instance before execution.

    Returns: A `BulkInsertResult<T>` containing the total number of rows inserted.

    Type parameters: T: The entity type. Must implement `IStaticEntityMetadata<T>`. Exceptions: ArgumentNullException: `connection` or `entities` is `null`.; InvalidOperationException: `transaction` does not belong to `connection`.

  • methodBulkInsertAsync<T>
    public static Task<BulkInsertResult<T>> BulkInsertAsync<T>(IDbConnection connection, IEnumerable<T> entities, BulkOptions? options = null, IDbTransaction? transaction = null, Action<OracleBulkCopy>? configure = null, CancellationToken cancellationToken = default) where T : IStaticEntityMetadata<T>

    Asynchronously bulk-inserts a collection of entities using a generic database connection.

    connection: IDbConnection
    A database connection (must be an `OracleConnection`).
    entities: IEnumerable<T>
    The entities to insert.
    options: BulkOptions?
    Optional bulk operation options.
    transaction: IDbTransaction?
    An optional database transaction (must be an `OracleTransaction` if provided).
    configure: Action<OracleBulkCopy>?
    An optional delegate to configure the `OracleBulkCopy` instance before execution.
    cancellationToken: CancellationToken
    A token that can be used to cancel the asynchronous operation.

    Returns: A task representing the asynchronous operation. The task result contains a `BulkInsertResult<T>` with the total number of rows inserted.

    Type parameters: T: The entity type. Must implement `IStaticEntityMetadata<T>`. Exceptions: ArgumentNullException: `connection` or `entities` is `null`.; InvalidOperationException: `connection` is not an `OracleConnection`, or `transaction` is not an `OracleTransaction`.

  • methodBulkInsertAsync<T>
    public static async Task<BulkInsertResult<T>> BulkInsertAsync<T>(OracleConnection connection, IEnumerable<T> entities, BulkOptions? options = null, OracleTransaction? transaction = null, Action<OracleBulkCopy>? configure = null, CancellationToken cancellationToken = default) where T : IStaticEntityMetadata<T>

    Asynchronously bulk-inserts a collection of entities into the Oracle table associated with `T` using `OracleBulkCopy`.

    connection: OracleConnection
    An `OracleConnection` instance.
    entities: IEnumerable<T>
    The entities to insert.
    options: BulkOptions?
    Optional bulk operation options. Defaults to `BulkOptions.Default`.
    transaction: OracleTransaction?
    An optional `OracleTransaction` associated with `connection`.
    configure: Action<OracleBulkCopy>?
    An optional delegate to configure the `OracleBulkCopy` instance before execution.
    cancellationToken: CancellationToken
    A token that can be used to cancel the asynchronous operation.

    Returns: A task representing the asynchronous operation. The task result contains a `BulkInsertResult<T>` with the total number of rows inserted.

    Type parameters: T: The entity type. Must implement `IStaticEntityMetadata<T>`. Exceptions: ArgumentNullException: `connection` or `entities` is `null`.; InvalidOperationException: `transaction` does not belong to `connection`.; OperationCanceledException: The operation was canceled via `cancellationToken`.

  • methodExecuteBulkCopy<T>
    public static void ExecuteBulkCopy<T>(this IBulkOperation<T> operation, OracleConnection connection, string destinationTableName, Action<OracleBulkCopy>? configure = null) where T : IStaticEntityMetadata<T>

    Executes a configured bulk insert operation against the specified Oracle destination table using `OracleBulkCopy`.

    operation: this IBulkOperation<T>
    The bulk insert operation containing the entity data and column selection rules.
    connection: OracleConnection
    An `OracleConnection` instance.
    destinationTableName: string
    The name of the Oracle table to copy rows into.
    configure: Action<OracleBulkCopy>?
    An optional delegate to configure the `OracleBulkCopy` instance before execution.

    Type parameters: T: The entity type. Must implement `IStaticEntityMetadata<T>`. Exceptions: ArgumentNullException: `operation` or `connection` is `null`.; ArgumentException: `destinationTableName` is `null`, empty, or consists only of white-space characters.; NotSupportedException: `operation` is not a bulk insert operation.

class

OracleCompiler

Assembly: EricksonLopez.SqlBuilder.Oracle
public class OracleCompiler : SqlCompilerBase
Inherits: SqlCompilerBase

Provides Oracle Database specific compilation and dialect rules.

Members (5)

  • constructorOracleCompiler
    public OracleCompiler(OracleDialectVersion version = OracleDialectVersion.Oracle12cPlus)

    Initializes a new instance of the `OracleCompiler` class.

    version: OracleDialectVersion
    The target Oracle Database dialect version.
  • methodCreateParameterManager
    public override IParameterManager CreateParameterManager()

    Creates a new parameter manager for storing SQL parameters during compilation.

    Returns: An instance of `IParameterManager`.

  • methodEscapeIdentifier
    public override void EscapeIdentifier(StringBuilder sb, ReadOnlySpan<char> identifier)

    Escapes a raw identifier span and appends it directly to the provided `StringBuilder`.

    sb: StringBuilder
    The string builder to append the escaped identifier to.
    identifier: ReadOnlySpan<char>
    The raw identifier span.
  • methodEscapeIdentifier
    public override string EscapeIdentifier(string identifier)

    Escapes a raw SQL identifier string.

    identifier: string
    The raw identifier to escape.

    Returns: The escaped identifier string.

  • propertyDialectVersion
    public OracleDialectVersion DialectVersion { get; }

    Gets the Oracle Database dialect version targeted by this compiler instance.

enum

OracleDialectVersion

Assembly: EricksonLopez.SqlBuilder.Oracle
public enum OracleDialectVersion

Specifies the target Oracle Database dialect version for SQL compilation.

Members (2)

  • fieldOracle11g
    Oracle11g = 1

    Oracle Database 11g Release 2 (11.2) and older. Emulates OFFSET and LIMIT pagination using ROWNUM nested subqueries.

  • fieldOracle12cPlus
    Oracle12cPlus = 0

    Oracle Database 12c Release 1 (12.1) and newer. Uses native ANSI SQL:2008 standard OFFSET / FETCH NEXT ROWS pagination syntax.

class

OracleParameterManager

Assembly: EricksonLopez.SqlBuilder.Oracle
public class OracleParameterManager : IParameterManager
Implements: IParameterManager

Custom parameter manager for Oracle that uses ':' prefix and translates booleans.

Members (5)

  • constructorOracleParameterManager
    public OracleParameterManager(string prefix = "")

    Initializes a new instance of the `OracleParameterManager` class.

    prefix: string
    The parameter name prefix.
  • methodAdd
    public string Add(object? value)

    Adds a parameter value and returns its generated parameter name in the dialect's syntax.

    value: object?
    The value to add as a parameter.

    Returns: The generated parameter name (e.g., '@p0').

  • methodAdd<TParam>
    public string Add<TParam>(TParam value)

    Adds a strongly-typed parameter to the manager.

    value: TParam
    The parameter value to register and process.

    Returns: The generated parameter placeholder name.

    Type parameters: TParam: The type of the parameter value.

  • methodAddNamed
    public string AddNamed(string name, object? value)

    Adds a named parameter value and returns its formatted parameter name in the dialect's syntax.

    name: string
    The explicit name of the parameter.
    value: object?
    The value to add.

    Returns: The formatted parameter name (e.g., '@name').

  • methodGetParameters
    public IReadOnlyDictionary<string, object?> GetParameters()

    Gets the read-only dictionary of all registered parameters.

    Returns: A dictionary containing the parameter names and their values.

class

OracleRenderer

Assembly: EricksonLopez.SqlBuilder.Oracle
public class OracleRenderer : AotSqlRendererBase
Inherits: AotSqlRendererBase

Provides AOT-optimized SQL rendering for Oracle Database.

Members (6)

  • constructorOracleRenderer
    public OracleRenderer(ISqlCompiler compiler)

    Initializes a new instance of the `OracleRenderer` class.

    compiler: ISqlCompiler
    The compiler associated with this renderer.
  • methodRenderBulkInsert<T>
    public override BulkSqlResult RenderBulkInsert<T>(IEnumerable<T> entities, List<EricksonLopez.SqlBuilder.ColumnSelection.IColumnSelectionRule<T>> rules, int batchSize)

    Renders a batch of bulk INSERT statements for a collection of entities.

    entities: IEnumerable<T>
    The collection of entities to insert.
    rules: List<EricksonLopez.SqlBuilder.ColumnSelection.IColumnSelectionRule<T>>
    The column selection rules applied to the operation.
    batchSize: int
    The maximum number of entities to process per batch.

    Returns: A `Operations.BulkSqlResult` containing the generated batches.

    Type parameters: T: The type of the entities.

  • methodRenderBulkInsertIgnore<T>
    public override BulkSqlResult RenderBulkInsertIgnore<T>(IEnumerable<T> entities, List<EricksonLopez.SqlBuilder.ColumnSelection.IColumnSelectionRule<T>> rules, int batchSize)

    Renders a batch of bulk INSERT IGNORE statements for a collection of entities.

    entities: IEnumerable<T>
    The collection of entities to insert.
    rules: List<EricksonLopez.SqlBuilder.ColumnSelection.IColumnSelectionRule<T>>
    The column selection rules applied to the operation.
    batchSize: int
    The maximum number of entities to process per batch.

    Returns: A `Operations.BulkSqlResult` containing the generated batches.

    Type parameters: T: The type of the entities.

  • methodRenderBulkMerge<T>
    public override BulkSqlResult RenderBulkMerge<T>(IEnumerable<T> entities, List<EricksonLopez.SqlBuilder.ColumnSelection.IColumnSelectionRule<T>> rules, int batchSize)

    Renders a batch of bulk MERGE statements for a collection of entities.

    entities: IEnumerable<T>
    The collection of entities to merge.
    rules: List<EricksonLopez.SqlBuilder.ColumnSelection.IColumnSelectionRule<T>>
    The column selection rules applied to the operation.
    batchSize: int
    The maximum number of entities to process per batch.

    Returns: A `Operations.BulkSqlResult` containing the generated batches.

    Type parameters: T: The type of the entities.

  • methodRenderBulkUpdate<T>
    public override BulkSqlResult RenderBulkUpdate<T>(IEnumerable<T> entities, List<EricksonLopez.SqlBuilder.ColumnSelection.IColumnSelectionRule<T>> rules, int batchSize)

    Renders a batch of bulk UPDATE statements for a collection of entities.

    entities: IEnumerable<T>
    The collection of entities to update.
    rules: List<EricksonLopez.SqlBuilder.ColumnSelection.IColumnSelectionRule<T>>
    The column selection rules applied to the operation.
    batchSize: int
    The maximum number of entities to process per batch.

    Returns: A `Operations.BulkSqlResult` containing the generated batches.

    Type parameters: T: The type of the entities.

  • methodRenderBulkUpsert<T>
    public override BulkSqlResult RenderBulkUpsert<T>(IEnumerable<T> entities, List<EricksonLopez.SqlBuilder.ColumnSelection.IColumnSelectionRule<T>> rules, int batchSize)

    Renders a batch of bulk UPSERT statements for a collection of entities.

    entities: IEnumerable<T>
    The collection of entities to upsert.
    rules: List<EricksonLopez.SqlBuilder.ColumnSelection.IColumnSelectionRule<T>>
    The column selection rules applied to the operation.
    batchSize: int
    The maximum number of entities to process per batch.

    Returns: A `Operations.BulkSqlResult` containing the generated batches.

    Type parameters: T: The type of the entities.

EricksonLopez.SqlBuilder.Pagination#

1
class

SqlBuilderPaginationExtensions

Assembly: EricksonLopez.SqlBuilder.Pagination
public static class SqlBuilderPaginationExtensions

Provides extension methods for applying offset and keyset cursor pagination directly to `SelectQuery<T>` AST queries.

Members (6)

  • methodApplyCursor<T, TKey>
    public static SelectQuery<T> ApplyCursor<T, TKey>(this SelectQuery<T> query, CursorPaginationParameters parameters, Expression<Func<T, TKey>> keySelector, ICursorEncoder? encoder = null, bool ascending = true) where T : class, new() where TKey : notnull

    Applies keyset cursor pagination to the query using the specified cursor key selector.

    query: this SelectQuery<T>
    The SQL query AST builder.
    parameters: CursorPaginationParameters
    The cursor pagination parameters containing after/before tokens.
    keySelector: Expression<Func<T, TKey>>
    The expression identifying the unique ordering key column.
    encoder: ICursorEncoder?
    The optional cursor encoder. If null, the development default HMAC encoder is used.
    ascending: bool
    True for ascending order (default); false for descending order.

    Returns: A new `SelectQuery<T>` with cursor predicates, ordering, and limit (pageSize + 1) applied.

    Type parameters: T: The entity type.; TKey: The cursor key type. Exceptions: ArgumentNullException: `query` or `keySelector` is `null`

  • methodPaginate<T>
    public static SelectQuery<T> Paginate<T>(this SelectQuery<T> query, PaginationParameters parameters) where T : class, new()

    Applies offset pagination limits and offsets to the query based on `PaginationParameters`.

    query: this SelectQuery<T>
    The SQL query AST builder.
    parameters: PaginationParameters
    The pagination parameters specifying page number and page size.

    Returns: A new `SelectQuery<T>` with limit and offset applied.

    Type parameters: T: The entity type. Exceptions: ArgumentNullException: `query` is `null`

  • methodPaginate<T>
    public static SelectQuery<T> Paginate<T>(this SelectQuery<T> query, int pageNumber, int pageSize) where T : class, new()

    Applies offset pagination limits and offsets to the query using explicit page number and page size.

    query: this SelectQuery<T>
    The SQL query AST builder.
    pageNumber: int
    The 1-based page number.
    pageSize: int
    The number of records per page.

    Returns: A new `SelectQuery<T>` with limit and offset applied.

    Type parameters: T: The entity type. Exceptions: ArgumentNullException: `query` is `null`; ArgumentOutOfRangeException: `pageNumber` or `pageSize` is less than 1

  • methodToCursorPagedList<T, TKey>
    public static CursorPagedList<T> ToCursorPagedList<T, TKey>(this IReadOnlyList<T> items, CursorPaginationParameters parameters, Func<T, TKey> keySelector, ICursorEncoder? encoder = null) where T : class where TKey : notnull

    Materializes a fetched collection into a strongly-typed `CursorPagedList<T>`.

    items: this IReadOnlyList<T>
    The items fetched from the database (query limit should have been pageSize + 1).
    parameters: CursorPaginationParameters
    The cursor pagination parameters that configure the query.
    keySelector: Func<T, TKey>
    The delegate for extracting the cursor key from an item.
    encoder: ICursorEncoder?
    The optional cursor encoder.

    Returns: A new `CursorPagedList<T>` instance.

    Type parameters: T: The entity type.; TKey: The cursor key type. Exceptions: ArgumentNullException: `items` or `keySelector` is `null`

  • methodToPagedList<T>
    public static PagedList<T> ToPagedList<T>(this IEnumerable<T> items, int totalCount, PaginationParameters parameters)

    Materializes a collection and total count into a strongly-typed `PagedList<T>`.

    items: this IEnumerable<T>
    The items of the current page.
    totalCount: int
    The total count of matching records across all pages.
    parameters: PaginationParameters
    The pagination parameters.

    Returns: A new `PagedList<T>` instance.

    Type parameters: T: The entity type. Exceptions: ArgumentNullException: `items` is `null`

  • methodToPagedList<T>
    public static PagedList<T> ToPagedList<T>(this IEnumerable<T> items, int totalCount, int pageNumber, int pageSize)

    Materializes a collection and total count into a strongly-typed `PagedList<T>`.

    items: this IEnumerable<T>
    The items of the current page.
    totalCount: int
    The total count of matching records across all pages.
    pageNumber: int
    The 1-based page number.
    pageSize: int
    The number of records per page.

    Returns: A new `PagedList<T>` instance.

    Type parameters: T: The entity type. Exceptions: ArgumentNullException: `items` is `null`; ArgumentOutOfRangeException: `pageNumber` or `pageSize` is less than 1

EricksonLopez.SqlBuilder.PostgreSql#

9
record

CopyNode

Assembly: EricksonLopez.SqlBuilder.PostgreSql
public sealed record CopyNode(string TableName, string[] Columns, string FromSource, string Format) : SqlExtensionNode
Inherits: SqlExtensionNode

Represents the AST node for a PostgreSQL COPY FROM operation.

Members (6)

  • constructorCopyNode
    public CopyNode(string TableName, string[] Columns, string FromSource, string Format)

    Initializes a new instance of CopyNode.

    TableName: string
    The name of the target table.
    Columns: string[]
    The array of column names being copied.
    FromSource: string
    The source identifier (e.g., STDIN).
    Format: string
    The serialization format (e.g., BINARY, CSV).
  • methodAccept
    public override void Accept(ISqlVisitor visitor)

    Accepts a visitor to perform double-dispatch traversal of the AST.

    visitor: ISqlVisitor
    The visitor instance handling the node.
  • propertyColumns
    public string[] Columns { get; init; }

    The array of column names being copied.

  • propertyFormat
    public string Format { get; init; }

    The serialization format (e.g., BINARY, CSV).

  • propertyFromSource
    public string FromSource { get; init; }

    The source identifier (e.g., STDIN).

  • propertyTableName
    public string TableName { get; init; }

    The name of the target table.

record

CopyQuery<T>

Assembly: EricksonLopez.SqlBuilder.PostgreSql
public sealed record CopyQuery<T> : IAstQuery where T : class, new()
Implements: IAstQuery

Represents a PostgreSQL COPY FROM STDIN statement for high-performance bulk inserts.

Remarks:

Type parameters: T: The entity type to copy into PostgreSQL.

Members (5)

  • constructorCopyQuery
    public CopyQuery()

    Initializes a new instance of `CopyQuery<T>` using all mapped columns of the entity.

  • constructorCopyQuery
    public CopyQuery(IEnumerable<string> columns)

    Initializes a new instance of `CopyQuery<T>` with specific target columns.

    columns: IEnumerable<string>
    The specific columns to copy into.
  • methodBuild
    public SqlResult Build(ISqlCompiler compiler)

    Inherits documentation from base type or interface.

    compiler: ISqlCompiler
  • propertyNodes
    public ImmutableList<ISqlNode> Nodes { get; init; }

    Gets the list of nodes that compose the SQL query.

  • propertyTag
    public string? Tag { get; }

    Inherits documentation from base type or interface.

class

NpgsqlBulkMergeStrategy

Assembly: EricksonLopez.SqlBuilder.PostgreSql
public static class NpgsqlBulkMergeStrategy

Provides a high-performance native bulk MERGE (INSERT + UPDATE) strategy for PostgreSQL using `INSERT INTO ... ON CONFLICT DO UPDATE SET` (UPSERT).

Remarks:

PostgreSQL natively supports upsert via the `ON CONFLICT DO UPDATE` clause, which is atomically safe and significantly faster than manual merge patterns. Entities are staged using the `NpgsqlCopyStrategy` binary COPY protocol into a temporary table, then merged via a single `INSERT ... ON CONFLICT` statement.

Members (2)

  • methodBulkMergeAsync<T>
    public static Task<BulkInsertResult<T>> BulkMergeAsync<T>(IDbConnection connection, IEnumerable<T> entities, BulkOptions? options = null, IDbTransaction? transaction = null, CancellationToken cancellationToken = default) where T : IStaticEntityMetadata<T>

    Bulk-merges a collection of entities using a generic database connection.

    connection: IDbConnection
    An open database connection (must be an `NpgsqlConnection`).
    entities: IEnumerable<T>
    The entities to merge.
    options: BulkOptions?
    Optional bulk options.
    transaction: IDbTransaction?
    An optional database transaction.
    cancellationToken: CancellationToken
    A token that can be used to cancel the asynchronous operation.

    Returns: A task representing the asynchronous operation. The task result contains a `BulkInsertResult<T>` with total rows affected.

    Type parameters: T: The entity type. Must implement `IStaticEntityMetadata<T>`. Exceptions: InvalidOperationException: `connection` is not an instance of `NpgsqlConnection`

  • methodBulkMergeAsync<T>
    public static async Task<BulkInsertResult<T>> BulkMergeAsync<T>(NpgsqlConnection connection, IEnumerable<T> entities, BulkOptions? options = null, NpgsqlTransaction? transaction = null, CancellationToken cancellationToken = default) where T : IStaticEntityMetadata<T>

    Bulk-merges a collection of entities into the PostgreSQL table associated with `T` using `INSERT INTO ... ON CONFLICT (pk) DO UPDATE SET ...`.

    connection: NpgsqlConnection
    An open `NpgsqlConnection`.
    entities: IEnumerable<T>
    The entities to merge.
    options: BulkOptions?
    Optional bulk options.
    transaction: NpgsqlTransaction?
    An optional `NpgsqlTransaction`.
    cancellationToken: CancellationToken
    A token that can be used to cancel the asynchronous operation.

    Returns: A task representing the asynchronous operation. The task result contains a `BulkInsertResult<T>` with total rows affected.

    Type parameters: T: The entity type. Must implement `IStaticEntityMetadata<T>`. Exceptions: ArgumentNullException: `connection` or `entities` is `null`

class

NpgsqlCopyStrategy

Assembly: EricksonLopez.SqlBuilder.PostgreSql
public static class NpgsqlCopyStrategy

Provides a high-performance native bulk INSERT strategy for PostgreSQL using the `COPY` binary protocol via `NpgsqlBinaryImporter`.

Remarks:

PostgreSQL's COPY protocol is the fastest way to insert large volumes of data into unguarded staging or analytical tables. This strategy uses the binary format, which avoids text parsing overhead. Row-Level Security (RLS) Limitation: PostgreSQL rejects `COPY ... FROM STDIN` on tables with active Row-Level Security policies under non-superuser roles (`SQLSTATE 0A000`). For RLS-protected tables, use `EricksonLopez.DapperExtensions.PostgreSql` typed-array `UNNEST` (`BulkParameters` + `BulkInsertAsync`). Requires `NpgsqlConnection` from the `Npgsql` package.

Members (3)

  • methodBulkInsertAsync<T>
    public static Task<BulkInsertResult<T>> BulkInsertAsync<T>(IDbConnection connection, IEnumerable<T> entities, BulkOptions? options = null, IDbTransaction? transaction = null, CancellationToken cancellationToken = default) where T : IStaticEntityMetadata<T>

    Bulk-inserts a collection of entities using a generic database connection.

    connection: IDbConnection
    An open database connection (must be an `NpgsqlConnection`).
    entities: IEnumerable<T>
    The entities to insert.
    options: BulkOptions?
    Optional bulk operation options.
    transaction: IDbTransaction?
    An optional database transaction.
    cancellationToken: CancellationToken
    A token that can be used to cancel the asynchronous operation.

    Returns: A task representing the asynchronous operation. The task result contains a `BulkInsertResult<T>` with the total number of rows inserted.

    Type parameters: T: The entity type. Must implement `IStaticEntityMetadata<T>`. Exceptions: InvalidOperationException: `connection` is not an instance of `NpgsqlConnection`

  • methodBulkInsertAsync<T>
    public static Task<BulkInsertResult<T>> BulkInsertAsync<T>(NpgsqlConnection connection, IEnumerable<T> entities, BulkOptions? options = null, NpgsqlTransaction? transaction = null, CancellationToken cancellationToken = default) where T : IStaticEntityMetadata<T>

    Bulk-inserts a collection of entities into the PostgreSQL table associated with `T` using the binary COPY protocol.

    connection: NpgsqlConnection
    An open `NpgsqlConnection`.
    entities: IEnumerable<T>
    The entities to insert.
    options: BulkOptions?
    Optional bulk operation options.
    transaction: NpgsqlTransaction?
    An optional open `NpgsqlTransaction` to enlist.
    cancellationToken: CancellationToken
    A token that can be used to cancel the asynchronous operation.

    Returns: A task representing the asynchronous operation. The task result contains a `BulkInsertResult<T>` with the total number of rows inserted.

    Type parameters: T: The entity type. Must implement `IStaticEntityMetadata<T>`. Exceptions: ArgumentNullException: `connection` or `entities` is `null`

  • methodBulkInsertAsync<T>
    public static async Task<BulkInsertResult<T>> BulkInsertAsync<T>(NpgsqlConnection connection, IEnumerable<T> entities, BulkOptions? options, NpgsqlTransaction? transaction, string? targetTableOverride, CancellationToken cancellationToken = default) where T : IStaticEntityMetadata<T>

    Bulk-inserts a collection of entities into the specified target table (or `T`'s default table when `targetTableOverride` is `null`) using the binary COPY protocol.

    connection: NpgsqlConnection
    An open `NpgsqlConnection`.
    entities: IEnumerable<T>
    The entities to insert.
    options: BulkOptions?
    Optional bulk operation options.
    transaction: NpgsqlTransaction?
    An optional open `NpgsqlTransaction` to enlist.
    targetTableOverride: string?
    Optional override table name (e.g., a temporary staging table).
    cancellationToken: CancellationToken
    A token that can be used to cancel the asynchronous operation.

    Returns: A task representing the asynchronous operation. The task result contains a `BulkInsertResult<T>` with the total number of rows inserted.

    Type parameters: T: The entity type. Must implement `IStaticEntityMetadata<T>`. Exceptions: ArgumentNullException: `connection` or `entities` is `null`

class

PgSql

Assembly: EricksonLopez.SqlBuilder.PostgreSql
public static class PgSql

Provides PostgreSQL-specific operators for building SQL expressions (e.g., ILIKE, ANY, ALL).

Members (3)

  • methodAll<TItem>
    public static bool All<TItem>(TItem value, IEnumerable<TItem> collection)

    Defines an ALL operator for SQL expressions in PostgreSQL.

    value: TItem
    The value to check.
    collection: IEnumerable<TItem>
    The collection of items.

    Returns: `true` if the value matches all items in the collection; otherwise, `false`.

    Type parameters: TItem: The type of the item to compare. Exceptions: InvalidOperationException: The method is invoked directly at runtime rather than inside a query expression

  • methodAny<TItem>
    public static bool Any<TItem>(TItem value, IEnumerable<TItem> collection)

    Defines an ANY operator for SQL expressions in PostgreSQL.

    value: TItem
    The value to check.
    collection: IEnumerable<TItem>
    The collection of items.

    Returns: `true` if the value matches any item in the collection; otherwise, `false`.

    Type parameters: TItem: The type of the item to compare. Exceptions: InvalidOperationException: The method is invoked directly at runtime rather than inside a query expression

  • methodILike
    public static bool ILike(string column, string pattern)

    Defines an ILike operator for SQL expressions in PostgreSQL.

    column: string
    The column name to compare.
    pattern: string
    The pattern to match against.

    Returns: `true` if the column matches the pattern; otherwise, `false`.

    Exceptions: InvalidOperationException: The method is invoked directly at runtime rather than inside a query expression

class

PostgreSqlCompiler

Assembly: EricksonLopez.SqlBuilder.PostgreSql
public class PostgreSqlCompiler : SqlCompilerBase
Inherits: SqlCompilerBase

Provides PostgreSQL-specific SQL compilation and dialect rules.

Members (3)

  • constructorPostgreSqlCompiler
    public PostgreSqlCompiler()

    Initializes a new instance of the `PostgreSqlCompiler` class.

  • methodEscapeIdentifier
    public override void EscapeIdentifier(StringBuilder sb, ReadOnlySpan<char> identifier)

    Escapes a raw identifier span and appends it directly to the provided `StringBuilder`.

    sb: StringBuilder
    The string builder to append the escaped identifier to.
    identifier: ReadOnlySpan<char>
    The raw identifier span.
  • methodEscapeIdentifier
    public override string EscapeIdentifier(string identifier)

    Escapes a raw SQL identifier string.

    identifier: string
    The raw identifier to escape.

    Returns: The escaped identifier string.

class

PostgreSqlDapperExtensions

Assembly: EricksonLopez.SqlBuilder.PostgreSql
public static class PostgreSqlDapperExtensions

Provides PostgreSQL-specific extension methods for Dapper connections.

Members (3)

  • methodBulkCopyAsync<T>
    public static async Task BulkCopyAsync<T>(this NpgsqlConnection connection, IEnumerable<T> entities, CancellationToken cancellationToken = default) where T : class, ISqlEntity, new()

    Executes a high-performance binary bulk copy using PostgreSQL COPY protocol. Requires NpgsqlConnection.

    connection: this NpgsqlConnection
    The PostgreSQL connection.
    entities: IEnumerable<T>
    The entities to copy.
    cancellationToken: CancellationToken
    An optional token to cancel the asynchronous operation.

    Returns: A task representing the asynchronous operation.

    Type parameters: T: The entity type. Exceptions: InvalidOperationException: Entity metadata column count does not match value count

  • methodBulkCopyAsync<T>
    public static Task BulkCopyAsync<T>(this System.Data.IDbConnection connection, IEnumerable<T> entities, CancellationToken cancellationToken = default) where T : class, ISqlEntity, new()

    Executes a high-performance binary bulk copy using PostgreSQL COPY protocol via IDbConnection interface.

    connection: this System.Data.IDbConnection
    The database connection (must be an `NpgsqlConnection`).
    entities: IEnumerable<T>
    The entities to copy.
    cancellationToken: CancellationToken
    An optional token to cancel the asynchronous operation.

    Returns: A task representing the asynchronous operation.

    Type parameters: T: The entity type. Exceptions: InvalidOperationException: `connection` is not an active `NpgsqlConnection`

  • methodBulkInsertUnnestAsync<T>
    public static async Task<int> BulkInsertUnnestAsync<T>(this IDbConnection connection, IEnumerable<T> entities, DbTransaction? transaction = null, CancellationToken cancellationToken = default) where T : ISqlEntity, new()

    Executes a bulk INSERT using PostgreSQL's UNNEST function with array parameters.

    connection: this IDbConnection
    The database connection.
    entities: IEnumerable<T>
    The entities to insert.
    transaction: DbTransaction?
    An optional database transaction.
    cancellationToken: CancellationToken
    An optional token to cancel the asynchronous operation.

    Returns: A task representing the asynchronous operation. The task result contains the number of rows affected.

    Type parameters: T: The entity type. Exceptions: InvalidOperationException: Entity metadata column count does not match value count

class

PostgreSqlExtensions

Assembly: EricksonLopez.SqlBuilder.PostgreSql
public static class PostgreSqlExtensions

Provides PostgreSQL-specific SQL extensions for building queries.

Members (14)

  • methodDistinctOn<T>
    public static SelectQuery<T> DistinctOn<T>(this SelectQuery<T> query, params string[] columns) where T : class, new()

    Adds a DISTINCT ON clause to the query.

    query: this SelectQuery<T>
    The SQL query AST builder.
    columns: params string[]
    The columns to evaluate for distinctness.

    Returns: A new `SelectQuery<T>` with the DISTINCT ON clause applied.

    Type parameters: T: The entity type.

  • methodFromUnnest<T>
    public static SelectQuery<T> FromUnnest<T>(this SelectQuery<T> query, string alias, params object[] arrays) where T : class, new()

    Adds a FROM UNNEST() clause for one or more array parameters.

    query: this SelectQuery<T>
    The SQL query AST builder.
    alias: string
    The alias name for the unnested table.
    arrays: params object[]
    The array parameters to unnest.

    Returns: A new `SelectQuery<T>` with the UNNEST clause applied.

    Type parameters: T: The entity type.

  • methodJoinLateral<T>
    public static SelectQuery<T> JoinLateral<T>(this SelectQuery<T> query, ISqlQuery subquery, string alias) where T : class, new()

    Adds a LATERAL join to a subquery.

    query: this SelectQuery<T>
    The SQL query AST builder.
    subquery: ISqlQuery
    The subquery to join laterally.
    alias: string
    The alias name for the lateral join.

    Returns: A new `SelectQuery<T>` with the LATERAL join applied.

    Type parameters: T: The entity type. Exceptions: ArgumentException: `subquery` is not an AST query

  • methodSelectFilter<T>
    public static SelectQuery<T> SelectFilter<T>(this SelectQuery<T> query, System.FormattableString aggregate, System.FormattableString filter, string alias) where T : class, new()

    Adds an aggregate function with a FILTER (WHERE ...) clause.

    query: this SelectQuery<T>
    The SQL query AST builder.
    aggregate: System.FormattableString
    The aggregate function expression.
    filter: System.FormattableString
    The filter expression.
    alias: string
    The column alias name.

    Returns: A new `SelectQuery<T>` with the filtered aggregate applied.

    Type parameters: T: The entity type.

  • methodWhereAll<T>
    public static SelectQuery<T> WhereAll<T>(this SelectQuery<T> query, string column, object array) where T : class, new()

    Adds an = ALL() condition against an array.

    query: this SelectQuery<T>
    The SQL query AST builder.
    column: string
    The column name to compare.
    array: object
    The array parameter value.

    Returns: A new `SelectQuery<T>` with the ALL condition applied.

    Type parameters: T: The entity type.

  • methodWhereAny<T>
    public static SelectQuery<T> WhereAny<T>(this SelectQuery<T> query, string column, object array) where T : class, new()

    Adds an = ANY() condition against an array.

    query: this SelectQuery<T>
    The SQL query AST builder.
    column: string
    The column name to compare.
    array: object
    The array parameter value.

    Returns: A new `SelectQuery<T>` with the ANY condition applied.

    Type parameters: T: The entity type.

  • methodWhereArrayContains<T>
    public static SelectQuery<T> WhereArrayContains<T>(this SelectQuery<T> query, string column, object array) where T : class, new()

    Adds an array @> condition to check if an array column contains elements.

    query: this SelectQuery<T>
    The SQL query AST builder.
    column: string
    The column name to check.
    array: object
    The array elements parameter.

    Returns: A new `SelectQuery<T>` with the array contains condition applied.

    Type parameters: T: The entity type.

  • methodWhereArrayOverlaps<T>
    public static SelectQuery<T> WhereArrayOverlaps<T>(this SelectQuery<T> query, string column, object array) where T : class, new()

    Adds an array && condition to check for overlap between two arrays.

    query: this SelectQuery<T>
    The SQL query AST builder.
    column: string
    The column name to check.
    array: object
    The array parameter value.

    Returns: A new `SelectQuery<T>` with the array overlaps condition applied.

    Type parameters: T: The entity type.

  • methodWhereComposite<T>
    public static SelectQuery<T> WhereComposite<T>(this SelectQuery<T> query, string column, string compositeTypeName, params object[] properties) where T : class, new()

    Adds a condition comparing against a strongly typed composite tuple.

    query: this SelectQuery<T>
    The SQL query AST builder.
    column: string
    The column name to compare.
    compositeTypeName: string
    The PostgreSQL composite type name.
    properties: params object[]
    The composite property values.

    Returns: A new `SelectQuery<T>` with the composite condition applied.

    Type parameters: T: The entity type. Exceptions: ArgumentException: `properties` is `null` or empty

  • methodWhereILike<T>
    public static SelectQuery<T> WhereILike<T>(this SelectQuery<T> query, string column, string pattern) where T : class, new()

    Adds an ILIKE condition for case-insensitive pattern matching.

    query: this SelectQuery<T>
    The SQL query AST builder.
    column: string
    The column name to compare.
    pattern: string
    The pattern to match against.

    Returns: A new `SelectQuery<T>` with the ILIKE condition applied.

    Type parameters: T: The entity type.

  • methodWhereJsonPath<T>
    public static SelectQuery<T> WhereJsonPath<T>(this SelectQuery<T> query, string column, string path) where T : class, new()

    Adds a JSONPATH @@ condition to check if a jsonpath expression matches.

    query: this SelectQuery<T>
    The SQL query AST builder.
    column: string
    The column name to check.
    path: string
    The JSONPATH expression string.

    Returns: A new `SelectQuery<T>` with the JSONPATH condition applied.

    Type parameters: T: The entity type.

  • methodWhereJsonbContains<T>
    public static SelectQuery<T> WhereJsonbContains<T>(this SelectQuery<T> query, string column, string json) where T : class, new()

    Adds a JSONB @> condition to check if the column contains the specified JSON payload.

    query: this SelectQuery<T>
    The SQL query AST builder.
    column: string
    The column name to check.
    json: string
    The JSON payload string.

    Returns: A new `SelectQuery<T>` with the JSONB contains condition applied.

    Type parameters: T: The entity type.

  • methodWhereJsonbExists<T>
    public static SelectQuery<T> WhereJsonbExists<T>(this SelectQuery<T> query, string column, string key) where T : class, new()

    Adds a JSONB ? condition to check if a specific key exists at the top level.

    query: this SelectQuery<T>
    The SQL query AST builder.
    column: string
    The column name to check.
    key: string
    The JSON key name.

    Returns: A new `SelectQuery<T>` with the JSONB exists condition applied.

    Type parameters: T: The entity type.

  • methodWherePgEnum<T>
    public static SelectQuery<T> WherePgEnum<T>(this SelectQuery<T> query, string column, string enumTypeName, object enumValue) where T : class, new()

    Adds a condition comparing against a custom PostgreSQL enum type.

    query: this SelectQuery<T>
    The SQL query AST builder.
    column: string
    The column name to compare.
    enumTypeName: string
    The PostgreSQL enum type name.
    enumValue: object
    The enum value.

    Returns: A new `SelectQuery<T>` with the enum condition applied.

    Type parameters: T: The entity type.

class

PostgreSqlRenderer

Assembly: EricksonLopez.SqlBuilder.PostgreSql
public class PostgreSqlRenderer : AotSqlRendererBase
Inherits: AotSqlRendererBase

Provides AOT-optimized SQL rendering for PostgreSQL, utilizing bulk UNNEST operations and specific syntax.

Members (8)

  • constructorPostgreSqlRenderer
    public PostgreSqlRenderer(ISqlCompiler compiler)

    Initializes a new instance of the `PostgreSqlRenderer` class.

    compiler: ISqlCompiler
    The compiler associated with this renderer.
  • methodRenderBulkInsert<T>
    public override BulkSqlResult RenderBulkInsert<T>(IEnumerable<T> entities, List<EricksonLopez.SqlBuilder.ColumnSelection.IColumnSelectionRule<T>> rules, int batchSize)

    Renders a batch of bulk INSERT statements for a collection of entities.

    entities: IEnumerable<T>
    The collection of entities to insert.
    rules: List<EricksonLopez.SqlBuilder.ColumnSelection.IColumnSelectionRule<T>>
    The column selection rules applied to the operation.
    batchSize: int
    The maximum number of entities to process per batch.

    Returns: A `Operations.BulkSqlResult` containing the generated batches.

    Type parameters: T: The type of the entities.

  • methodRenderBulkInsertIgnore<T>
    public override BulkSqlResult RenderBulkInsertIgnore<T>(IEnumerable<T> entities, List<EricksonLopez.SqlBuilder.ColumnSelection.IColumnSelectionRule<T>> rules, int batchSize)

    Renders a batch of bulk INSERT IGNORE statements for a collection of entities.

    entities: IEnumerable<T>
    The collection of entities to insert.
    rules: List<EricksonLopez.SqlBuilder.ColumnSelection.IColumnSelectionRule<T>>
    The column selection rules applied to the operation.
    batchSize: int
    The maximum number of entities to process per batch.

    Returns: A `Operations.BulkSqlResult` containing the generated batches.

    Type parameters: T: The type of the entities.

  • methodRenderBulkMerge<T>
    public override BulkSqlResult RenderBulkMerge<T>(IEnumerable<T> entities, List<EricksonLopez.SqlBuilder.ColumnSelection.IColumnSelectionRule<T>> rules, int batchSize)

    Renders a batch of bulk MERGE statements for a collection of entities.

    entities: IEnumerable<T>
    The collection of entities to merge.
    rules: List<EricksonLopez.SqlBuilder.ColumnSelection.IColumnSelectionRule<T>>
    The column selection rules applied to the operation.
    batchSize: int
    The maximum number of entities to process per batch.

    Returns: A `Operations.BulkSqlResult` containing the generated batches.

    Type parameters: T: The type of the entities.

  • methodRenderBulkUpdate<T>
    public override BulkSqlResult RenderBulkUpdate<T>(IEnumerable<T> entities, List<EricksonLopez.SqlBuilder.ColumnSelection.IColumnSelectionRule<T>> rules, int batchSize)

    Renders a batch of bulk UPDATE statements for a collection of entities.

    entities: IEnumerable<T>
    The collection of entities to update.
    rules: List<EricksonLopez.SqlBuilder.ColumnSelection.IColumnSelectionRule<T>>
    The column selection rules applied to the operation.
    batchSize: int
    The maximum number of entities to process per batch.

    Returns: A `Operations.BulkSqlResult` containing the generated batches.

    Type parameters: T: The type of the entities.

  • methodRenderBulkUpsert<T>
    public override BulkSqlResult RenderBulkUpsert<T>(IEnumerable<T> entities, List<EricksonLopez.SqlBuilder.ColumnSelection.IColumnSelectionRule<T>> rules, int batchSize)

    Renders a batch of bulk UPSERT statements for a collection of entities.

    entities: IEnumerable<T>
    The collection of entities to upsert.
    rules: List<EricksonLopez.SqlBuilder.ColumnSelection.IColumnSelectionRule<T>>
    The column selection rules applied to the operation.
    batchSize: int
    The maximum number of entities to process per batch.

    Returns: A `Operations.BulkSqlResult` containing the generated batches.

    Type parameters: T: The type of the entities.

  • methodRenderInsert<T>
    public override SqlResult RenderInsert<T>(T entity, Span<bool> insertMask)

    Renders an INSERT statement for a single entity.

    entity: T
    The entity instance.
    insertMask: Span<bool>
    A span representing which columns to include in the INSERT.

    Returns: A `SqlResult` containing the generated SQL and parameters.

    Type parameters: T: The type of the entity.

  • methodRenderUpdate<T>
    public override SqlResult RenderUpdate<T>(T entity, Span<bool> setMask, Span<bool> whereMask)

    Renders an UPDATE statement for a single entity.

    entity: T
    The entity instance.
    setMask: Span<bool>
    A span representing which columns to include in the SET clause.
    whereMask: Span<bool>
    A span representing which columns to use in the WHERE clause (usually primary keys).

    Returns: A `SqlResult` containing the generated SQL and parameters.

    Type parameters: T: The type of the entity.

EricksonLopez.SqlBuilder.SourceGenerators#

3
class

FilterGenerator

Assembly: EricksonLopez.SqlBuilder.SourceGenerators
public class FilterGenerator : IIncrementalGenerator
Implements: IIncrementalGenerator

Generates strongly-typed filter extension methods and `ISqlFilter<T>` DTO classes for SQL entities.

Members (1)

  • methodInitialize
    public void Initialize(IncrementalGeneratorInitializationContext context)

    Inherits documentation from base type or interface.

    context: IncrementalGeneratorInitializationContext
class

MultiMapDescriptorGenerator

Assembly: EricksonLopez.SqlBuilder.SourceGenerators
public class MultiMapDescriptorGenerator : IIncrementalGenerator
Implements: IIncrementalGenerator

Generates compile-time multi-map metadata methods for entity types annotated with `[SqlEntity]`. For each entity, emits a `GetMultiMapReaderFactory()` static method that returns a `Func<System.Data.IDataReader, object>` — a reflection-free factory for NativeAOT and stream reader execution paths.

Members (1)

  • methodInitialize
    public void Initialize(IncrementalGeneratorInitializationContext context)

    Inherits documentation from base type or interface.

    context: IncrementalGeneratorInitializationContext
class

SqlEntityGenerator

Assembly: EricksonLopez.SqlBuilder.SourceGenerators
public class SqlEntityGenerator : IIncrementalGenerator
Implements: IIncrementalGenerator

Generates boilerplate AOT metadata, hydration logic, and column definitions for SQL entities.

Members (1)

  • methodInitialize
    public void Initialize(IncrementalGeneratorInitializationContext context)

    Inherits documentation from base type or interface.

    context: IncrementalGeneratorInitializationContext

EricksonLopez.SqlBuilder.SqlServer#

4
class

SqlBulkCopyStrategy

Assembly: EricksonLopez.SqlBuilder.SqlServer
public static class SqlBulkCopyStrategy

Provides a high-performance native bulk INSERT strategy for SQL Server using `SqlBulkCopy` (TDS bulk load protocol).

Remarks:

This strategy bypasses parameter-based SQL and streams rows directly to SQL Server via the TDS bulk load protocol, achieving orders-of-magnitude better throughput for large datasets compared to multi-row INSERT statements. Requires a `SqlConnection` from `Microsoft.Data.SqlClient`.

Members (2)

  • methodBulkInsertAsync<T>
    public static Task<BulkInsertResult<T>> BulkInsertAsync<T>(IDbConnection connection, IEnumerable<T> entities, BulkOptions? options = null, IDbTransaction? transaction = null, CancellationToken cancellationToken = default) where T : IStaticEntityMetadata<T>

    Bulk-inserts a collection of entities using a generic database connection.

    connection: IDbConnection
    An open database connection (must be a `SqlConnection`).
    entities: IEnumerable<T>
    The entities to insert.
    options: BulkOptions?
    Optional bulk operation options.
    transaction: IDbTransaction?
    An optional database transaction.
    cancellationToken: CancellationToken
    A token that can be used to cancel the asynchronous operation.

    Returns: A task representing the asynchronous operation. The task result contains a `BulkInsertResult<T>` with the total number of rows inserted.

    Type parameters: T: The entity type. Must implement `IStaticEntityMetadata<T>`. Exceptions: InvalidOperationException: `connection` is not a `SqlConnection`

  • methodBulkInsertAsync<T>
    public static async Task<BulkInsertResult<T>> BulkInsertAsync<T>(SqlConnection connection, IEnumerable<T> entities, BulkOptions? options = null, SqlTransaction? transaction = null, CancellationToken cancellationToken = default) where T : IStaticEntityMetadata<T>

    Bulk-inserts a collection of entities into the SQL Server table associated with `T` using `SqlBulkCopy`.

    connection: SqlConnection
    An open `SqlConnection`.
    entities: IEnumerable<T>
    The entities to insert.
    options: BulkOptions?
    Optional bulk operation options. Defaults to `BulkOptions.Default`.
    transaction: SqlTransaction?
    An optional open `SqlTransaction` to enlist.
    cancellationToken: CancellationToken
    A token that can be used to cancel the asynchronous operation.

    Returns: A task representing the asynchronous operation. The task result contains a `BulkInsertResult<T>` with the total number of rows inserted. When `BulkOptions.ReturnIdentities` is `true`, the original entity list is returned (identity population requires OUTPUT clause — use `InsertQuery<T>` for that).

    Type parameters: T: The entity type. Must implement `IStaticEntityMetadata<T>` (typically generated by the SqlEntity Source Generator). Exceptions: ArgumentNullException: `connection` or `entities` is `null`

class

SqlBulkMergeStrategy

Assembly: EricksonLopez.SqlBuilder.SqlServer
public static class SqlBulkMergeStrategy

Provides a high-performance native bulk MERGE (INSERT + UPDATE) strategy for SQL Server.

Remarks:

The merge is implemented in two stages: - Bulk-copies the entities into a temporary staging table using `SqlBulkCopy`. - Executes a `MERGE INTO target USING staging ON (key) WHEN MATCHED THEN UPDATE ... WHEN NOT MATCHED THEN INSERT ...` statement. This approach is faster than row-by-row upsert and avoids the deadlocks associated with `IF EXISTS ... UPDATE ... ELSE INSERT` patterns.

Members (2)

  • methodBulkMergeAsync<T>
    public static Task<BulkInsertResult<T>> BulkMergeAsync<T>(IDbConnection connection, IEnumerable<T> entities, BulkOptions? options = null, IDbTransaction? transaction = null, CancellationToken cancellationToken = default) where T : IStaticEntityMetadata<T>

    Bulk-merges a collection of entities using a generic database connection.

    connection: IDbConnection
    An open database connection (must be a `SqlConnection`).
    entities: IEnumerable<T>
    The entities to merge.
    options: BulkOptions?
    Optional bulk options (batch size, timeout).
    transaction: IDbTransaction?
    An optional database transaction.
    cancellationToken: CancellationToken
    A token that can be used to cancel the asynchronous operation.

    Returns: A task representing the asynchronous operation. The task result contains a `BulkInsertResult<T>` with the total number of rows affected.

    Type parameters: T: The entity type. Must implement `IStaticEntityMetadata<T>`. Exceptions: InvalidOperationException: `connection` is not a `SqlConnection`

  • methodBulkMergeAsync<T>
    public static async Task<BulkInsertResult<T>> BulkMergeAsync<T>(SqlConnection connection, IEnumerable<T> entities, BulkOptions? options = null, SqlTransaction? transaction = null, CancellationToken cancellationToken = default) where T : IStaticEntityMetadata<T>

    Bulk-merges a collection of entities into the SQL Server table associated with `T` using a staging-table + MERGE pattern.

    connection: SqlConnection
    An open `SqlConnection`.
    entities: IEnumerable<T>
    The entities to merge.
    options: BulkOptions?
    Optional bulk options (batch size, timeout).
    transaction: SqlTransaction?
    An optional `SqlTransaction`.
    cancellationToken: CancellationToken
    A token that can be used to cancel the asynchronous operation.

    Returns: A task representing the asynchronous operation. The task result contains a `BulkInsertResult<T>` with the total number of rows affected (inserted + updated).

    Type parameters: T: The entity type. Must implement `IStaticEntityMetadata<T>`. Exceptions: ArgumentNullException: `connection` or `entities` is `null`

class

SqlServerCompiler

Assembly: EricksonLopez.SqlBuilder.SqlServer
public class SqlServerCompiler : SqlCompilerBase
Inherits: SqlCompilerBase

Provides SQL Server (T-SQL) specific compilation and dialect rules.

Members (5)

  • constructorSqlServerCompiler
    public SqlServerCompiler()

    Initializes a new instance of the `SqlServerCompiler` class.

  • methodCreateParameterManager
    public override IParameterManager CreateParameterManager()

    Creates a new parameter manager for storing SQL parameters during compilation.

    Returns: An instance of `IParameterManager`.

  • methodEscapeIdentifier
    public override void EscapeIdentifier(StringBuilder sb, ReadOnlySpan<char> identifier)

    Escapes a raw identifier span and appends it directly to the provided `StringBuilder`.

    sb: StringBuilder
    The string builder to append the escaped identifier to.
    identifier: ReadOnlySpan<char>
    The raw identifier span.
  • methodEscapeIdentifier
    public override string EscapeIdentifier(string identifier)

    Escapes a raw SQL identifier string.

    identifier: string
    The raw identifier to escape.

    Returns: The escaped identifier string.

  • methodSupportsCapability
    public override bool SupportsCapability(ProviderCapability capability)

    Determines whether the compiler and target database provider support a specific capability.

    capability: ProviderCapability
    The provider capability to check.

    Returns: `true` if the capability is supported; otherwise, `false`.

class

SqlServerRenderer

Assembly: EricksonLopez.SqlBuilder.SqlServer
public class SqlServerRenderer : AotSqlRendererBase
Inherits: AotSqlRendererBase

Provides AOT-optimized SQL rendering for SQL Server.

Members (6)

  • constructorSqlServerRenderer
    public SqlServerRenderer(ISqlCompiler compiler)

    Initializes a new instance of the `SqlServerRenderer` class.

    compiler: ISqlCompiler
    The compiler associated with this renderer.
  • methodRenderBulkInsert<T>
    public override BulkSqlResult RenderBulkInsert<T>(IEnumerable<T> entities, List<EricksonLopez.SqlBuilder.ColumnSelection.IColumnSelectionRule<T>> rules, int batchSize)

    Renders a batch of bulk INSERT statements for a collection of entities.

    entities: IEnumerable<T>
    The collection of entities to insert.
    rules: List<EricksonLopez.SqlBuilder.ColumnSelection.IColumnSelectionRule<T>>
    The column selection rules applied to the operation.
    batchSize: int
    The maximum number of entities to process per batch.

    Returns: A `Operations.BulkSqlResult` containing the generated batches.

    Type parameters: T: The type of the entities.

  • methodRenderBulkInsertIgnore<T>
    public override BulkSqlResult RenderBulkInsertIgnore<T>(IEnumerable<T> entities, List<EricksonLopez.SqlBuilder.ColumnSelection.IColumnSelectionRule<T>> rules, int batchSize)

    Renders a batch of bulk INSERT IGNORE statements for a collection of entities.

    entities: IEnumerable<T>
    The collection of entities to insert.
    rules: List<EricksonLopez.SqlBuilder.ColumnSelection.IColumnSelectionRule<T>>
    The column selection rules applied to the operation.
    batchSize: int
    The maximum number of entities to process per batch.

    Returns: A `Operations.BulkSqlResult` containing the generated batches.

    Type parameters: T: The type of the entities.

  • methodRenderBulkMerge<T>
    public override BulkSqlResult RenderBulkMerge<T>(IEnumerable<T> entities, List<EricksonLopez.SqlBuilder.ColumnSelection.IColumnSelectionRule<T>> rules, int batchSize)

    Renders a batch of bulk MERGE statements for a collection of entities.

    entities: IEnumerable<T>
    The collection of entities to merge.
    rules: List<EricksonLopez.SqlBuilder.ColumnSelection.IColumnSelectionRule<T>>
    The column selection rules applied to the operation.
    batchSize: int
    The maximum number of entities to process per batch.

    Returns: A `Operations.BulkSqlResult` containing the generated batches.

    Type parameters: T: The type of the entities.

  • methodRenderBulkUpdate<T>
    public override BulkSqlResult RenderBulkUpdate<T>(IEnumerable<T> entities, List<EricksonLopez.SqlBuilder.ColumnSelection.IColumnSelectionRule<T>> rules, int batchSize)

    Renders a batch of bulk UPDATE statements for a collection of entities.

    entities: IEnumerable<T>
    The collection of entities to update.
    rules: List<EricksonLopez.SqlBuilder.ColumnSelection.IColumnSelectionRule<T>>
    The column selection rules applied to the operation.
    batchSize: int
    The maximum number of entities to process per batch.

    Returns: A `Operations.BulkSqlResult` containing the generated batches.

    Type parameters: T: The type of the entities.

  • methodRenderBulkUpsert<T>
    public override BulkSqlResult RenderBulkUpsert<T>(IEnumerable<T> entities, List<EricksonLopez.SqlBuilder.ColumnSelection.IColumnSelectionRule<T>> rules, int batchSize)

    Renders a batch of bulk UPSERT statements for a collection of entities.

    entities: IEnumerable<T>
    The collection of entities to upsert.
    rules: List<EricksonLopez.SqlBuilder.ColumnSelection.IColumnSelectionRule<T>>
    The column selection rules applied to the operation.
    batchSize: int
    The maximum number of entities to process per batch.

    Returns: A `Operations.BulkSqlResult` containing the generated batches.

    Type parameters: T: The type of the entities.

EricksonLopez.SqlBuilder.Sqlite#

2
class

SqliteCompiler

Assembly: EricksonLopez.SqlBuilder.Sqlite
public class SqliteCompiler : SqlCompilerBase
Inherits: SqlCompilerBase

Provides SQLite specific compilation and dialect rules.

Members (3)

  • constructorSqliteCompiler
    public SqliteCompiler()

    Initializes a new instance of the `SqliteCompiler` class.

  • methodEscapeIdentifier
    public override void EscapeIdentifier(StringBuilder sb, ReadOnlySpan<char> identifier)

    Escapes a raw identifier span and appends it directly to the provided `StringBuilder`.

    sb: StringBuilder
    The string builder to append the escaped identifier to.
    identifier: ReadOnlySpan<char>
    The raw identifier span.
  • methodEscapeIdentifier
    public override string EscapeIdentifier(string identifier)

    Escapes a raw SQL identifier string.

    identifier: string
    The raw identifier to escape.

    Returns: The escaped identifier string.

class

SqliteRenderer

Assembly: EricksonLopez.SqlBuilder.Sqlite
public class SqliteRenderer : AotSqlRendererBase
Inherits: AotSqlRendererBase

Provides AOT-optimized SQL rendering for SQLite.

Members (6)

  • constructorSqliteRenderer
    public SqliteRenderer(ISqlCompiler compiler)

    Initializes a new instance of the `SqliteRenderer` class.

    compiler: ISqlCompiler
    The compiler associated with this renderer.
  • methodRenderBulkInsert<T>
    public override BulkSqlResult RenderBulkInsert<T>(IEnumerable<T> entities, List<EricksonLopez.SqlBuilder.ColumnSelection.IColumnSelectionRule<T>> rules, int batchSize)

    Renders a batch of bulk INSERT statements for a collection of entities.

    entities: IEnumerable<T>
    The collection of entities to insert.
    rules: List<EricksonLopez.SqlBuilder.ColumnSelection.IColumnSelectionRule<T>>
    The column selection rules applied to the operation.
    batchSize: int
    The maximum number of entities to process per batch.

    Returns: A `Operations.BulkSqlResult` containing the generated batches.

    Type parameters: T: The type of the entities.

  • methodRenderBulkInsertIgnore<T>
    public override BulkSqlResult RenderBulkInsertIgnore<T>(IEnumerable<T> entities, List<EricksonLopez.SqlBuilder.ColumnSelection.IColumnSelectionRule<T>> rules, int batchSize)

    Renders a batch of bulk INSERT IGNORE statements for a collection of entities.

    entities: IEnumerable<T>
    The collection of entities to insert.
    rules: List<EricksonLopez.SqlBuilder.ColumnSelection.IColumnSelectionRule<T>>
    The column selection rules applied to the operation.
    batchSize: int
    The maximum number of entities to process per batch.

    Returns: A `Operations.BulkSqlResult` containing the generated batches.

    Type parameters: T: The type of the entities.

  • methodRenderBulkMerge<T>
    public override BulkSqlResult RenderBulkMerge<T>(IEnumerable<T> entities, List<EricksonLopez.SqlBuilder.ColumnSelection.IColumnSelectionRule<T>> rules, int batchSize)

    Renders a batch of bulk MERGE statements for a collection of entities.

    entities: IEnumerable<T>
    The collection of entities to merge.
    rules: List<EricksonLopez.SqlBuilder.ColumnSelection.IColumnSelectionRule<T>>
    The column selection rules applied to the operation.
    batchSize: int
    The maximum number of entities to process per batch.

    Returns: A `Operations.BulkSqlResult` containing the generated batches.

    Type parameters: T: The type of the entities.

  • methodRenderBulkUpdate<T>
    public override BulkSqlResult RenderBulkUpdate<T>(IEnumerable<T> entities, List<EricksonLopez.SqlBuilder.ColumnSelection.IColumnSelectionRule<T>> rules, int batchSize)

    Renders a batch of bulk UPDATE statements for a collection of entities.

    entities: IEnumerable<T>
    The collection of entities to update.
    rules: List<EricksonLopez.SqlBuilder.ColumnSelection.IColumnSelectionRule<T>>
    The column selection rules applied to the operation.
    batchSize: int
    The maximum number of entities to process per batch.

    Returns: A `Operations.BulkSqlResult` containing the generated batches.

    Type parameters: T: The type of the entities.

  • methodRenderBulkUpsert<T>
    public override BulkSqlResult RenderBulkUpsert<T>(IEnumerable<T> entities, List<EricksonLopez.SqlBuilder.ColumnSelection.IColumnSelectionRule<T>> rules, int batchSize)

    Renders a batch of bulk UPSERT statements for a collection of entities.

    entities: IEnumerable<T>
    The collection of entities to upsert.
    rules: List<EricksonLopez.SqlBuilder.ColumnSelection.IColumnSelectionRule<T>>
    The column selection rules applied to the operation.
    batchSize: int
    The maximum number of entities to process per batch.

    Returns: A `Operations.BulkSqlResult` containing the generated batches.

    Type parameters: T: The type of the entities.

EricksonLopez.SqlBuilder.Testing#

10
class

DiagnosticActivityScope

Assembly: EricksonLopez.SqlBuilder.Testing
public sealed class DiagnosticActivityScope : IDisposable
Implements: IDisposable

Scoped test fixture for capturing OpenTelemetry and System.Diagnostics Activities during testing.

Members (3)

  • methodDispose
    public void Dispose()

    Inherits documentation from base type or interface.

  • methodStart
    public static DiagnosticActivityScope Start(string sourceName = "")

    Starts capturing activities from the specified ActivitySource name.

    sourceName: string
    The name of the ActivitySource to listen to.

    Returns: An active `DiagnosticActivityScope` instance.

  • propertyActivities
    public IReadOnlyCollection<Activity> Activities { get; }

    Gets all activities captured during the lifetime of this scope.

class

DummyEntity

Assembly: EricksonLopez.SqlBuilder.Testing
public class DummyEntity : ISqlEntity, IStaticEntityMetadata<DummyEntity>
Implements: ISqlEntity, IStaticEntityMetadata<DummyEntity>

Represents a minimal in-memory entity used exclusively in unit tests to exercise `ISqlEntity` and `IStaticEntityMetadata<T>` contract paths.

Remarks:

This type is not intended for production use. It exposes a fixed two-column schema (`Id`, `Name`) and is designed to be used as a predictable stand-in when verifying SQL generation, parameter binding, and bulk serialization behavior.

Members (23)

  • methodAreEqual
    public static bool AreEqual(DummyEntity entity, DummyEntity snapshot, int columnIndex)

    Determines whether the value of the specified column is equal between the current entity and a snapshot.

    entity: DummyEntity
    The current entity instance.
    snapshot: DummyEntity
    The original snapshot of the entity.
    columnIndex: int
    The zero-based index of the column to compare.

    Returns: `true` if the values are equal; otherwise, `false`.

  • methodBindParameter
    public static string BindParameter(DummyEntity entity, int columnIndex, IParameterManager parameters)

    Adds the value of the specified column from the given entity to the parameter manager and returns the generated parameter placeholder.

    entity: DummyEntity
    The entity whose column value is to be bound
    columnIndex: int
    The zero-based index of the column to bind
    parameters: IParameterManager
    The parameter manager that receives the bound value

    Returns: The parameter placeholder string generated by `parameters`.

  • methodExtractColumnArrays
    public static void ExtractColumnArrays(ReadOnlySpan<DummyEntity> entities, ReadOnlySpan<bool> activeColumns, IParameterManager parameters)

    Extracts column value arrays from the given entity span and adds them to the parameter manager for bulk operations, respecting the active column mask.

    entities: ReadOnlySpan<DummyEntity>
    The span of entities whose values are extracted
    activeColumns: ReadOnlySpan<bool>
    A boolean span indicating which columns are active. Index `0` controls `Id`; index `1` controls `Name`.
    parameters: IParameterManager
    The parameter manager that receives the extracted column arrays
  • methodFromReader
    public static DummyEntity FromReader(System.Data.IDataReader reader)

    Creates a new `DummyEntity` instance by reading from the specified data reader.

    reader: System.Data.IDataReader
    The data reader positioned at the current row

    Returns: A new `DummyEntity` instance with default values.

  • methodGetAllColumnNames
    public string[] GetAllColumnNames()

    Gets all column names mapped to the entity properties, including generated ones.

    Returns: An array of all column names.

  • methodGetAllValues
    public object?[] GetAllValues()

    Gets all current values of the entity properties, including generated ones.

    Returns: An array of all property values.

  • methodGetColumnName
    public static string GetColumnName(int columnIndex)

    Returns the column name for the specified zero-based column index.

    columnIndex: int
    The zero-based column index. `0` returns `"Id"`; any other value returns `"Name"`.

    Returns: The column name associated with the specified index.

  • methodGetColumnNames
    public string[] GetColumnNames()

    Gets the column names mapped to the entity properties, excluding generated ones.

    Returns: An array of column names.

  • methodGetColumns
    public static ReadOnlySpan<ColumnMetadata> GetColumns()

    Returns the column metadata descriptors for the `DummyEntity` schema.

    Returns: A read-only span containing the two column descriptors: `Id` (primary key) and `Name`.

  • methodGetIndexedColumns
    public string[] GetIndexedColumns()

    Gets the names of the columns that are indexed.

    Returns: An array of indexed column names.

  • methodGetPropertyMap
    public IReadOnlyDictionary<string, string> GetPropertyMap()

    Gets a mapping from property names to their corresponding database column names.

    Returns: A dictionary of property-to-column mappings.

  • methodGetReaderParser
    public static Func<System.Data.IDataReader, DummyEntity> GetReaderParser()

    Returns a delegate that creates a `DummyEntity` from a data reader row.

    Returns: A factory function that accepts an `Data.IDataReader` and returns a new `DummyEntity`.

  • methodGetTableName
    public string GetTableName()

    Gets the name of the mapped database table.

    Returns: The table name.

  • methodGetValues
    public object?[] GetValues()

    Gets the current values of the entity properties, excluding generated ones.

    Returns: An array of property values.

  • methodIsDefault
    public static bool IsDefault(DummyEntity entity, int columnIndex)

    Determines whether the value of the specified column is the default value for the given entity.

    entity: DummyEntity
    The entity instance to evaluate.
    columnIndex: int
    The zero-based index of the column.

    Returns: `true` if the column value is the default value; otherwise, `false`.

  • methodIsNull
    public static bool IsNull(DummyEntity entity, int columnIndex)

    Determines whether the value of the specified column is null for the given entity.

    entity: DummyEntity
    The entity instance to evaluate.
    columnIndex: int
    The zero-based index of the column.

    Returns: `true` if the column value is null; otherwise, `false`.

  • propertyColumnCount
    public static int ColumnCount { get; }

    Gets the number of columns defined for this entity type.

  • propertyId
    public int Id { get; set; }

    Gets or sets the primary key identifier of the entity.

  • propertyIsActive
    public bool IsActive { get; set; }

    Gets or sets a value indicating whether the entity is considered active.

  • propertyName
    public string Name { get; set; }

    Gets or sets the name value of the entity.

  • propertyRowGuid
    public Guid RowGuid { get; set; }

    Gets or sets a globally unique identifier associated with the entity.

  • propertyTableName
    public static string TableName { get; }

    Gets the database table name for this entity type.

  • propertyVersion
    public int Version { get; set; }

    Gets or sets a numeric version value for concurrency testing.

class

GoldenFileAssert

Assembly: EricksonLopez.SqlBuilder.Testing
public static class GoldenFileAssert

Provides assertion helpers for comparing compiled SQL against Golden Files stored on disk.

Members (1)

  • methodMatchesGoldenFile
    public static void MatchesGoldenFile(ISqlQuery query, ISqlCompiler compiler, string goldenFilePath, bool updateGoldenFiles = false, bool normalizeWhitespace = true)

    Verifies that the compiled SQL matches the content of a golden file. If the golden file does not exist and updateGoldenFiles is true, it creates or updates the golden file.

    query: ISqlQuery
    The SQL query to compile and verify.
    compiler: ISqlCompiler
    The SQL compiler used to build the query.
    goldenFilePath: string
    The path to the golden file containing the expected SQL.
    updateGoldenFiles: bool
    If `true`, overwrites the golden file with the actual output instead of asserting.
    normalizeWhitespace: bool
    If `true`, collapses all whitespace before comparing SQL strings.

    Exceptions: InvalidOperationException: The actual compiled SQL does not match the expected content of the golden file

class

MockSqlCompiler

Assembly: EricksonLopez.SqlBuilder.Testing
public class MockSqlCompiler : ISqlCompiler
Implements: ISqlCompiler

Provides a mock implementation of `ISqlCompiler` for testing purposes.

Members (11)

  • methodCompile
    public SqlResult Compile(ISqlQuery query)

    Compiles the specified SQL query into an executable result.

    query: ISqlQuery
    The query to compile.

    Returns: A `SqlResult` containing the generated SQL string and parameters.

  • methodCompile
    public SqlResult Compile(ISqlQuery query, IParameterManager? existingParameters)

    Compiles the specified SQL query using an existing parameter manager.

    query: ISqlQuery
    The query to compile.
    existingParameters: IParameterManager?
    An existing parameter manager to append parameters to.

    Returns: A `SqlResult` containing the generated SQL string and parameters.

  • methodCompileDelete
    public void CompileDelete(IReadOnlyList<ISqlNode> nodes, ISqlVisitor visitor)

    Inherits documentation from base type or interface.

    nodes: IReadOnlyList<ISqlNode>
    visitor: ISqlVisitor
  • methodCompileInsert
    public void CompileInsert(IReadOnlyList<ISqlNode> nodes, ISqlVisitor visitor)

    Inherits documentation from base type or interface.

    nodes: IReadOnlyList<ISqlNode>
    visitor: ISqlVisitor
  • methodCompileSelect
    public void CompileSelect(IReadOnlyList<ISqlNode> nodes, ISqlVisitor visitor)

    Inherits documentation from base type or interface.

    nodes: IReadOnlyList<ISqlNode>
    visitor: ISqlVisitor
  • methodCompileUpdate
    public void CompileUpdate(IReadOnlyList<ISqlNode> nodes, ISqlVisitor visitor)

    Inherits documentation from base type or interface.

    nodes: IReadOnlyList<ISqlNode>
    visitor: ISqlVisitor
  • methodCreateParameterManager
    public IParameterManager CreateParameterManager()

    Creates a new parameter manager suitable for this compiler's dialect.

    Returns: A new `IParameterManager` instance.

  • methodEscape
    public string Escape(string identifier)

    Escapes an identifier according to the specific database dialect rules.

    identifier: string
    The identifier to escape.

    Returns: The escaped identifier string.

  • methodEscapeIdentifier
    public string EscapeIdentifier(string identifier)

    Escapes an identifier only if it contains special characters or keywords, according to dialect rules.

    identifier: string
    The identifier to potentially escape.

    Returns: The escaped identifier string.

  • methodEscapeIdentifier
    public void EscapeIdentifier(System.Text.StringBuilder sb, System.ReadOnlySpan<char> identifier)

    Inherits documentation from base type or interface.

    sb: System.Text.StringBuilder
    identifier: System.ReadOnlySpan<char>
  • methodSupportsCapability
    public bool SupportsCapability(ProviderCapability capability)

    Determines whether the compiler and target database provider support a specific capability.

    capability: ProviderCapability
    The provider capability to check.

    Returns: `true` if the capability is supported; otherwise, `false`.

class

QueryAssert

Assembly: EricksonLopez.SqlBuilder.Testing
public static class QueryAssert

Provides assertion helpers for validating SQL queries and parameters in unit tests.

Members (10)

  • methodParametersMatch
    public static void ParametersMatch(SqlResult result, params(string Key, object Value)[] expectedParams)

    Asserts that the parameters match the expected keys and values.

    result: SqlResult
    The compiled SQL result whose parameters to inspect.
    expectedParams: params(string Key, object Value)[]
    The expected key-value pairs that the result parameters must contain.
  • methodQueriesMatch
    public static void QueriesMatch(ISqlQuery expected, ISqlQuery actual, ISqlCompiler compiler, bool normalizeWhitespace = true)

    Asserts that two SQL queries generate equivalent SQL and parameters.

    expected: ISqlQuery
    The reference query to compare against.
    actual: ISqlQuery
    The query being tested.
    compiler: ISqlCompiler
    The SQL compiler used to compile both queries.
    normalizeWhitespace: bool
    If `true`, collapses all whitespace before comparing SQL strings.

    Exceptions: Sdk.XunitException: The generated SQL or parameters of the two queries do not match

  • methodSqlMatches
    public static void SqlMatches(ISqlQuery query, ISqlCompiler compiler, string expectedSql)

    Asserts that the compiled query SQL matches the expected SQL.

    query: ISqlQuery
    The SQL query to compile and verify.
    compiler: ISqlCompiler
    The SQL compiler used to build the query.
    expectedSql: string
    The expected SQL string (whitespace is normalized before comparison).
  • methodSqlMatchesMySql
    public static void SqlMatchesMySql(ISqlQuery query, string expectedSql)

    Compiles the query using the MySQL compiler and asserts the SQL matches.

    query: ISqlQuery
    The SQL query to compile and verify.
    expectedSql: string
    The expected SQL string.
  • methodSqlMatchesOracle
    public static void SqlMatchesOracle(ISqlQuery query, string expectedSql)

    Compiles the query using the Oracle compiler and asserts the SQL matches.

    query: ISqlQuery
    The SQL query to compile and verify.
    expectedSql: string
    The expected SQL string.
  • methodSqlMatchesPostgreSql
    public static void SqlMatchesPostgreSql(ISqlQuery query, string expectedSql)

    Compiles the query using the PostgreSQL compiler and asserts the SQL matches.

    query: ISqlQuery
    The SQL query to compile and verify.
    expectedSql: string
    The expected SQL string.
  • methodSqlMatchesSqlServer
    public static void SqlMatchesSqlServer(ISqlQuery query, string expectedSql)

    Compiles the query using the SQL Server compiler and asserts the SQL matches.

    query: ISqlQuery
    The SQL query to compile and verify.
    expectedSql: string
    The expected SQL string.
  • methodSqlMatchesSqlite
    public static void SqlMatchesSqlite(ISqlQuery query, string expectedSql)

    Compiles the query using the SQLite compiler and asserts the SQL matches.

    query: ISqlQuery
    The SQL query to compile and verify.
    expectedSql: string
    The expected SQL string.
  • methodVerifySql
    public static Task VerifySql(ISqlQuery query, ISqlCompiler compiler)

    Compiles and verifies the SQL query using Snapshot verification.

    query: ISqlQuery
    The SQL query to compile and verify.
    compiler: ISqlCompiler
    The SQL compiler to use when building the query.

    Returns: A task representing the asynchronous snapshot verification.

  • methodVerifySql
    public static Task VerifySql(SqlResult result, object? target = null)

    Verifies the compiled SQL and parameters using Snapshot verification (Verify).

    result: SqlResult
    The compiled SQL result to verify.
    target: object?
    Reserved for future use; pass `null`.

    Returns: A task representing the asynchronous snapshot verification.

class

QueryComparer

Assembly: EricksonLopez.SqlBuilder.Testing
public static class QueryComparer

Provides comparison functionality between SQL queries, evaluating compiled SQL, AST structures, and parameters.

Members (1)

  • methodCompare
    public static QueryComparerResult Compare(ISqlQuery expected, ISqlQuery actual, ISqlCompiler compiler, bool normalizeWhitespace = true)

    Compares two queries by compiling them and comparing their AST nodes, SQL strings, and parameters.

    expected: ISqlQuery
    The reference query to compare against.
    actual: ISqlQuery
    The query being tested.
    compiler: ISqlCompiler
    The SQL compiler used to compile both queries.
    normalizeWhitespace: bool
    If `true`, collapses all whitespace before comparing SQL strings.

    Returns: A `QueryComparerResult` describing any differences found.

class

QueryComparerResult

Assembly: EricksonLopez.SqlBuilder.Testing
public class QueryComparerResult

Represents the result of comparing two SQL queries.

Members (3)

  • constructorQueryComparerResult
    public QueryComparerResult(bool areEqual, IReadOnlyList<string> differences)

    Initializes a new instance of `QueryComparerResult`.

    areEqual: bool
    Whether the two queries were found to be equivalent.
    differences: IReadOnlyList<string>
    The list of differences found between the queries.
  • propertyAreEqual
    public bool AreEqual { get; }

    Gets a value indicating whether the queries are equal.

  • propertyDifferences
    public IReadOnlyList<string> Differences { get; }

    Gets the list of differences between the queries.

class

QueryTestingExtensions

Assembly: EricksonLopez.SqlBuilder.Testing
public static class QueryTestingExtensions

Provides extension methods for fluent testing of SQL queries.

Members (2)

  • methodShouldGenerate
    public static void ShouldGenerate(this IAstQuery query, ISqlCompiler compiler, string expectedSql, params object?[] expectedParameters)

    Asserts that compiling the query generates the expected SQL and parameters.

    query: this IAstQuery
    The SQL query to compile.
    compiler: ISqlCompiler
    The SQL compiler used to build the query.
    expectedSql: string
    The expected SQL string (whitespace is normalized before comparison).
    expectedParameters: params object?[]
    The expected parameter values in the order they were bound.

    Exceptions: Exception: The compiled SQL does not match the expected SQL, or the parameter count or values do not match

  • methodVerifyQueryAsync
    public static Task VerifyQueryAsync(this IAstQuery query, ISqlCompiler compiler, string sourceFile = "")

    Compiles the query and verifies it against a Snapshot.

    query: this IAstQuery
    The SQL query to compile and snapshot.
    compiler: ISqlCompiler
    The SQL compiler used to build the query.
    sourceFile: string
    The source file path, automatically supplied by the compiler via `CompilerServices.CallerFilePathAttribute`.

    Returns: A task representing the asynchronous snapshot verification.

class

SnapshotAssert

Assembly: EricksonLopez.SqlBuilder.Testing
public static class SnapshotAssert

Provides assertion helpers for verifying SQL queries against snapshot files.

Members (5)

  • methodMatchesContract
    public static void MatchesContract(IAstQuery query, string expectedFingerprint)

    Compares the structural contract of an ISqlQuery against an expected fingerprint.

    query: IAstQuery
    The AST query whose fingerprint is to be compared.
    expectedFingerprint: string
    The expected fingerprint string.

    Exceptions: InvalidOperationException: The actual query fingerprint does not match the expected fingerprint

  • methodMatchesSnapshot
    public static void MatchesSnapshot(ISqlQuery query, ISqlCompiler compiler, string snapshotSql, bool normalizeWhitespace = true)

    Compares the compiled SQL against an inline or file snapshot string.

    query: ISqlQuery
    The SQL query to compile and compare.
    compiler: ISqlCompiler
    The SQL compiler used to build the query.
    snapshotSql: string
    The expected SQL snapshot string.
    normalizeWhitespace: bool
    If `true`, collapses all whitespace before comparing SQL strings.

    Exceptions: InvalidOperationException: The actual compiled SQL does not match the expected snapshot

  • methodVerify
    public static async Task Verify(ISqlQuery query, ISqlCompiler compiler)

    Verifies the compiled SQL and parameters of an ISqlQuery against a snapshot.

    query: ISqlQuery
    The SQL query to compile and snapshot.
    compiler: ISqlCompiler
    The SQL compiler used to build the query.

    Returns: A task representing the asynchronous snapshot verification.

  • methodVerify
    public static async Task Verify(SqlResult result)

    Verifies a SqlResult against a snapshot.

    result: SqlResult
    The compiled SQL result to snapshot.

    Returns: A task representing the asynchronous snapshot verification.

  • methodVerifyContract
    public static async Task VerifyContract(IAstQuery query)

    Verifies the structural contract of an ISqlQuery against a snapshot using Verify.

    query: IAstQuery
    The AST query whose structural contract is to be verified.

    Returns: A task representing the asynchronous snapshot verification.

class

ThreeColumnEntity

Assembly: EricksonLopez.SqlBuilder.Testing
public class ThreeColumnEntity : ISqlEntity, IStaticEntityMetadata<ThreeColumnEntity>
Implements: ISqlEntity, IStaticEntityMetadata<ThreeColumnEntity>

Represents a three-column static entity designed for testing dialect render methods with explicit column casings.

Members (21)

  • methodAreEqual
    public static bool AreEqual(ThreeColumnEntity entity, ThreeColumnEntity snapshot, int columnIndex)

    Determines whether the value of the specified column is equal between the current entity and a snapshot.

    entity: ThreeColumnEntity
    The current entity instance.
    snapshot: ThreeColumnEntity
    The original snapshot of the entity.
    columnIndex: int
    The zero-based index of the column to compare.

    Returns: `true` if the values are equal; otherwise, `false`.

  • methodBindParameter
    public static string BindParameter(ThreeColumnEntity entity, int columnIndex, IParameterManager parameters)

    Binds the value of the specified column to the provided parameter manager and returns the parameter name.

    entity: ThreeColumnEntity
    The entity containing the value to bind.
    columnIndex: int
    The zero-based index of the column.
    parameters: IParameterManager
    The parameter manager responsible for holding the bound parameter.

    Returns: The name of the bound parameter.

  • methodExtractColumnArrays
    public static void ExtractColumnArrays(ReadOnlySpan<ThreeColumnEntity> entities, ReadOnlySpan<bool> activeColumns, IParameterManager parameters)

    Extracts a batch of entities into column-based arrays and binds them to the parameter manager.

    entities: ReadOnlySpan<ThreeColumnEntity>
    A read-only span of entities to extract.
    activeColumns: ReadOnlySpan<bool>
    A read-only span of booleans indicating which columns should be extracted.
    parameters: IParameterManager
    The parameter manager where the extracted arrays will be bound.

    Supports bulk operations that rely on parameter arrays (e.g., PostgreSQL COPY or array unnesting).

  • methodFromReader
    public static ThreeColumnEntity FromReader(IDataReader reader)

    Reads and parses a single entity instance from an active `Data.IDataReader` row.

    reader: IDataReader
    The active data reader positioned at a valid row.

    Returns: A populated instance of `TEntity`.

  • methodGetAllColumnNames
    public string[] GetAllColumnNames()

    Gets all column names mapped to the entity properties, including generated ones.

    Returns: An array of all column names.

  • methodGetAllValues
    public object?[] GetAllValues()

    Gets all current values of the entity properties, including generated ones.

    Returns: An array of all property values.

  • methodGetColumnName
    public static string GetColumnName(int columnIndex)

    Retrieves the database column name for the specified column index.

    columnIndex: int
    The zero-based index of the column.

    Returns: The physical name of the column in the database.

  • methodGetColumnNames
    public string[] GetColumnNames()

    Gets the column names mapped to the entity properties, excluding generated ones.

    Returns: An array of column names.

  • methodGetColumns
    public static ReadOnlySpan<ColumnMetadata> GetColumns()

    Retrieves a read-only span containing the metadata for all mapped columns.

    Returns: A read-only span of `ColumnMetadata`.

  • methodGetIndexedColumns
    public string[] GetIndexedColumns()

    Gets the names of the columns that are indexed.

    Returns: An array of indexed column names.

  • methodGetPropertyMap
    public IReadOnlyDictionary<string, string> GetPropertyMap()

    Gets a mapping from property names to their corresponding database column names.

    Returns: A dictionary of property-to-column mappings.

  • methodGetReaderParser
    public static Func<IDataReader, ThreeColumnEntity> GetReaderParser()

    Returns a high-performance, reusable reader parser delegate for `TEntity`.

    Returns: A delegate that reads and maps reader rows into `TEntity`.

  • methodGetTableName
    public string GetTableName()

    Gets the name of the mapped database table.

    Returns: The table name.

  • methodGetValues
    public object?[] GetValues()

    Gets the current values of the entity properties, excluding generated ones.

    Returns: An array of property values.

  • methodIsDefault
    public static bool IsDefault(ThreeColumnEntity entity, int columnIndex)

    Determines whether the value of the specified column is the default value for the given entity.

    entity: ThreeColumnEntity
    The entity instance to evaluate.
    columnIndex: int
    The zero-based index of the column.

    Returns: `true` if the column value is the default value; otherwise, `false`.

  • methodIsNull
    public static bool IsNull(ThreeColumnEntity entity, int columnIndex)

    Determines whether the value of the specified column is null for the given entity.

    entity: ThreeColumnEntity
    The entity instance to evaluate.
    columnIndex: int
    The zero-based index of the column.

    Returns: `true` if the column value is null; otherwise, `false`.

  • propertyColumnCount
    public static int ColumnCount { get; }

    Gets the total number of columns mapped for the entity.

  • propertyId
    public string Id { get; set; }

    Gets or sets the identifier value.

  • propertyName
    public string Name { get; set; }

    Gets or sets the name value.

  • propertyStatus
    public string Status { get; set; }

    Gets or sets the status value.

  • propertyTableName
    public static string TableName { get; }

    Gets the name of the database table associated with the entity.

EricksonLopez.SqlBuilder.Testing.Abstractions#

1
class

CrudTestsBase<TFixture>

Assembly: EricksonLopez.SqlBuilder.Testing
public abstract class CrudTestsBase<TFixture> where TFixture : DatabaseFixture

Provides an abstract suite of database-agnostic CRUD integration tests.

Remarks:

Exercises query compilation and execution against real database fixtures across SELECT, INSERT, UPDATE, DELETE, transactions, and aggregates. Type parameters: TFixture: The database fixture type used to obtain connections and compilers.

Members (30)

  • methodDelete_Customer_ShouldRemoveFromDatabase
    public async Task Delete_Customer_ShouldRemoveFromDatabase()

    Verifies that deleting a customer removes the record from the database.

    Returns: A task representing the asynchronous unit test.

  • methodInsert_MultipleCustomers_ShouldAllPersist
    public async Task Insert_MultipleCustomers_ShouldAllPersist()

    Verifies that batch inserting multiple customers persists all inserted records.

    Returns: A task representing the asynchronous unit test.

  • methodInsert_NewCustomer_ShouldPersistToDatabase
    public async Task Insert_NewCustomer_ShouldPersistToDatabase()

    Verifies that inserting a new customer persists the record into the database.

    Returns: A task representing the asynchronous unit test.

  • methodSelect_1000OrdersWithinTimeout_ShouldComplete
    public async Task Select_1000OrdersWithinTimeout_ShouldComplete()

    Verifies that retrieving one thousand order records completes within acceptable time limits.

    Returns: A task representing the asynchronous unit test.

  • methodSelect_ActiveCustomers_ShouldReturnSubset
    public async Task Select_ActiveCustomers_ShouldReturnSubset()

    Verifies that filtering customers by active status returns only active records.

    Returns: A task representing the asynchronous unit test.

  • methodSelect_AllCustomers_ShouldReturn100Records
    public async Task Select_AllCustomers_ShouldReturn100Records()

    Verifies that selecting all customers returns all seeded customer records.

    Returns: A task representing the asynchronous unit test.

  • methodSelect_AllProducts_ShouldReturn500Records
    public async Task Select_AllProducts_ShouldReturn500Records()

    Verifies that selecting all products returns all seeded product records.

    Returns: A task representing the asynchronous unit test.

  • methodSelect_CountAggregate_ShouldReturnAtLeast100
    public async Task Select_CountAggregate_ShouldReturnAtLeast100()

    Verifies that calculating a COUNT aggregate returns at least one hundred customer rows.

    Returns: A task representing the asynchronous unit test.

  • methodSelect_CustomerById_ShouldReturnExactlyOne
    public async Task Select_CustomerById_ShouldReturnExactlyOne()

    Verifies that querying a customer by primary key returns exactly one matching record.

    Returns: A task representing the asynchronous unit test.

  • methodSelect_Distinct_ShouldReturnUniqueStatuses
    public async Task Select_Distinct_ShouldReturnUniqueStatuses()

    Verifies that selecting distinct column values returns deduplicated results.

    Returns: A task representing the asynchronous unit test.

  • methodSelect_EmptyResult_ShouldReturnEmptyList
    public async Task Select_EmptyResult_ShouldReturnEmptyList()

    Verifies that querying with a non-matching predicate returns an empty collection.

    Returns: A task representing the asynchronous unit test.

  • methodSelect_GroupByStatus_ShouldReturnGroupCounts
    public async Task Select_GroupByStatus_ShouldReturnGroupCounts()

    Verifies that grouping rows by status computes correct aggregate counts per group.

    Returns: A task representing the asynchronous unit test.

  • methodSelect_InnerJoin_OrdersWithCustomers_ShouldReturnJoinedRows
    public async Task Select_InnerJoin_OrdersWithCustomers_ShouldReturnJoinedRows()

    Verifies that inner joining orders with customers produces joined result rows.

    Returns: A task representing the asynchronous unit test.

  • methodSelect_MaxProductPrice_ShouldBePositive
    public async Task Select_MaxProductPrice_ShouldBePositive()

    Verifies that calculating the MAX price aggregate produces a positive value.

    Returns: A task representing the asynchronous unit test.

  • methodSelect_NonDeletedOrders_ShouldReturnMostOrders
    public async Task Select_NonDeletedOrders_ShouldReturnMostOrders()

    Verifies that querying non-deleted orders excludes soft-deleted records.

    Returns: A task representing the asynchronous unit test.

  • methodSelect_NonExistentCustomer_ShouldReturnNull
    public async Task Select_NonExistentCustomer_ShouldReturnNull()

    Verifies that querying a non-existent customer by identifier returns `null`.

    Returns: A task representing the asynchronous unit test.

  • methodSelect_NullablePhone_ShouldHandleNullsWithoutException
    public async Task Select_NullablePhone_ShouldHandleNullsWithoutException()

    Verifies that querying nullable columns handles null values without errors.

    Returns: A task representing the asynchronous unit test.

  • methodSelect_OrderItems_ShouldHaveAtLeast1000Records
    public async Task Select_OrderItems_ShouldHaveAtLeast1000Records()

    Verifies that selecting order items returns at least one thousand seeded records.

    Returns: A task representing the asynchronous unit test.

  • methodSelect_OrderedByNameDescending_ShouldReturnSortedResults
    public async Task Select_OrderedByNameDescending_ShouldReturnSortedResults()

    Verifies that ordering customers by name descending produces sorted results.

    Returns: A task representing the asynchronous unit test.

  • methodSelect_OrdersByCustomer_ShouldReturnExactCount
    public async Task Select_OrdersByCustomer_ShouldReturnExactCount()

    Verifies that filtering orders by customer identifier returns the exact count of customer orders.

    Returns: A task representing the asynchronous unit test.

  • methodSelect_Paginated_ShouldReturnCorrectPage
    public async Task Select_Paginated_ShouldReturnCorrectPage()

    Verifies that paginating customer queries with limit and offset returns the expected page size.

    Returns: A task representing the asynchronous unit test.

  • methodSelect_ProductsAboveMinPrice_ShouldFilterCorrectly
    public async Task Select_ProductsAboveMinPrice_ShouldFilterCorrectly()

    Verifies that filtering products above a minimum price returns only matching products.

    Returns: A task representing the asynchronous unit test.

  • methodSelect_SpecificColumns_ShouldReturnPartialData
    public async Task Select_SpecificColumns_ShouldReturnPartialData()

    Verifies that selecting specific columns returns partial entity projections.

    Returns: A task representing the asynchronous unit test.

  • methodSelect_SumOrderRevenue_ShouldBePositive
    public async Task Select_SumOrderRevenue_ShouldBePositive()

    Verifies that calculating the SUM of order total amounts produces a positive total.

    Returns: A task representing the asynchronous unit test.

  • methodSelect_WithCTE_ActiveProducts_ShouldWork
    public async Task Select_WithCTE_ActiveProducts_ShouldWork()

    Verifies that queries using common table expressions execute successfully.

    Returns: A task representing the asynchronous unit test.

  • methodSoftDelete_Order_ShouldSetIsDeletedFlag
    public async Task SoftDelete_Order_ShouldSetIsDeletedFlag()

    Verifies that soft deleting an order sets the deletion flag.

    Returns: A task representing the asynchronous unit test.

  • methodTransaction_Commit_ShouldPersistChanges
    public async Task Transaction_Commit_ShouldPersistChanges()

    Verifies that committed database transactions persist inserted changes.

    Returns: A task representing the asynchronous unit test.

    Exceptions: InvalidOperationException: The connection provided by the fixture is not a `Common.DbConnection`

  • methodTransaction_Rollback_ShouldDiscardChanges
    public async Task Transaction_Rollback_ShouldDiscardChanges()

    Verifies that rolled back database transactions discard pending changes.

    Returns: A task representing the asynchronous unit test.

    Exceptions: InvalidOperationException: The connection provided by the fixture is not a `Common.DbConnection`

  • methodUpdate_CustomerName_ShouldPersistChange
    public async Task Update_CustomerName_ShouldPersistChange()

    Verifies that updating a customer name persists the modified value in the database.

    Returns: A task representing the asynchronous unit test.

  • methodUpdate_DeactivateCustomer_ShouldSetIsActiveFalse
    public async Task Update_DeactivateCustomer_ShouldSetIsActiveFalse()

    Verifies that deactivating a customer updates the active flag to false.

    Returns: A task representing the asynchronous unit test.

EricksonLopez.SqlBuilder.Testing.DataBuilders#

6
class

CustomerBuilder

Assembly: EricksonLopez.SqlBuilder.Testing
public sealed class CustomerBuilder

Provides a fluent test data builder for creating `Customer` instances.

Members (7)

  • methodBuild
    public Customer Build()

    Builds and returns a new `Customer` instance with the configured values.

    Returns: A configured `Customer` instance.

  • methodCreate
    public static CustomerBuilder Create()

    Creates a new instance of the `CustomerBuilder` class.

    Returns: A new `CustomerBuilder` instance.

  • methodWithActive
    public CustomerBuilder WithActive(bool isActive)

    Sets the active status for the customer being built.

    isActive: bool
    A value indicating whether the customer is active.

    Returns: This builder instance for fluent chaining.

  • methodWithEmail
    public CustomerBuilder WithEmail(string email)

    Sets the email address for the customer being built.

    email: string
    The customer email address.

    Returns: This builder instance for fluent chaining.

  • methodWithId
    public CustomerBuilder WithId(int id)

    Sets the identifier for the customer being built.

    id: int
    The customer identifier.

    Returns: This builder instance for fluent chaining.

  • methodWithName
    public CustomerBuilder WithName(string name)

    Sets the name for the customer being built.

    name: string
    The customer name.

    Returns: This builder instance for fluent chaining.

  • methodWithPhone
    public CustomerBuilder WithPhone(string phone)

    Sets the phone number for the customer being built.

    phone: string
    The customer phone number.

    Returns: This builder instance for fluent chaining.

class

ObjectMother

Assembly: EricksonLopez.SqlBuilder.Testing
public static class ObjectMother

Provides pre-configured domain entity instances for testing scenarios.

Members (11)

  • methodCreateAddress
    public static Address CreateAddress(int id = 1, int customerId = 1, string addressType = "")

    Creates a pre-configured `Address` instance with optional overrides.

    id: int
    The unique identifier for the address.
    customerId: int
    The identifier of the customer associated with the address.
    addressType: string
    The classification type of the address (e.g., shipping or billing).

    Returns: A new `Address` instance initialized with test data.

  • methodCreateAuditLog
    public static AuditLog CreateAuditLog(int id = 1, string entityName = "", string action = "")

    Creates a pre-configured `AuditLog` instance with optional overrides.

    id: int
    The unique identifier for the audit record.
    entityName: string
    The name of the audited entity.
    action: string
    The audited operation name.

    Returns: A new `AuditLog` instance initialized with test data.

  • methodCreateCategory
    public static Category CreateCategory(int id = 1, string name = "")

    Creates a pre-configured `Category` instance with optional overrides.

    id: int
    The unique identifier for the category.
    name: string
    The display name of the category.

    Returns: A new `Category` instance initialized with test data.

  • methodCreateCustomer
    public static Customer CreateCustomer(int id = 1, string name = "", string email = "", bool isActive = true)

    Creates a pre-configured `Customer` instance with optional overrides.

    id: int
    The unique identifier for the customer.
    name: string
    The customer name.
    email: string
    The customer email address.
    isActive: bool
    `true` if the customer is active; otherwise, `false`.

    Returns: A new `Customer` instance initialized with test data.

  • methodCreateInvoice
    public static Invoice CreateInvoice(int id = 1, int orderId = 1, decimal amount = 150.00m)

    Creates a pre-configured `Invoice` instance with optional overrides.

    id: int
    The unique identifier for the invoice.
    orderId: int
    The parent order identifier.
    amount: decimal
    The total billed invoice amount.

    Returns: A new `Invoice` instance initialized with test data.

  • methodCreateOrder
    public static Order CreateOrder(int id = 1, int customerId = 1, decimal totalAmount = 150.00m, string status = "")

    Creates a pre-configured `Order` instance with optional overrides.

    id: int
    The unique identifier for the order.
    customerId: int
    The identifier of the customer placing the order.
    totalAmount: decimal
    The total order amount.
    status: string
    The order status string.

    Returns: A new `Order` instance initialized with test data.

  • methodCreateOrderItem
    public static OrderItem CreateOrderItem(int id = 1, int orderId = 1, int productId = 1, int quantity = 2, decimal unitPrice = 75.00m)

    Creates a pre-configured `OrderItem` instance with optional overrides.

    id: int
    The unique identifier for the order item.
    orderId: int
    The parent order identifier.
    productId: int
    The purchased product identifier.
    quantity: int
    The purchased quantity.
    unitPrice: decimal
    The price per unit.

    Returns: A new `OrderItem` instance initialized with test data.

  • methodCreatePayment
    public static Payment CreatePayment(int id = 1, int invoiceId = 1, decimal amount = 150.00m)

    Creates a pre-configured `Payment` instance with optional overrides.

    id: int
    The unique identifier for the payment transaction.
    invoiceId: int
    The identifier of the paid invoice.
    amount: decimal
    The payment transaction amount.

    Returns: A new `Payment` instance initialized with test data.

  • methodCreateProduct
    public static Product CreateProduct(int id = 1, string name = "", decimal price = 999.99m, int stock = 50, int categoryId = 1)

    Creates a pre-configured `Product` instance with optional overrides.

    id: int
    The unique identifier for the product.
    name: string
    The product name.
    price: decimal
    The retail price of the product.
    stock: int
    The quantity available in stock.
    categoryId: int
    The identifier of the product category.

    Returns: A new `Product` instance initialized with test data.

  • methodCreateTestEntity
    public static TestEntity CreateTestEntity(int id = 1, string name = "", bool isActive = true)

    Creates a pre-configured `TestEntity` instance with optional overrides.

    id: int
    The unique identifier for the entity.
    name: string
    The entity name.
    isActive: bool
    `true` if the entity is active; otherwise, `false`.

    Returns: A new `TestEntity` instance initialized with test data.

  • methodCreateUser
    public static User CreateUser(int id = 1, string name = "", bool isActive = true)

    Creates a pre-configured `User` instance with optional overrides.

    id: int
    The unique identifier for the user.
    name: string
    The username and first name of the user.
    isActive: bool
    `true` if the user is active; otherwise, `false`.

    Returns: A new `User` instance initialized with test data.

class

OrderBuilder

Assembly: EricksonLopez.SqlBuilder.Testing
public sealed class OrderBuilder

Provides a fluent test data builder for creating `Order` instances.

Members (8)

  • methodBuild
    public Order Build()

    Builds and returns a new `Order` instance with the configured values.

    Returns: A configured `Order` instance.

  • methodCreate
    public static OrderBuilder Create()

    Creates a new instance of the `OrderBuilder` class.

    Returns: A new `OrderBuilder` instance.

  • methodWithCurrency
    public OrderBuilder WithCurrency(string currency)

    Sets the currency code for the order being built.

    currency: string
    The currency code.

    Returns: This builder instance for fluent chaining.

  • methodWithCustomerId
    public OrderBuilder WithCustomerId(int customerId)

    Sets the customer identifier for the order being built.

    customerId: int
    The customer identifier.

    Returns: This builder instance for fluent chaining.

  • methodWithDeleted
    public OrderBuilder WithDeleted(bool isDeleted)

    Sets a value indicating whether the order being built is marked as soft-deleted.

    isDeleted: bool
    A value indicating whether the order is soft-deleted.

    Returns: This builder instance for fluent chaining.

  • methodWithId
    public OrderBuilder WithId(int id)

    Sets the identifier for the order being built.

    id: int
    The order identifier.

    Returns: This builder instance for fluent chaining.

  • methodWithStatus
    public OrderBuilder WithStatus(string status)

    Sets the order lifecycle status for the order being built.

    status: string
    The order status.

    Returns: This builder instance for fluent chaining.

  • methodWithTotalAmount
    public OrderBuilder WithTotalAmount(decimal totalAmount)

    Sets the total monetary amount for the order being built.

    totalAmount: decimal
    The total order amount.

    Returns: This builder instance for fluent chaining.

class

ProductBuilder

Assembly: EricksonLopez.SqlBuilder.Testing
public sealed class ProductBuilder

Provides a fluent test data builder for creating `Product` instances.

Members (10)

  • methodBuild
    public Product Build()

    Builds and returns the configured `Product` instance.

    Returns: A new `Product` instance initialized with configured properties.

  • methodCreate
    public static ProductBuilder Create()

    Creates a new instance of the `ProductBuilder` class.

    Returns: A new `ProductBuilder` instance.

  • methodWithActive
    public ProductBuilder WithActive(bool isActive)

    Sets a value indicating whether the product being built is active.

    isActive: bool
    `true` if the product is active; otherwise, `false`.

    Returns: This builder instance for fluent chaining.

  • methodWithCategoryId
    public ProductBuilder WithCategoryId(int categoryId)

    Sets the category identifier for the product being built.

    categoryId: int
    The category identifier.

    Returns: This builder instance for fluent chaining.

  • methodWithCostPrice
    public ProductBuilder WithCostPrice(decimal costPrice)

    Sets the cost price for the product being built.

    costPrice: decimal
    The wholesale or cost price.

    Returns: This builder instance for fluent chaining.

  • methodWithId
    public ProductBuilder WithId(int id)

    Sets the identifier for the product being built.

    id: int
    The product identifier.

    Returns: This builder instance for fluent chaining.

  • methodWithName
    public ProductBuilder WithName(string name)

    Sets the name for the product being built.

    name: string
    The product name.

    Returns: This builder instance for fluent chaining.

  • methodWithPrice
    public ProductBuilder WithPrice(decimal price)

    Sets the selling price for the product being built.

    price: decimal
    The retail selling price.

    Returns: This builder instance for fluent chaining.

  • methodWithSku
    public ProductBuilder WithSku(string sku)

    Sets the SKU code for the product being built.

    sku: string
    The stock keeping unit identifier.

    Returns: This builder instance for fluent chaining.

  • methodWithStock
    public ProductBuilder WithStock(int stock)

    Sets the available stock count for the product being built.

    stock: int
    The quantity available in stock.

    Returns: This builder instance for fluent chaining.

class

TestEntity

Assembly: EricksonLopez.SqlBuilder.Testing
public partial class TestEntity

Represents a simple test entity designed for generic query tests.

Members (3)

  • propertyId
    public int Id { get; set; }

    Gets or sets the primary key identifier of the test entity.

  • propertyIsActive
    public bool IsActive { get; set; }

    Gets or sets a value indicating whether the test entity is active.

  • propertyName
    public string Name { get; set; }

    Gets or sets the name of the test entity.

class

UserBuilder

Assembly: EricksonLopez.SqlBuilder.Testing
public sealed class UserBuilder

Provides a fluent test data builder for creating `User` instances.

Members (8)

  • methodBuild
    public User Build()

    Builds and returns the configured `User` instance.

    Returns: A new `User` instance initialized with configured properties.

  • methodCreate
    public static UserBuilder Create()

    Creates a new instance of the `UserBuilder` class.

    Returns: A new `UserBuilder` instance.

  • methodWithActive
    public UserBuilder WithActive(bool isActive)

    Sets a value indicating whether the user being built is active.

    isActive: bool
    `true` if the user is active; otherwise, `false`.

    Returns: This builder instance for fluent chaining.

  • methodWithCreatedAt
    public UserBuilder WithCreatedAt(DateTime createdAt)

    Sets the creation timestamp for the user being built.

    createdAt: DateTime
    The creation date and time in UTC.

    Returns: This builder instance for fluent chaining.

  • methodWithEmail
    public UserBuilder WithEmail(string email)

    Sets the email address for the user being built.

    email: string
    The email address.

    Returns: This builder instance for fluent chaining.

  • methodWithFailedLoginAttempts
    public UserBuilder WithFailedLoginAttempts(int count)

    Sets the count of failed login attempts for the user being built.

    count: int
    The number of failed login attempts.

    Returns: This builder instance for fluent chaining.

  • methodWithId
    public UserBuilder WithId(int id)

    Sets the identifier for the user being built.

    id: int
    The user identifier.

    Returns: This builder instance for fluent chaining.

  • methodWithUsername
    public UserBuilder WithUsername(string username)

    Sets the username for the user being built, and automatically derives an email address.

    username: string
    The username.

    Returns: This builder instance for fluent chaining.

EricksonLopez.SqlBuilder.Testing.Domain#

15
class

Address

Assembly: EricksonLopez.SqlBuilder.Testing
public partial class Address

Represents a shipping or billing address associated with a customer.

Members (9)

  • propertyAddressType
    public string AddressType { get; set; }

    Gets or sets the address type classification, such as shipping or billing.

  • propertyCity
    public string City { get; set; }

    Gets or sets the city of the address.

  • propertyCountry
    public string Country { get; set; }

    Gets or sets the country of the address.

  • propertyCustomerId
    public int CustomerId { get; set; }

    Gets or sets the identifier of the customer associated with this address.

  • propertyId
    public int Id { get; set; }

    Gets or sets the primary key identifier of the address.

  • propertyIsDefault
    public bool IsDefault { get; set; }

    Gets or sets a value indicating whether this is the default address for the customer.

  • propertyPostalCode
    public string PostalCode { get; set; }

    Gets or sets the postal code or ZIP code of the address.

  • propertyState
    public string State { get; set; }

    Gets or sets the state, province, or region of the address.

  • propertyStreet
    public string Street { get; set; }

    Gets or sets the street line of the address.

class

AuditLog

Assembly: EricksonLopez.SqlBuilder.Testing
public partial class AuditLog

Represents an immutable audit trail record for entity changes.

Members (12)

  • propertyAction
    public string Action { get; set; }

    Gets or sets the audited database action, such as INSERT, UPDATE, or DELETE.

  • propertyChangedFields
    public string? ChangedFields { get; set; }

    Gets or sets the serialized JSON array containing the names of modified fields.

  • propertyCorrelationId
    public string? CorrelationId { get; set; }

    Gets or sets the distributed tracing or request correlation identifier.

  • propertyEntityId
    public string EntityId { get; set; }

    Gets or sets the string representation of the modified entity identifier.

  • propertyEntityName
    public string EntityName { get; set; }

    Gets or sets the name of the entity associated with the audited action.

  • propertyId
    public long Id { get; set; }

    Gets or sets the primary key identifier of the audit log entry.

  • propertyIpAddress
    public string? IpAddress { get; set; }

    Gets or sets the IP address of the client that originated the change.

  • propertyNewValues
    public string? NewValues { get; set; }

    Gets or sets the serialized JSON representation of the entity state after the change.

  • propertyOldValues
    public string? OldValues { get; set; }

    Gets or sets the serialized JSON representation of the entity state before the change.

  • propertyTimestamp
    public DateTime Timestamp { get; set; }

    Gets or sets the UTC timestamp when the change occurred.

  • propertyUserAgent
    public string? UserAgent { get; set; }

    Gets or sets the client user-agent string that originated the change.

  • propertyUserId
    public int? UserId { get; set; }

    Gets or sets the identifier of the user who performed the action.

class

Category

Assembly: EricksonLopez.SqlBuilder.Testing
public partial class Category

Represents a product category supporting hierarchical parent-child structure.

Members (6)

  • propertyId
    public int Id { get; set; }

    Gets or sets the primary key identifier of the category.

  • propertyIsActive
    public bool IsActive { get; set; }

    Gets or sets a value indicating whether the category is currently active.

  • propertyName
    public string Name { get; set; }

    Gets or sets the display name of the category.

  • propertyParentCategoryId
    public int? ParentCategoryId { get; set; }

    Gets or sets the optional parent category identifier for hierarchical categorization.

  • propertySlug
    public string Slug { get; set; }

    Gets or sets the URL-friendly unique slug for the category.

  • propertySortOrder
    public int SortOrder { get; set; }

    Gets or sets the sequential display ordering index for the category.

class

CrudUser

Assembly: EricksonLopez.SqlBuilder.Testing
public partial class CrudUser

Represents a user entity for integration CRUD tests. Maps to the 'users' table across integration test fixtures.

Members (5)

  • propertyAge
    public int Age { get; set; }

    Gets or sets the age in years of the user.

  • propertyCreatedAt
    public DateTime CreatedAt { get; set; }

    Gets or sets the UTC timestamp when the user was created.

  • propertyId
    public int Id { get; set; }

    Gets or sets the primary key identifier of the user.

  • propertyIsActive
    public bool IsActive { get; set; }

    Gets or sets a value indicating whether the user is active.

  • propertyName
    public string Name { get; set; }

    Gets or sets the full name of the user.

class

Customer

Assembly: EricksonLopez.SqlBuilder.Testing
public partial class Customer

Represents a business customer (B2B or B2C).

Members (8)

  • propertyCreatedAt
    public DateTime CreatedAt { get; set; }

    Gets or sets the UTC timestamp when the customer record was created.

  • propertyEmail
    public string Email { get; set; }

    Gets or sets the primary contact email address of the customer.

  • propertyId
    public int Id { get; set; }

    Gets or sets the primary key identifier of the customer.

  • propertyIsActive
    public bool IsActive { get; set; }

    Gets or sets a value indicating whether the customer account is active.

  • propertyName
    public string Name { get; set; }

    Gets or sets the full legal or trade name of the customer.

  • propertyPhone
    public string? Phone { get; set; }

    Gets or sets the contact telephone number of the customer.

  • propertyTaxId
    public string? TaxId { get; set; }

    Gets or sets the tax identification or VAT number of the customer.

  • propertyUpdatedAt
    public DateTime? UpdatedAt { get; set; }

    Gets or sets the optional UTC timestamp when the customer record was last updated.

class

Invoice

Assembly: EricksonLopez.SqlBuilder.Testing
public partial class Invoice

Represents a tax invoice issued for an order.

Members (13)

  • propertyCurrency
    public string Currency { get; set; }

    Gets or sets the three-letter ISO currency code for the invoice amounts.

  • propertyDueAt
    public DateTime DueAt { get; set; }

    Gets or sets the UTC timestamp by which payment on the invoice is due.

  • propertyId
    public int Id { get; set; }

    Gets or sets the primary key identifier of the invoice.

  • propertyInvoiceNumber
    public string InvoiceNumber { get; set; }

    Gets or sets the alphanumeric reference number assigned to the invoice.

  • propertyIssuedAt
    public DateTime IssuedAt { get; set; }

    Gets or sets the UTC timestamp when the invoice was issued.

  • propertyNotes
    public string? Notes { get; set; }

    Gets or sets optional remarks, payment terms, or notes on the invoice.

  • propertyOrderId
    public int OrderId { get; set; }

    Gets or sets the identifier of the order associated with this invoice.

  • propertyPaidAmount
    public decimal PaidAmount { get; set; }

    Gets or sets the amount that has been paid toward the invoice balance.

  • propertyPaidAt
    public DateTime? PaidAt { get; set; }

    Gets or sets the optional UTC timestamp when the invoice was fully paid.

  • propertyStatus
    public string Status { get; set; }

    Gets or sets the status of the invoice, such as draft, issued, paid, overdue, or cancelled.

  • propertySubtotalAmount
    public decimal SubtotalAmount { get; set; }

    Gets or sets the pre-tax subtotal amount of the invoice.

  • propertyTaxAmount
    public decimal TaxAmount { get; set; }

    Gets or sets the total tax amount applied to the invoice.

  • propertyTotalAmount
    public decimal TotalAmount { get; set; }

    Gets or sets the total amount payable on the invoice, including taxes.

class

OracleCrudUser

Assembly: EricksonLopez.SqlBuilder.Testing
public partial class OracleCrudUser

Represents a user entity for Oracle integration CRUD tests. Maps to the 'TEST_USERS' table in Oracle.

Members (5)

  • propertyAge
    public int Age { get; set; }

    Gets or sets the age in years of the user.

  • propertyCreatedAt
    public DateTime CreatedAt { get; set; }

    Gets or sets the UTC timestamp when the user was created.

  • propertyId
    public int Id { get; set; }

    Gets or sets the primary key identifier of the user.

  • propertyIsActive
    public bool IsActive { get; set; }

    Gets or sets a value indicating whether the user is active.

  • propertyName
    public string Name { get; set; }

    Gets or sets the full name of the user.

class

Order

Assembly: EricksonLopez.SqlBuilder.Testing
public partial class Order

Represents a customer purchase order.

Members (14)

  • propertyConfirmedAt
    public DateTime? ConfirmedAt { get; set; }

    Gets or sets the optional UTC timestamp when the order was confirmed.

  • propertyCreatedAt
    public DateTime CreatedAt { get; set; }

    Gets or sets the UTC timestamp when the order was created.

  • propertyCurrency
    public string Currency { get; set; }

    Gets or sets the three-letter ISO currency code for the order amounts.

  • propertyCustomerId
    public int CustomerId { get; set; }

    Gets or sets the identifier of the customer who placed the order.

  • propertyDeletedAt
    public DateTime? DeletedAt { get; set; }

    Gets or sets the optional UTC timestamp when the order was soft-deleted.

  • propertyDeliveredAt
    public DateTime? DeliveredAt { get; set; }

    Gets or sets the optional UTC timestamp when the order was delivered.

  • propertyDiscountAmount
    public decimal DiscountAmount { get; set; }

    Gets or sets the total promotional discount amount deducted from the order.

  • propertyId
    public int Id { get; set; }

    Gets or sets the primary key identifier of the order.

  • propertyIsDeleted
    public bool IsDeleted { get; set; }

    Gets or sets a value indicating whether the order has been soft-deleted.

  • propertyNotes
    public string? Notes { get; set; }

    Gets or sets optional delivery or order instructions.

  • propertyShippedAt
    public DateTime? ShippedAt { get; set; }

    Gets or sets the optional UTC timestamp when the order was dispatched.

  • propertyStatus
    public string Status { get; set; }

    Gets or sets the order lifecycle status, such as pending, confirmed, shipped, delivered, or cancelled.

  • propertyTaxAmount
    public decimal TaxAmount { get; set; }

    Gets or sets the total tax amount applied to the order.

  • propertyTotalAmount
    public decimal TotalAmount { get; set; }

    Gets or sets the total monetary amount of the order, including taxes and discounts.

class

OrderItem

Assembly: EricksonLopez.SqlBuilder.Testing
public partial class OrderItem

Represents a line item in a customer order.

Members (8)

  • propertyDiscountPercent
    public decimal DiscountPercent { get; set; }

    Gets or sets the discount percentage applied to this line item.

  • propertyId
    public int Id { get; set; }

    Gets or sets the primary key identifier of the order item.

  • propertyNotes
    public string? Notes { get; set; }

    Gets or sets optional item-level customization or notes.

  • propertyOrderId
    public int OrderId { get; set; }

    Gets or sets the identifier of the order this item belongs to.

  • propertyProductId
    public int ProductId { get; set; }

    Gets or sets the identifier of the ordered product.

  • propertyQuantity
    public int Quantity { get; set; }

    Gets or sets the number of units ordered.

  • propertyTotalPrice
    public decimal TotalPrice { get; set; }

    Gets or sets the calculated total line price after discounts.

  • propertyUnitPrice
    public decimal UnitPrice { get; set; }

    Gets or sets the unit price of the product at the time of purchase.

class

Payment

Assembly: EricksonLopez.SqlBuilder.Testing
public partial class Payment

Represents a payment transaction applied to an invoice.

Members (10)

  • propertyAmount
    public decimal Amount { get; set; }

    Gets or sets the monetary amount processed in the payment transaction.

  • propertyGatewayResponse
    public string? GatewayResponse { get; set; }

    Gets or sets the raw response payload returned by the payment gateway.

  • propertyId
    public int Id { get; set; }

    Gets or sets the primary key identifier of the payment.

  • propertyInvoiceId
    public int InvoiceId { get; set; }

    Gets or sets the identifier of the invoice being paid.

  • propertyMethod
    public string Method { get; set; }

    Gets or sets the payment method used, such as credit_card, bank_transfer, paypal, or stripe.

  • propertyPaidAt
    public DateTime PaidAt { get; set; }

    Gets or sets the UTC timestamp when the payment was processed.

  • propertyRefundedAmount
    public decimal? RefundedAmount { get; set; }

    Gets or sets the optional monetary amount that was refunded.

  • propertyRefundedAt
    public DateTime? RefundedAt { get; set; }

    Gets or sets the optional UTC timestamp when the payment was refunded.

  • propertyStatus
    public string Status { get; set; }

    Gets or sets the transaction status, such as pending, completed, failed, or refunded.

  • propertyTransactionRef
    public string? TransactionRef { get; set; }

    Gets or sets the external transaction or gateway reference number.

class

Product

Assembly: EricksonLopez.SqlBuilder.Testing
public partial class Product

Represents a product in the catalog.

Members (12)

  • propertyCategoryId
    public int CategoryId { get; set; }

    Gets or sets the category identifier to which this product belongs.

  • propertyCostPrice
    public decimal CostPrice { get; set; }

    Gets or sets the wholesale or acquisition cost price of the product.

  • propertyCreatedAt
    public DateTime CreatedAt { get; set; }

    Gets or sets the UTC timestamp when the product was created.

  • propertyDescription
    public string? Description { get; set; }

    Gets or sets optional descriptive text or marketing copy for the product.

  • propertyId
    public int Id { get; set; }

    Gets or sets the primary key identifier of the product.

  • propertyIsActive
    public bool IsActive { get; set; }

    Gets or sets a value indicating whether the product is active for sales.

  • propertyMinStock
    public int MinStock { get; set; }

    Gets or sets the minimum inventory reorder threshold quantity.

  • propertyName
    public string Name { get; set; }

    Gets or sets the display name of the product.

  • propertyPrice
    public decimal Price { get; set; }

    Gets or sets the retail sales price of the product.

  • propertySku
    public string Sku { get; set; }

    Gets or sets the Stock Keeping Unit (SKU) identifying the product variant.

  • propertyStock
    public int Stock { get; set; }

    Gets or sets the currently available inventory quantity in stock.

  • propertyUpdatedAt
    public DateTime? UpdatedAt { get; set; }

    Gets or sets the optional UTC timestamp when the product was last updated.

class

Role

Assembly: EricksonLopez.SqlBuilder.Testing
public partial class Role

Represents an authorization role.

Members (6)

  • propertyCreatedAt
    public DateTime CreatedAt { get; set; }

    Gets or sets the UTC timestamp when the role was created.

  • propertyDescription
    public string? Description { get; set; }

    Gets or sets an optional description explaining the responsibilities of the role.

  • propertyId
    public int Id { get; set; }

    Gets or sets the primary key identifier of the role.

  • propertyIsSystem
    public bool IsSystem { get; set; }

    Gets or sets a value indicating whether this is a built-in immutable system role.

  • propertyName
    public string Name { get; set; }

    Gets or sets the unique name of the role, such as admin, manager, or viewer.

  • propertyPermissions
    public string Permissions { get; set; }

    Gets or sets the serialized JSON array of permission strings granted to the role.

class

TestUser

Assembly: EricksonLopez.SqlBuilder.Testing
public partial class TestUser

Represents a test user entity mapped to the `test_users` database table, used in integration and unit tests that exercise SQL generation and CRUD operations.

Members (6)

  • propertyAge
    public int Age { get; set; }

    Gets or sets the age of the user.

  • propertyCreatedAt
    public DateTime CreatedAt { get; set; }

    Gets or sets the UTC timestamp at which the user record was created.

  • propertyEmail
    public string Email { get; set; }

    Gets or sets the email address of the user.

  • propertyId
    public int Id { get; set; }

    Gets or sets the database-generated primary key identifier.

  • propertyIsActive
    public bool IsActive { get; set; }

    Gets or sets a value indicating whether the user account is active.

  • propertyName
    public string Name { get; set; }

    Gets or sets the display name of the user.

class

User

Assembly: EricksonLopez.SqlBuilder.Testing
public partial class User

Represents an application user authentication identity.

Members (12)

  • propertyCreatedAt
    public DateTime CreatedAt { get; set; }

    Gets or sets the UTC timestamp when the user account was registered.

  • propertyEmail
    public string Email { get; set; }

    Gets or sets the primary email address of the user.

  • propertyEmailVerified
    public bool EmailVerified { get; set; }

    Gets or sets a value indicating whether the user's email address has been verified.

  • propertyFailedLoginAttempts
    public int FailedLoginAttempts { get; set; }

    Gets or sets the count of consecutive failed authentication attempts.

  • propertyFirstName
    public string? FirstName { get; set; }

    Gets or sets the optional first name of the user.

  • propertyId
    public int Id { get; set; }

    Gets or sets the primary key identifier of the user.

  • propertyIsActive
    public bool IsActive { get; set; }

    Gets or sets a value indicating whether the user account is active.

  • propertyLastLoginAt
    public DateTime? LastLoginAt { get; set; }

    Gets or sets the optional UTC timestamp of the user's most recent login.

  • propertyLastName
    public string? LastName { get; set; }

    Gets or sets the optional last name or surname of the user.

  • propertyLockedUntil
    public DateTime? LockedUntil { get; set; }

    Gets or sets the optional UTC timestamp until which the user account is temporarily locked.

  • propertyPasswordHash
    public string PasswordHash { get; set; }

    Gets or sets the secure cryptographic hash of the user's password.

  • propertyUsername
    public string Username { get; set; }

    Gets or sets the unique username for login authentication.

class

UserRole

Assembly: EricksonLopez.SqlBuilder.Testing
public partial class UserRole

Represents a junction table entry for a many-to-many user-role relationship.

Members (4)

  • propertyAssignedAt
    public DateTime AssignedAt { get; set; }

    Gets or sets the UTC timestamp when the role was assigned to the user.

  • propertyAssignedByUserId
    public int? AssignedByUserId { get; set; }

    Gets or sets the optional identifier of the administrator who assigned the role.

  • propertyRoleId
    public int RoleId { get; set; }

    Gets or sets the identifier of the assigned role.

  • propertyUserId
    public int UserId { get; set; }

    Gets or sets the identifier of the assigned user.

EricksonLopez.SqlBuilder.Testing.Infrastructure#

9
class

CrudTestsBase<TFixture>

Assembly: EricksonLopez.SqlBuilder.Testing
public abstract class CrudTestsBase<TFixture> : IClassFixture<TFixture> where TFixture : DatabaseFixture
Implements: IClassFixture<TFixture>

Provides a reusable suite of CRUD integration tests for a given database fixture.

Remarks:

Subclasses bind a concrete `TFixture` implementation, allowing the same test logic to run against multiple database backends. Type parameters: TFixture: The database fixture that creates connections for the target database.

Members (4)

  • methodDelete_Customer_ShouldRemoveFromDatabase
    public async Task Delete_Customer_ShouldRemoveFromDatabase()

    Verifies that deleting a customer removes the record from the database.

    Returns: A task representing the asynchronous unit test.

  • methodInsert_NewCustomer_ShouldPersistToDatabase
    public async Task Insert_NewCustomer_ShouldPersistToDatabase()

    Verifies that inserting a new customer persists the record into the database.

    Returns: A task representing the asynchronous unit test.

  • methodSelect_CountAggregate_ShouldReturnExpectedRecords
    public async Task Select_CountAggregate_ShouldReturnExpectedRecords()

    Verifies that counting rows from a customer query returns expected records.

    Returns: A task representing the asynchronous unit test.

  • methodUpdate_CustomerName_ShouldPersistChange
    public async Task Update_CustomerName_ShouldPersistChange()

    Verifies that updating a customer name persists the modified value in the database.

    Returns: A task representing the asynchronous unit test.

class

DatabaseFixture

Assembly: EricksonLopez.SqlBuilder.Testing
public abstract class DatabaseFixture : IAsyncLifetime
Implements: IAsyncLifetime

Provides an abstract base class for database test fixtures.

Remarks:

Implements `IAsyncLifetime` for xUnit setup and teardown, managing container lifecycle, connection factories, and data seeding.

Members (7)

  • methodCreateCompiler
    public abstract ISqlCompiler CreateCompiler()

    Returns the SQL compiler for this database engine.

    Returns: An `ISqlCompiler` instance configured for the database dialect.

  • methodCreateConnection
    public abstract IDbConnection CreateConnection()

    Creates a new open database connection for a test.

    Returns: A new `IDbConnection` instance.

  • methodDisposeAsync
    public async Task DisposeAsync()

    Stops and disposes the container.

    Returns: A task representing the asynchronous disposal operation.

  • methodInitializeAsync
    public async Task InitializeAsync()

    Starts the container if applicable, initializes the schema, and seeds test data.

    Returns: A task representing the asynchronous initialization operation.

    Exceptions: InvalidOperationException: The connection created by `CreateConnection` is not a `Common.DbConnection`

  • propertyConnectionString
    public abstract string ConnectionString { get; }

    Gets the connection string for this fixture.

  • propertyData
    public StandardDataset Data { get; }

    Gets the standard dataset shared across all tests in the fixture.

  • propertyEngineName
    public abstract string EngineName { get; }

    Gets the engine identifier for diagnostics and compiler registration.

class

IntegrationTestBase

Assembly: EricksonLopez.SqlBuilder.Testing
public abstract class IntegrationTestBase

Provides a reusable base for integration tests that require a live database connection.

Remarks:

Subclasses supply the connection factory and compiler, and define database initialization and cleanup hooks. The `Connection` property is initialized before each test via `InitializeAsync` and disposed after each test via `DisposeAsync`.

Members (2)

  • methodDisposeAsync
    public async Task DisposeAsync()

    Disposes the database connection and cleans up after the test.

    Returns: A task representing the asynchronous disposal operation.

  • methodInitializeAsync
    public async Task InitializeAsync()

    Initializes the test environment by creating the database connection and preparing the schema.

    Returns: A task representing the asynchronous initialization operation.

class

MySqlFixture

Assembly: EricksonLopez.SqlBuilder.Testing
public sealed class MySqlFixture : DatabaseFixture
Inherits: DatabaseFixture

Represents a MySQL 8.0 test fixture backed by Testcontainers.

Remarks:

Starts a MySQL 8.0 container, applies DDL schema, and seeds test data for integration tests.

Members (4)

  • methodCreateCompiler
    public override ISqlCompiler CreateCompiler()

    Returns the SQL compiler for this database engine.

    Returns: An `ISqlCompiler` instance configured for the database dialect.

  • methodCreateConnection
    public override IDbConnection CreateConnection()

    Creates a new open database connection for a test.

    Returns: A new `IDbConnection` instance.

  • propertyConnectionString
    public override string ConnectionString { get; }

    Gets the connection string for this fixture.

  • propertyEngineName
    public override string EngineName { get; }

    Gets the engine identifier for diagnostics and compiler registration.

class

OracleBooleanHandler

Assembly: EricksonLopez.SqlBuilder.Testing
public sealed class OracleBooleanHandler : SqlMapper.TypeHandler<bool>
Inherits: SqlMapper.TypeHandler<bool>

Dapper type handler that maps `bool` to Oracle NUMBER(1) integers.

Members (2)

  • methodParse
    public override bool Parse(object value)

    Inherits documentation from base type or interface.

    value: object
  • methodSetValue
    public override void SetValue(IDbDataParameter parameter, bool value)

    Inherits documentation from base type or interface.

    parameter: IDbDataParameter
    value: bool
class

OracleFixture

Assembly: EricksonLopez.SqlBuilder.Testing
public sealed class OracleFixture : DatabaseFixture
Inherits: DatabaseFixture

Represents an Oracle Database test fixture backed by Testcontainers.

Remarks:

Starts an Oracle XE container, creates schema with IDENTITY columns and indexes, and seeds test data.

Members (4)

  • methodCreateCompiler
    public override ISqlCompiler CreateCompiler()

    Returns the SQL compiler for this database engine.

    Returns: An `ISqlCompiler` instance configured for the database dialect.

  • methodCreateConnection
    public override IDbConnection CreateConnection()

    Creates a new open database connection for a test.

    Returns: A new `IDbConnection` instance.

  • propertyConnectionString
    public override string ConnectionString { get; }

    Gets the connection string for this fixture.

  • propertyEngineName
    public override string EngineName { get; }

    Gets the engine identifier for diagnostics and compiler registration.

class

PostgreSqlFixture

Assembly: EricksonLopez.SqlBuilder.Testing
public sealed class PostgreSqlFixture : DatabaseFixture
Inherits: DatabaseFixture

Represents a PostgreSQL test fixture backed by Testcontainers.

Remarks:

Starts a PostgreSQL container, creates schema and extensions, and seeds test data.

Members (4)

  • methodCreateCompiler
    public override ISqlCompiler CreateCompiler()

    Returns the SQL compiler for this database engine.

    Returns: An `ISqlCompiler` instance configured for the database dialect.

  • methodCreateConnection
    public override IDbConnection CreateConnection()

    Creates a new open database connection for a test.

    Returns: A new `IDbConnection` instance.

  • propertyConnectionString
    public override string ConnectionString { get; }

    Gets the connection string for this fixture.

  • propertyEngineName
    public override string EngineName { get; }

    Gets the engine identifier for diagnostics and compiler registration.

class

SqlServerFixture

Assembly: EricksonLopez.SqlBuilder.Testing
public sealed class SqlServerFixture : DatabaseFixture
Inherits: DatabaseFixture

Represents a Microsoft SQL Server test fixture backed by Testcontainers.

Remarks:

Starts an MS SQL Server container, initializes database tables and indexes, and seeds test data.

Members (4)

  • methodCreateCompiler
    public override ISqlCompiler CreateCompiler()

    Returns the SQL compiler for this database engine.

    Returns: An `ISqlCompiler` instance configured for the database dialect.

  • methodCreateConnection
    public override IDbConnection CreateConnection()

    Creates a new open database connection for a test.

    Returns: A new `IDbConnection` instance.

  • propertyConnectionString
    public override string ConnectionString { get; }

    Gets the connection string for this fixture.

  • propertyEngineName
    public override string EngineName { get; }

    Gets the engine identifier for diagnostics and compiler registration.

class

SqliteFixture

Assembly: EricksonLopez.SqlBuilder.Testing
public sealed class SqliteFixture : DatabaseFixture
Inherits: DatabaseFixture

Represents a SQLite in-memory test fixture using a shared-cache connection.

Remarks:

Initializes an in-memory SQLite database, configures schema, and seeds test data without requiring Docker.

Members (4)

  • methodCreateCompiler
    public override ISqlCompiler CreateCompiler()

    Returns the SQL compiler for this database engine.

    Returns: An `ISqlCompiler` instance configured for the database dialect.

  • methodCreateConnection
    public override IDbConnection CreateConnection()

    Creates a new open database connection for a test.

    Returns: A new `IDbConnection` instance.

  • propertyConnectionString
    public override string ConnectionString { get; }

    Gets the connection string for this fixture.

  • propertyEngineName
    public override string EngineName { get; }

    Gets the engine identifier for diagnostics and compiler registration.

EricksonLopez.SqlBuilder.Testing.Seeders#

2
class

StandardDataset

Assembly: EricksonLopez.SqlBuilder.Testing
public sealed class StandardDataset

Represents a complete standard dataset for integration testing scenarios.

Members (8)

  • constructorStandardDataset
    public StandardDataset(IReadOnlyList<Customer> customers, IReadOnlyList<Category> categories, IReadOnlyList<Product> products, IReadOnlyList<Order> orders, IReadOnlyList<OrderItem> orderItems, IReadOnlyList<Invoice> invoices, IReadOnlyList<Payment> payments)

    Initializes a new instance of the `StandardDataset` class with the specified seeded entity collections.

    customers: IReadOnlyList<Customer>
    The collection of seeded customer entities.
    categories: IReadOnlyList<Category>
    The collection of seeded category entities.
    products: IReadOnlyList<Product>
    The collection of seeded product entities.
    orders: IReadOnlyList<Order>
    The collection of seeded order entities.
    orderItems: IReadOnlyList<OrderItem>
    The collection of seeded order item entities.
    invoices: IReadOnlyList<Invoice>
    The collection of seeded invoice entities.
    payments: IReadOnlyList<Payment>
    The collection of seeded payment entities.
  • propertyCategories
    public IReadOnlyList<Category> Categories { get; }

    Gets the collection of seeded category entities.

  • propertyCustomers
    public IReadOnlyList<Customer> Customers { get; }

    Gets the collection of seeded customer entities.

  • propertyInvoices
    public IReadOnlyList<Invoice> Invoices { get; }

    Gets the collection of seeded invoice entities.

  • propertyOrderItems
    public IReadOnlyList<OrderItem> OrderItems { get; }

    Gets the collection of seeded order item entities.

  • propertyOrders
    public IReadOnlyList<Order> Orders { get; }

    Gets the collection of seeded order entities.

  • propertyPayments
    public IReadOnlyList<Payment> Payments { get; }

    Gets the collection of seeded payment entities.

  • propertyProducts
    public IReadOnlyList<Product> Products { get; }

    Gets the collection of seeded product entities.

class

TestDataSeeder

Assembly: EricksonLopez.SqlBuilder.Testing
public static class TestDataSeeder

Generates realistic test data for integration tests using the Bogus library.

Remarks:

All generated data is deterministic when a seed is provided.

Members (10)

  • methodAddresses
    public static IReadOnlyList<Address> Addresses(IReadOnlyList<Customer> customers, int seed = DefaultSeed)

    Generates one to three `Address` entities per specified customer.

    customers: IReadOnlyList<Customer>
    The list of customers to generate addresses for.
    seed: int
    The random seed for deterministic data generation.

    Returns: A read-only list of generated `Address` entities.

  • methodCategories
    public static IReadOnlyList<Category> Categories()

    Returns the standard ten-category hierarchy used in DDL seed data.

    Returns: A read-only list of standard `Category` entities.

  • methodCustomers
    public static IReadOnlyList<Customer> Customers(int count = 100, int seed = DefaultSeed)

    Generates a collection of fake `Customer` entities.

    count: int
    The number of customer records to generate.
    seed: int
    The random seed for deterministic data generation.

    Returns: A read-only list of generated `Customer` entities.

  • methodGenerate
    public static StandardDataset Generate(int seed = DefaultSeed)

    Generates the complete standard dataset containing customers, categories, products, orders, order items, invoices, and payments.

    seed: int
    The random seed for deterministic data generation.

    Returns: A `StandardDataset` instance populated with seeded entities.

  • methodInvoices
    public static IReadOnlyList<Invoice> Invoices(IReadOnlyList<Order>? orders = null, int seed = DefaultSeed)

    Generates `Invoice` records for confirmed, shipped, or delivered orders.

    orders: IReadOnlyList<Order>?
    The optional order list to invoice; defaults to generated orders when `null`.
    seed: int
    The random seed for deterministic data generation.

    Returns: A read-only list of generated `Invoice` entities.

  • methodOrderItems
    public static IReadOnlyList<OrderItem> OrderItems(int count = 5000, IReadOnlyList<Order>? orders = null, IReadOnlyList<Product>? products = null, int seed = DefaultSeed)

    Generates a collection of fake `OrderItem` entities.

    count: int
    The number of order item records to generate.
    orders: IReadOnlyList<Order>?
    The optional order list to associate items with; defaults to generated orders when `null`.
    products: IReadOnlyList<Product>?
    The optional product list to associate items with; defaults to generated products when `null`.
    seed: int
    The random seed for deterministic data generation.

    Returns: A read-only list of generated `OrderItem` entities.

  • methodOrders
    public static IReadOnlyList<Order> Orders(int count = 1000, IReadOnlyList<Customer>? customers = null, int seed = DefaultSeed)

    Generates a collection of fake `Order` entities.

    count: int
    The number of order records to generate.
    customers: IReadOnlyList<Customer>?
    The optional customer list to associate orders with; defaults to generated customers when `null`.
    seed: int
    The random seed for deterministic data generation.

    Returns: A read-only list of generated `Order` entities.

  • methodPayments
    public static IReadOnlyList<Payment> Payments(IReadOnlyList<Invoice>? invoices = null, int seed = DefaultSeed)

    Generates `Payment` records for paid invoices.

    invoices: IReadOnlyList<Invoice>?
    The optional invoice list to pay; defaults to generated invoices when `null`.
    seed: int
    The random seed for deterministic data generation.

    Returns: A read-only list of generated `Payment` entities.

  • methodProducts
    public static IReadOnlyList<Product> Products(int count = 500, IReadOnlyList<Category>? categories = null, int seed = DefaultSeed)

    Generates a collection of fake `Product` entities.

    count: int
    The number of product records to generate.
    categories: IReadOnlyList<Category>?
    The optional category list to assign products to; defaults to standard categories when `null`.
    seed: int
    The random seed for deterministic data generation.

    Returns: A read-only list of generated `Product` entities.

  • methodUsers
    public static IReadOnlyList<User> Users(int count = 20, int seed = DefaultSeed)

    Generates a collection of fake `User` entities.

    count: int
    The number of user records to generate.
    seed: int
    The random seed for deterministic data generation.

    Returns: A read-only list of generated `User` entities.

Search EricksonLopez.* Ecosystem

Type a library name, NuGet package ID, .NET type, or architectural concept to search across the portal.