Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 3 additions & 2 deletions Package.swift
Original file line number Diff line number Diff line change
Expand Up @@ -131,6 +131,7 @@ let package = Package(
"StructuredQueriesSQLiteMacros",
.product(name: "IssueReporting", package: "xctest-dynamic-overlay"),
.product(name: "MacroTesting", package: "swift-macro-testing"),
.product(name: "SwiftCompilerPlugin", package: "swift-syntax"),
]
),
.testTarget(
Expand All @@ -157,8 +158,8 @@ let package = Package(
)

if ProcessInfo.processInfo.environment["SPI_GENERATE_DOCS"] != nil
|| ProcessInfo.processInfo.environment["CI"] != nil// NB: For local testing in Xcode:
// || true
|| ProcessInfo.processInfo.environment["CI"] != nil // NB: For local testing in Xcode:
// || true
{
package.traits.insert(
.default(
Expand Down
67 changes: 67 additions & 0 deletions Sources/StructuredQueriesSQLiteCore/JSONFunctions.swift
Original file line number Diff line number Diff line change
Expand Up @@ -210,6 +210,73 @@ where
}
}

extension TableColumnExpression
where
Root: PrimaryKeyedTable & _OptionalProtocol,
QueryValue: _OptionalProtocol & Codable & QueryBindable,
QueryValue.Wrapped: Codable
{
/// A JSON array aggregate of an optional column's wrapped value.
///
/// When aggregating from a joined table that may be `NULL` (for instance, a `LEFT JOIN` that
/// yields no matching rows), this overload automatically filters out the rows where the joined
/// table's primary key is `NULL`, ensuring the resulting JSON array only contains fully realized
/// rows.
///
/// ```swift
/// RemindersList
/// .group(by: \.id)
/// .leftJoin(Reminder.all) { $0.id.eq($1.remindersListID) }
/// .select { list, reminder in
/// (
/// list.title,
/// reminder.title.jsonGroupArray()
/// )
/// }
/// ```
///
/// - Parameters:
/// - isDistinct: A boolean that enables the `DISTINCT` clause on the aggregation.
/// - order: An `ORDER BY` clause to apply to the aggregation.
/// - filter: A `FILTER` clause to apply to the aggregation.
/// - Returns: A JSON array aggregate of this column's wrapped value.
public func jsonGroupArray(
distinct isDistinct: Bool = false,
order: (some QueryExpression)? = Bool?.none,
filter: (some QueryExpression<Bool>)? = Bool?.none
) -> some QueryExpression<[QueryValue.Wrapped].JSONRepresentation> {
let primaryKeyNames = Root.columns.primaryKey._names
let primaryKeyColumns: QueryFragment =
primaryKeyNames
.map { "\(Root.self).\(quote: $0)" }
.joined(separator: ", ")
let primaryKeyNulls: QueryFragment = Array(
repeating: QueryFragment("NULL"),
count: primaryKeyNames.count
)
.joined(separator: ", ")
let primaryKeyFilter = SQLQueryExpression(
"(\(primaryKeyColumns)) IS NOT (\(primaryKeyNulls))",
as: Bool.self

)
let combinedFilter: SQLQueryExpression<Bool>
if let filter {
combinedFilter = SQLQueryExpression(primaryKeyFilter.and(filter))
} else {
combinedFilter = primaryKeyFilter
}

return AggregateFunctionExpression<[QueryValue.Wrapped].JSONRepresentation>(
"json_group_array",
distinct: isDistinct,
self,
order: order,
filter: combinedFilter
)
}
}

extension TableDefinition where QueryValue: Codable {
/// A JSON representation of a table's columns.
///
Expand Down
32 changes: 32 additions & 0 deletions Tests/StructuredQueriesTests/JSONFunctionsTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -64,6 +64,38 @@ extension SnapshotTests {
}
}

@Test func jsonGroupArrayOptionalColumn() {
assertQuery(
RemindersList
.group(by: \.id)
.leftJoin(Reminder.all) { $0.id.eq($1.remindersListID) }
.select { list, reminder in
(list.title, reminder.title.jsonGroupArray())
}
.limit(1)
) {
"""
SELECT "remindersLists"."title", "json_group_array"("reminders"."title") FILTER (WHERE ("reminders"."id") IS NOT (NULL))
FROM "remindersLists"
LEFT JOIN "reminders" ON ("remindersLists"."id") = ("reminders"."remindersListID")
GROUP BY "remindersLists"."id"
LIMIT 1
"""
} results: {
"""
┌────────────┬──────────────────────────────┐
│ "Personal" │ [ │
│ │ [0]: "Groceries", │
│ │ [1]: "Haircut", │
│ │ [2]: "Doctor appointment", │
│ │ [3]: "Take a walk", │
│ │ [4]: "Buy concert tickets" │
│ │ ] │
└────────────┴──────────────────────────────┘
"""
}
}

@Test func jsonArrayLength() {
assertQuery(
Reminder.select {
Expand Down