Skip to main content

QWhereBuilder

@quik/database


@quik/database / QWhereBuilder

Class: QWhereBuilder

Defined in: database/src/repository/QWhereBuilder.ts:60

Builder class for creating complex where conditions.

This class provides a fluent interface for constructing database query conditions with support for nested logical groups, different condition types, and complex logical expressions. The builder pattern allows for intuitive and readable query construction.

Key features:

  • AND/OR logical operations with proper precedence
  • Nested condition groups with parentheses for complex criteria
  • Support for all SQL comparison operators (=, <>, <, <=, >, >=)
  • Special operators like IN, BETWEEN, LIKE for advanced filtering
  • Condition negation for inverse logic
  • Chainable method calls for building complex conditions

When used with QQueryBuilder, the QWhereBuilder's conditions are transformed into SQL clauses through the transformWhereBuilder and transformWhereCondition methods. These methods handle both simple conditions and complex nested logical expressions.

The transformWhereCondition method processes individual conditions by:

  1. Determining the appropriate SQL function to use based on the logical operator
  2. Applying the condition with proper field qualification
  3. Handling special operators like IS NULL and LIKE with appropriate syntax
  4. Supporting negated conditions with the correct logical inversion

Example

// Basic conditions
const whereBuilder = QWhereBuilder.New()
.Equal('status', 'active')
.GreaterThan('createdAt', '2023-01-01');

// Complex nested conditions
const complexBuilder = QWhereBuilder.New()
.Equal('status', 'active')
.Or(
QWhereBuilder.New()
.Equal('role', 'admin')
.And(
QWhereBuilder.New().In('department', ['IT', 'HR'])
)
);
// Produces: WHERE status = 'active' OR (role = 'admin' AND department IN ('IT', 'HR'))

See

  • QQueryBuilder For using where conditions in database queries
  • Conditions For factory functions to create individual conditions
  • QRepository For high-level database operations using where conditions

Extends

  • QObject

Constructors

Constructor

protected new QWhereBuilder(...conditions): QWhereBuilder

Defined in: database/src/repository/QWhereBuilder.ts:81

Creates a new where builder with initial conditions

This constructor initializes the conditions array and adds any provided initial conditions. It's protected because instances should be created using the static New() factory method for a more fluent API.

Parameters

conditions

...QWhereCondition[]

Initial conditions to add to the builder

Returns

QWhereBuilder

See

New For the static factory method to create instances

Overrides

QObject.constructor

Properties

_conditions

protected _conditions: QWhereClause[]

Defined in: database/src/repository/QWhereBuilder.ts:68

Storage for where clauses

This array stores all the conditions added to the builder. Each entry contains the condition and a flag indicating if it should be combined with OR logic (true) or AND logic (false).

Accessors

conditions

Get Signature

get conditions(): QWhereClause[]

Defined in: database/src/repository/QWhereBuilder.ts:491

Gets the current list of where clauses

Each clause is stored with a flag indicating whether it is joined with OR or AND logic. Consumers typically use this for transforming the builder into raw SQL.

Returns

QWhereClause[]


logger

Get Signature

get protected logger(): IQLogger

Defined in: core/src/QObject.ts:15

The logger getter for the object.

Returns

IQLogger

Inherited from

QObject.logger


name

Get Signature

get name(): string

Defined in: core/src/QObject.ts:8

Returns

string

Inherited from

QObject.name

Methods

addAndCondition()

protected addAndCondition(condition): QWhereBuilder

Defined in: database/src/repository/QWhereBuilder.ts:546

Adds a condition to the builder with AND logic

Parameters

condition

QWhereBuilder

Builder containing conditions to add with AND logic

Returns

QWhereBuilder


addCondition()

protected addCondition(condition): QWhereBuilder

Defined in: database/src/repository/QWhereBuilder.ts:520

Adds a condition to the builder with AND logic

Parameters

condition

QWhereCondition

Condition to add

Returns

QWhereBuilder


addOrCondition()

protected addOrCondition(condition): QWhereBuilder

Defined in: database/src/repository/QWhereBuilder.ts:533

Adds a condition to the builder with OR logic

Parameters

condition

QWhereBuilder

Builder containing conditions to add with OR logic

Returns

QWhereBuilder


And()

And(...builderOrConditions): QWhereBuilder

Defined in: database/src/repository/QWhereBuilder.ts:261

Adds conditions with AND logic

This method adds one or more conditions or nested builders to the current builder, combining them with AND logic. When the resulting SQL is executed, all of these conditions must be true for a record to be included in the results.

When providing QWhereCondition objects, they are automatically wrapped in a new QWhereBuilder for proper handling of logical groups. This automatic wrapping ensures proper nesting and parentheses in the generated SQL query.

The AND logic is applied between all conditions provided in the parameters, creating a logical conjunction. Multiple calls to .And() will be joined with the existing conditions according to operator precedence rules in SQL. AND has higher precedence than OR in SQL, which is reflected in the generated queries.

Parameters

builderOrConditions

...(QWhereCondition | QWhereBuilder | ((builder) => unknown))[]

Conditions or builders to add with AND logic

Returns

QWhereBuilder

Example

// Simple AND with conditions
const builder = QWhereBuilder.New()
.Equal('status', 'active')
.And(
{ field: 'lastLogin', operator: '>', value: '2023-01-01' },
{ field: 'role', operator: '=', value: 'user' }
);
// WHERE status = 'active' AND lastLogin > '2023-01-01' AND role = 'user'

// AND with nested builders
const builder = QWhereBuilder.New()
.Equal('status', 'active')
.And(
QWhereBuilder.New()
.Equal('department', 'sales')
.Or(
QWhereBuilder.New().Equal('role', 'manager'),
QWhereBuilder.New().GreaterThan('revenue', 5000)
)
);
// WHERE status = 'active' AND (department = 'sales' AND (role = 'manager' OR revenue > 5000))

// Complex condition combining AND and OR for advanced filtering
const builder = QWhereBuilder.New()
.Equal('isActive', true)
.And(
QWhereBuilder.New()
.Equal('userType', 'customer')
.Equal('verificationStatus', 'verified')
)
.Or(
QWhereBuilder.New()
.Equal('userType', 'admin')
);
// WHERE isActive = true AND (userType = 'customer' AND verificationStatus = 'verified') OR (userType = 'admin')

Nested groups can also be built inline with a callback instead of a separate QWhereBuilder.New() call — this is the terse form for combining plain conditions and nested OR groups in a single .And(...) call:

const builder = QWhereBuilder.New()
.Equal('ProjectTeam.projectId', projectId)
.And(
Conditions.Equal('ProjectTeamMember.userId', userId),
Conditions.LessThanOrEqual('ProjectTeamMember.startDate', date),
(group) => group.Or(
Conditions.IsNull('ProjectTeamMember.endDate'),
Conditions.GreaterThanOrEqual('ProjectTeamMember.endDate', date)
)
);

See


Between()

Between(field, min, max): QWhereBuilder

Defined in: database/src/repository/QWhereBuilder.ts:397

Adds a BETWEEN condition Checks if field value is between min and max (inclusive)

This is typically used for numeric or date ranges and expands to field BETWEEN min AND max in SQL.

Parameters

field

string

Field name to check

min

unknown

Minimum value (inclusive)

max

unknown

Maximum value (inclusive)

Returns

QWhereBuilder

Example

QWhereBuilder.New().Between('age', 18, 30);
// WHERE age BETWEEN 18 AND 30

endSpan()

protected endSpan(span): void

Defined in: core/src/QObject.ts:35

End a span returned by startSpan.

Parameters

span

TelemetrySpan

The span to end.

Returns

void

Inherited from

QObject.endSpan


Equal()

Equal(field, value): QWhereBuilder

Defined in: database/src/repository/QWhereBuilder.ts:285

Adds an equality condition

This method appends a simple field = value comparison to the builder. It's the most common way to filter results by an exact match. The value is parameterized in the final SQL to avoid injection issues.

Parameters

field

string

Field name to compare

value

unknown

Value to compare against

Returns

QWhereBuilder

Example

const where = QWhereBuilder.New().Equal('status', 'active');
// WHERE status = 'active'

GreaterThan()

GreaterThan(field, value): QWhereBuilder

Defined in: database/src/repository/QWhereBuilder.ts:343

Adds a greater-than condition

Generates a field > value comparison. Commonly used for numeric checks such as filtering by an ID greater than a certain value.

Parameters

field

string

Field name to compare

value

unknown

Value to compare against

Returns

QWhereBuilder


GreaterThanOrEqual()

GreaterThanOrEqual(field, value): QWhereBuilder

Defined in: database/src/repository/QWhereBuilder.ts:356

Adds a greater-than-or-equal condition

Works the same as GreaterThan but includes the provided value in the comparison.

Parameters

field

string

Field name to compare

value

unknown

Value to compare against

Returns

QWhereBuilder


In()

In(field, value): QWhereBuilder

Defined in: database/src/repository/QWhereBuilder.ts:376

Adds an IN condition Checks if field value is in the provided array

The generated SQL uses the IN operator with parameterized values. This is helpful when restricting results to a known list of values.

Parameters

field

string

Field name to check

value

unknown[]

Array of values to check against

Returns

QWhereBuilder

Example

QWhereBuilder.New().In('role', ['admin', 'user']);
// WHERE role IN ('admin', 'user')

IsNull()

IsNull(field): QWhereBuilder

Defined in: database/src/repository/QWhereBuilder.ts:444

Adds an IS NULL condition Checks if field value is null

Useful when filtering for records where a column has not been set.

Parameters

field

string

Field name to check

Returns

QWhereBuilder


LessThan()

LessThan(field, value): QWhereBuilder

Defined in: database/src/repository/QWhereBuilder.ts:317

Adds a less-than condition

Generates a field < value clause which is often used for numeric or date comparisons. The builder will automatically handle value parameterization.

Parameters

field

string

Field name to compare

value

unknown

Value to compare against

Returns

QWhereBuilder


LessThanOrEqual()

LessThanOrEqual(field, value): QWhereBuilder

Defined in: database/src/repository/QWhereBuilder.ts:330

Adds a less-than-or-equal condition

Similar to LessThan but inclusive of the provided value. Useful for filtering ranges with an upper bound.

Parameters

field

string

Field name to compare

value

unknown

Value to compare against

Returns

QWhereBuilder


Like()

Like(field, value): QWhereBuilder

Defined in: database/src/repository/QWhereBuilder.ts:418

Adds a LIKE condition Performs pattern matching on field value

Supports SQL wildcards such as % for flexible pattern matching. The comparison is case-sensitive unless your database configuration states otherwise.

Parameters

field

string

Field name to check

value

unknown

Pattern to match against

Returns

QWhereBuilder

Example

QWhereBuilder.New().Like('name', 'A%');
// WHERE name LIKE 'A%'

Not()

Not(fieldOrCondition, value?, operator?): QWhereBuilder

Defined in: database/src/repository/QWhereBuilder.ts:479

Adds a negated condition Can either negate an existing condition or create a new negated condition

When providing a field name, you may also specify the operator to use. If no operator is given, '=' is assumed. Passing an existing condition allows for negating complex expressions.

Parameters

fieldOrCondition

string | QWhereCondition

Field name or existing condition to negate

value?

string

Value to compare against (when using field name)

operator?

QWhereOperator

Operator to use (when using field name)

Returns

QWhereBuilder

Example

QWhereBuilder.New().Not('status', 'inactive');
// WHERE NOT status = 'inactive'

NotEqual()

NotEqual(field, value): QWhereBuilder

Defined in: database/src/repository/QWhereBuilder.ts:304

Adds a not-equal condition

This creates a field <> value comparison for excluding matching rows. Use it when you need to filter out a specific value from the results.

Parameters

field

string

Field name to compare

value

unknown

Value to compare against

Returns

QWhereBuilder

Example

QWhereBuilder.New().NotEqual('status', 'inactive');
// WHERE status <> 'inactive'

NotLike()

NotLike(field, value): QWhereBuilder

Defined in: database/src/repository/QWhereBuilder.ts:432

Adds a NOT LIKE condition Negates a LIKE pattern matching condition

This is useful for excluding values that match a pattern. Internally it expands to NOT (field LIKE value).

Parameters

field

string

Field name to check

value

unknown

Pattern to not match against

Returns

QWhereBuilder


NotNull()

NotNull(field): QWhereBuilder

Defined in: database/src/repository/QWhereBuilder.ts:457

Adds a NOT NULL condition Checks if field value is not null

Opposite of IsNull. Filters out rows where the column contains a null value.

Parameters

field

string

Field name to check

Returns

QWhereBuilder


Or()

Or(...builderOrConditions): QWhereBuilder

Defined in: database/src/repository/QWhereBuilder.ts:177

Adds conditions with OR logic

This method adds one or more conditions or nested builders to the current builder, combining them with OR logic. When the resulting SQL is executed, any of these conditions must be true for a record to be included in the results.

When providing QWhereCondition objects, they are automatically wrapped in a new QWhereBuilder for proper handling of logical groups. This automatic wrapping ensures proper nesting and parentheses in the generated SQL query.

The OR logic is applied between all conditions provided in the parameters, creating a logical disjunction. Multiple calls to .Or() will be joined with the existing conditions according to operator precedence rules in SQL.

Parameters

builderOrConditions

...(QWhereCondition | QWhereBuilder | ((builder) => unknown))[]

Conditions or builders to add with OR logic

Returns

QWhereBuilder

Example

// Simple OR with conditions
const builder = QWhereBuilder.New()
.Equal('status', 'active')
.Or(
{ field: 'role', operator: '=', value: 'admin' },
{ field: 'role', operator: '=', value: 'manager' }
);
// WHERE status = 'active' OR role = 'admin' OR role = 'manager'

// OR with nested builders
const builder = QWhereBuilder.New()
.Equal('status', 'active')
.Or(
QWhereBuilder.New()
.Equal('department', 'sales')
.GreaterThan('revenue', 1000)
);
// WHERE status = 'active' OR (department = 'sales' AND revenue > 1000)

// Multiple OR operations with mixed conditions
const builder = QWhereBuilder.New()
.Equal('status', 'active')
.Or(
{ field: 'role', operator: '=', value: 'admin' }
)
.Or(
QWhereBuilder.New()
.Equal('department', 'IT')
.Equal('clearance', 'high')
);
// WHERE status = 'active' OR role = 'admin' OR (department = 'IT' AND clearance = 'high')

Nested groups can also be built inline with a callback instead of a separate QWhereBuilder.New() call:

const builder = QWhereBuilder.New()
.Equal('status', 'active')
.Or((group) => group.Equal('department', 'sales').GreaterThan('revenue', 1000));
// WHERE status = 'active' OR (department = 'sales' AND revenue > 1000)

See


recordSpanError()

protected recordSpanError(span, err): void

Defined in: core/src/QObject.ts:45

Record an exception on an active span.

Parameters

span

TelemetrySpan

The span to record the error on.

err

unknown

The error to record.

Returns

void

Inherited from

QObject.recordSpanError


resolveNestedBuilder()

protected resolveNestedBuilder(item): QWhereBuilder

Defined in: database/src/repository/QWhereBuilder.ts:501

Resolves a .And()/.Or() argument (a condition, a nested builder, or a callback building a nested group) into a QWhereBuilder ready to be pushed onto _conditions.

Parameters

item

QWhereCondition | QWhereBuilder | ((builder) => unknown)

Argument passed to .And()/.Or().

Returns

QWhereBuilder


setSpanAttribute()

protected setSpanAttribute(span, key, value): void

Defined in: core/src/QObject.ts:64

Set a single attribute on an active span.

Parameters

span

TelemetrySpan

The span to update.

key

string

Attribute key.

value

string | number | boolean

Attribute value.

Returns

void

Inherited from

QObject.setSpanAttribute


startSpan()

protected startSpan(spanName, options?): TelemetrySpan

Defined in: core/src/QObject.ts:26

Start a telemetry span for the given operation name. Returns undefined when no telemetry provider is active.

Parameters

spanName

string

Name of the span.

options?

TelemetrySpanOptions

Optional span attributes and kind.

Returns

TelemetrySpan

Inherited from

QObject.startSpan


New()

static New(...conditions): QWhereBuilder

Defined in: database/src/repository/QWhereBuilder.ts:109

Static factory method to create a new where builder

This factory method creates and returns a new QWhereBuilder instance. Using this method allows for a more fluent API compared to using the constructor directly.

Parameters

conditions

...QWhereCondition[]

Initial conditions to add to the builder

Returns

QWhereBuilder

Example

// Create an empty builder
const emptyBuilder = QWhereBuilder.New();

// Create a builder with initial conditions
const builder = QWhereBuilder.New(
{ field: 'status', operator: '=', value: 'active' },
{ field: 'createdAt', operator: '>', value: '2023-01-01' }
);