Skip to content

Commit 422f59f

Browse files
ampagenttmm
andcommitted
zero-swift: typed aggregates, distinct and groupBy
zql.issue.count() is a Query<Issue, Int>: the new QueryValue protocol, which QueryResult refines, is what Query, run, liveQuery, @ZeroQuery and defineQuery take. sum/avg give Double?, min/max the column's type, and each takes a JSON path. distinct() and groupBy() give DistinctRow and GroupRow, read by key path. Codegen adds an aggregates property (RelationshipAggregates) to row structs with relationships, which related(\.comments) { $0.count() } fills. Co-authored-by: tmm <tmm@tmm.dev> Amp-Thread-ID: https://ampcode.com/threads/T-01a19a37-5aa9-7256-bff5-cdc47c01a1fe
1 parent 1c93766 commit 422f59f

21 files changed

Lines changed: 799 additions & 131 deletions

File tree

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,7 @@
1+
---
2+
'zero-swift': minor
3+
---
4+
5+
The typed query builder has aggregates, `distinct()` and `groupBy()`. `zql.issue.count()` is a `Query<Issue, Int>`; `sum` and `avg` give a `Double?`, and `min` and `max` the column's type, optional; each also takes a JSON path (`sum(json: \.metadata, "points")`). `distinct(\.ownerId)` gives `DistinctRow`s and `groupBy(\.ownerId).count()` gives `GroupRow`s, read by key path (`row[\.ownerId]`, `row.value`). `run`, `liveQuery`, `@ZeroQuery` and `defineQuery` take these queries as they take queries of rows. In `related`, an aggregate goes in the row's new generated `aggregates` property: `issue.aggregates?.count(\.comments)`.
6+
7+
Breaking: `QueryResult` now refines the new `QueryValue` protocol, which `Query`, `LiveQuery`, `QueryDefinition`, `QueryRequest` and `ZeroQuery` take in its place, and `Query` no longer requires `Result.Row == Row`. `ZeroRow` refines `QueryElement` and `OptionalQueryElement`, and `ZeroValue` refines `OptionalQueryElement`. Regenerate row structs with `zero-swift codegen` to get `aggregates`; a table can no longer have a column or relationship property named `aggregates`, which codegen renames.

‎apps/zbugs-swift/Sources/ZBugs/Schema.swift‎

Lines changed: 42 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,8 @@ public struct User: ZeroTable, Codable, Hashable, Identifiable {
1313
// Relationships, filled when a query asks for them with `related`.
1414
public var createdIssues: [Issue]?
1515
public var assignedIssues: [Issue]?
16+
// The aggregates a query asked for in `related`; nil when it asked for none.
17+
public var aggregates: RelationshipAggregates<User>?
1618

1719
public init(
1820
id: String,
@@ -21,7 +23,8 @@ public struct User: ZeroTable, Codable, Hashable, Identifiable {
2123
avatar: String,
2224
role: UserRole,
2325
createdIssues: [Issue]? = nil,
24-
assignedIssues: [Issue]? = nil
26+
assignedIssues: [Issue]? = nil,
27+
aggregates: RelationshipAggregates<User>? = nil
2528
) {
2629
self.id = id
2730
self.login = login
@@ -30,6 +33,7 @@ public struct User: ZeroTable, Codable, Hashable, Identifiable {
3033
self.role = role
3134
self.createdIssues = createdIssues
3235
self.assignedIssues = assignedIssues
36+
self.aggregates = aggregates
3337
}
3438

3539
public static let tableName = "user"
@@ -55,6 +59,7 @@ public struct User: ZeroTable, Codable, Hashable, Identifiable {
5559
role = try entry.column("role", 4)
5660
createdIssues = try entry.relationship("createdIssues")
5761
assignedIssues = try entry.relationship("assignedIssues")
62+
aggregates = RelationshipAggregates(entry: entry)
5863
}
5964

6065
public var columnValues: Row {
@@ -130,6 +135,8 @@ public struct Project: ZeroTable, Codable, Hashable, Identifiable {
130135
// Relationships, filled when a query asks for them with `related`.
131136
public var issues: [Issue]?
132137
public var labels: [Label]?
138+
// The aggregates a query asked for in `related`; nil when it asked for none.
139+
public var aggregates: RelationshipAggregates<Project>?
133140

134141
public init(
135142
id: String,
@@ -140,7 +147,8 @@ public struct Project: ZeroTable, Codable, Hashable, Identifiable {
140147
markURL: String? = nil,
141148
logoURL: String? = nil,
142149
issues: [Issue]? = nil,
143-
labels: [Label]? = nil
150+
labels: [Label]? = nil,
151+
aggregates: RelationshipAggregates<Project>? = nil
144152
) {
145153
self.id = id
146154
self.name = name
@@ -151,6 +159,7 @@ public struct Project: ZeroTable, Codable, Hashable, Identifiable {
151159
self.logoURL = logoURL
152160
self.issues = issues
153161
self.labels = labels
162+
self.aggregates = aggregates
154163
}
155164

156165
public static let tableName = "project"
@@ -180,6 +189,7 @@ public struct Project: ZeroTable, Codable, Hashable, Identifiable {
180189
logoURL = try entry.column("logoURL", 6)
181190
issues = try entry.relationship("issues")
182191
labels = try entry.relationship("labels")
192+
aggregates = RelationshipAggregates(entry: entry)
183193
}
184194

185195
public var columnValues: Row {
@@ -276,6 +286,8 @@ public struct Issue: ZeroTable, Codable, Hashable, Identifiable {
276286
public var viewState: [ViewState]?
277287
public var emoji: [Emoji]?
278288
@Indirect public var notificationState: IssueNotifications?
289+
// The aggregates a query asked for in `related`; nil when it asked for none.
290+
public var aggregates: RelationshipAggregates<Issue>?
279291

280292
public init(
281293
id: String,
@@ -297,7 +309,8 @@ public struct Issue: ZeroTable, Codable, Hashable, Identifiable {
297309
assignee: User? = nil,
298310
viewState: [ViewState]? = nil,
299311
emoji: [Emoji]? = nil,
300-
notificationState: IssueNotifications? = nil
312+
notificationState: IssueNotifications? = nil,
313+
aggregates: RelationshipAggregates<Issue>? = nil
301314
) {
302315
self.id = id
303316
self.shortID = shortID
@@ -319,6 +332,7 @@ public struct Issue: ZeroTable, Codable, Hashable, Identifiable {
319332
self.viewState = viewState
320333
self.emoji = emoji
321334
self.notificationState = notificationState
335+
self.aggregates = aggregates
322336
}
323337

324338
public static let tableName = "issue"
@@ -370,6 +384,7 @@ public struct Issue: ZeroTable, Codable, Hashable, Identifiable {
370384
viewState = try entry.relationship("viewState")
371385
emoji = try entry.relationship("emoji")
372386
notificationState = try entry.relationship("notificationState")
387+
aggregates = RelationshipAggregates(entry: entry)
373388
}
374389

375390
public var columnValues: Row {
@@ -474,6 +489,8 @@ public struct Comment: ZeroTable, Codable, Hashable, Identifiable {
474489
@Indirect public var creator: User?
475490
public var emoji: [Emoji]?
476491
@Indirect public var issue: Issue?
492+
// The aggregates a query asked for in `related`; nil when it asked for none.
493+
public var aggregates: RelationshipAggregates<Comment>?
477494

478495
public init(
479496
id: String,
@@ -483,7 +500,8 @@ public struct Comment: ZeroTable, Codable, Hashable, Identifiable {
483500
creatorID: String,
484501
creator: User? = nil,
485502
emoji: [Emoji]? = nil,
486-
issue: Issue? = nil
503+
issue: Issue? = nil,
504+
aggregates: RelationshipAggregates<Comment>? = nil
487505
) {
488506
self.id = id
489507
self.issueID = issueID
@@ -493,6 +511,7 @@ public struct Comment: ZeroTable, Codable, Hashable, Identifiable {
493511
self.creator = creator
494512
self.emoji = emoji
495513
self.issue = issue
514+
self.aggregates = aggregates
496515
}
497516

498517
public static let tableName = "comment"
@@ -520,6 +539,7 @@ public struct Comment: ZeroTable, Codable, Hashable, Identifiable {
520539
creator = try entry.relationship("creator")
521540
emoji = try entry.relationship("emoji")
522541
issue = try entry.relationship("issue")
542+
aggregates = RelationshipAggregates(entry: entry)
523543
}
524544

525545
public var columnValues: Row {
@@ -590,17 +610,21 @@ public struct Label: ZeroTable, Codable, Hashable, Identifiable {
590610

591611
// Relationships, filled when a query asks for them with `related`.
592612
@Indirect public var project: Project?
613+
// The aggregates a query asked for in `related`; nil when it asked for none.
614+
public var aggregates: RelationshipAggregates<Label>?
593615

594616
public init(
595617
id: String,
596618
name: String,
597619
projectID: String,
598-
project: Project? = nil
620+
project: Project? = nil,
621+
aggregates: RelationshipAggregates<Label>? = nil
599622
) {
600623
self.id = id
601624
self.name = name
602625
self.projectID = projectID
603626
self.project = project
627+
self.aggregates = aggregates
604628
}
605629

606630
public static let tableName = "label"
@@ -620,6 +644,7 @@ public struct Label: ZeroTable, Codable, Hashable, Identifiable {
620644
name = try entry.column("name", 1)
621645
projectID = try entry.column("projectID", 2)
622646
project = try entry.relationship("project")
647+
aggregates = RelationshipAggregates(entry: entry)
623648
}
624649

625650
public var columnValues: Row {
@@ -681,19 +706,23 @@ public struct IssueLabel: ZeroTable, Codable, Hashable {
681706
// Relationships, filled when a query asks for them with `related`.
682707
@Indirect public var issue: Issue?
683708
@Indirect public var label: Label?
709+
// The aggregates a query asked for in `related`; nil when it asked for none.
710+
public var aggregates: RelationshipAggregates<IssueLabel>?
684711

685712
public init(
686713
issueID: String,
687714
labelID: String,
688715
projectID: String,
689716
issue: Issue? = nil,
690-
label: Label? = nil
717+
label: Label? = nil,
718+
aggregates: RelationshipAggregates<IssueLabel>? = nil
691719
) {
692720
self.issueID = issueID
693721
self.labelID = labelID
694722
self.projectID = projectID
695723
self.issue = issue
696724
self.label = label
725+
self.aggregates = aggregates
697726
}
698727

699728
public static let tableName = "issueLabel"
@@ -715,6 +744,7 @@ public struct IssueLabel: ZeroTable, Codable, Hashable {
715744
projectID = try entry.column("projectID", 2)
716745
issue = try entry.relationship("issue")
717746
label = try entry.relationship("label")
747+
aggregates = RelationshipAggregates(entry: entry)
718748
}
719749

720750
public var columnValues: Row {
@@ -870,6 +900,8 @@ public struct Emoji: ZeroTable, Codable, Hashable, Identifiable {
870900
@Indirect public var creator: User?
871901
@Indirect public var issue: Issue?
872902
@Indirect public var comment: Comment?
903+
// The aggregates a query asked for in `related`; nil when it asked for none.
904+
public var aggregates: RelationshipAggregates<Emoji>?
873905

874906
public init(
875907
id: String,
@@ -880,7 +912,8 @@ public struct Emoji: ZeroTable, Codable, Hashable, Identifiable {
880912
created: Double,
881913
creator: User? = nil,
882914
issue: Issue? = nil,
883-
comment: Comment? = nil
915+
comment: Comment? = nil,
916+
aggregates: RelationshipAggregates<Emoji>? = nil
884917
) {
885918
self.id = id
886919
self.value = value
@@ -891,6 +924,7 @@ public struct Emoji: ZeroTable, Codable, Hashable, Identifiable {
891924
self.creator = creator
892925
self.issue = issue
893926
self.comment = comment
927+
self.aggregates = aggregates
894928
}
895929

896930
public static let tableName = "emoji"
@@ -920,6 +954,7 @@ public struct Emoji: ZeroTable, Codable, Hashable, Identifiable {
920954
creator = try entry.relationship("creator")
921955
issue = try entry.relationship("issue")
922956
comment = try entry.relationship("comment")
957+
aggregates = RelationshipAggregates(entry: entry)
923958
}
924959

925960
public var columnValues: Row {

‎packages/zero-swift-cli/src/generate.ts‎

Lines changed: 39 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -114,6 +114,8 @@ const rowMembers = [
114114
'columns',
115115
'relationships',
116116
'columnValues',
117+
// The aggregates a query asked for in `related`.
118+
'aggregates',
117119
'hashValue',
118120
'CodingKeys',
119121
// The parameter of `init(entry:)`, which assigns the columns.
@@ -587,6 +589,10 @@ export function generate(
587589
: ` ${pub}var ${r.property}: [${r.dest}]?`,
588590
);
589591
}
592+
lines.push(
593+
' // The aggregates a query asked for in `related`; nil when it asked for none.',
594+
` ${pub}var aggregates: RelationshipAggregates<${row}>?`,
595+
);
590596
}
591597

592598
const params = [
@@ -596,6 +602,9 @@ export function generate(
596602
...relationships.map(
597603
r => `${r.property}: ${r.one ? `${r.dest}?` : `[${r.dest}]?`} = nil`,
598604
),
605+
...(relationships.length
606+
? [`aggregates: RelationshipAggregates<${row}>? = nil`]
607+
: []),
599608
];
600609
lines.push('');
601610
lines.push(` ${pub}init(`);
@@ -604,6 +613,9 @@ export function generate(
604613
for (const c of [...columns, ...relationships]) {
605614
lines.push(` self.${c.property} = ${c.property}`);
606615
}
616+
if (relationships.length) {
617+
lines.push(' self.aggregates = aggregates');
618+
}
607619
lines.push(' }');
608620

609621
lines.push('');
@@ -637,6 +649,9 @@ export function generate(
637649
for (const r of relationships) {
638650
lines.push(` ${r.property} = try entry.relationship(${str(r.name)})`);
639651
}
652+
if (relationships.length) {
653+
lines.push(' aggregates = RelationshipAggregates(entry: entry)');
654+
}
640655
lines.push(' }');
641656

642657
lines.push('');
@@ -647,7 +662,13 @@ export function generate(
647662
}
648663
lines.push(' ]');
649664
lines.push(' }');
650-
lines.push(...codingKeys([...columns, ...relationships]));
665+
lines.push(
666+
...codingKeys([
667+
...columns,
668+
...relationships,
669+
...(relationships.length ? [aggregatesKey(props)] : []),
670+
]),
671+
);
651672
const keyColumns = table.primaryKey.map(k =>
652673
columns.find(c => c.name === k)!,
653674
);
@@ -784,6 +805,23 @@ function columnsDecl(
784805
return lines;
785806
}
786807

808+
/**
809+
* The coding key of a row's `aggregates`: `aggregates`, unless a column or
810+
* relationship has that name on the wire, then with underscores appended
811+
* until it's free.
812+
*/
813+
function aggregatesKey(props: readonly {name: string}[]): {
814+
name: string;
815+
id: string;
816+
property: string;
817+
} {
818+
let name = 'aggregates';
819+
while (props.some(p => p.name === name)) {
820+
name += '_';
821+
}
822+
return {name, id: 'aggregates', property: 'aggregates'};
823+
}
824+
787825
/**
788826
* The `CodingKeys` of a struct whose properties aren't all named as their
789827
* keys, so `Codable` uses the names on the wire; none when they are.

‎packages/zero-swift-cli/test/sweep-schema.ts‎

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -157,6 +157,26 @@ export const wrapperStorage = createSchema({
157157
],
158158
});
159159

160+
const aggregated = table('aggregated')
161+
.columns({id: string(), aggregates: string(), otherID: string()})
162+
.primaryKey('id');
163+
const other = table('other').columns({id: string()}).primaryKey('id');
164+
165+
/** A column named as the property a row with relationships holds its
166+
* aggregates in. */
167+
export const aggregatesColumn = createSchema({
168+
tables: [aggregated, other],
169+
relationships: [
170+
relationships(aggregated, ({many}) => ({
171+
others: many({
172+
sourceField: ['otherID'],
173+
destField: ['id'],
174+
destSchema: other,
175+
}),
176+
})),
177+
],
178+
});
179+
160180
/** Enumeration values that are members of every enumeration, or keywords. */
161181
export const memberEnum = createSchema({
162182
tables: [

0 commit comments

Comments
 (0)