1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
use std::collections::HashMap;
use indexmap::IndexMap;
use serde::{Deserialize, Serialize};
use super::argument::{AUTO_PARAM_NAMES, ArgumentDefinition, AutoParams};
use crate::{
backend::types::ReadRouting,
schema::{
field_type::{DeprecationInfo, FieldType},
graphql_type_defs::default_jsonb_column,
security_config::InjectedParamSource,
source_probe::SourceKind,
},
};
/// The type of column used as the keyset cursor for relay pagination.
///
/// Determines how the cursor value is encoded/decoded and how the SQL comparison
/// is emitted (`bigint` vs `uuid` cast).
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, Default)]
#[serde(rename_all = "snake_case")]
#[non_exhaustive]
pub enum CursorType {
/// BIGINT / INTEGER column (default, backward-compatible).
/// Cursor is `base64(decimal_string)`.
#[default]
Int64,
/// UUID column.
/// Cursor is `base64(uuid_string)`.
Uuid,
}
pub(super) fn is_default_cursor_type(ct: &CursorType) -> bool {
*ct == CursorType::Int64
}
/// The total order a `LIMIT`/`OFFSET` page falls back to when the client asked
/// for none (#1303).
///
/// A page is a *slice of a sequence*, and a read with no `ORDER BY` is not a
/// sequence: PostgreSQL may return the same relation in a different physical
/// order for each page, so a client walking `?offset=` sees some rows twice and
/// never sees others — under `200`, with no error anywhere. #1287 closed the
/// half of that where the client *did* order and the ordering was not total;
/// this closes the half where it ordered by nothing at all.
///
/// # Why the compiler decides and not the SQL layer
///
/// A tie-breaker and a default ordering are different things. A tie-breaker has
/// no semantic content — any total order disambiguates ties *inside* an ordering
/// the client chose — so the SQL layer may pick one unaided. A default ordering
/// decides what "page 2" **means** when nobody said, which is the schema
/// author's call, and choosing well needs the schema: measured against
/// PostgreSQL 16 over 200 000 rows at a deep offset, a native `id` column costs
/// 4.2× the unordered plan and `pk_<type>` 1.7×. The page identity is never the
/// document's `data->>'id'` (#1569): no index applies to it, and its sort
/// detoasts every row of the relation, 7.7× there and 10× end to end on 2.17.0.
///
/// This is why the field is derived at compile time and sits beside
/// [`relay_cursor_column`](QueryDefinition::relay_cursor_column): the other
/// pagination family already declares its ordering key in the compiled schema,
/// for the same reason.
///
/// # Deliberately not `#[non_exhaustive]`
///
/// A downstream `match` over this enum must be exhaustive, so a third way to
/// reach an identity is a compile error at every site that lowers one rather
/// than a wildcard arm that silently renders nothing.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum PaginationOrder {
/// `ORDER BY "id" ASC` — the entity identity, as the relation's native `id` column.
///
/// The ordering the compiler **derives** when the author declared none, and the
/// answer a compile with no `--database` can always give: under ADR-0017 every
/// read table and view carries `id` as a base column (Trinity: `id UUID NOT NULL
/// UNIQUE`). Kept apart from [`Column`](Self::Column) because it is derived, not
/// authored: a compile that introspects the relation replaces it with
/// `Column("pk_<type>")` when the relation has that cheaper column, and refuses a
/// relation with neither; an authored column is never replaced.
Identity,
/// `ORDER BY <column> ASC` — a native column on the relation.
///
/// Either declared by the author or discovered by introspection
/// (`pk_<type>`, then `id`). The column must be **unique** over the
/// relation: a non-unique one leaves the order partial, which is the defect
/// this field exists to remove rather than a cheaper way to fix it. Nothing
/// in the catalog reports uniqueness for a view, so a declared column is
/// checked for existence and taken on trust.
Column(String),
}
/// A query definition compiled from `@fraiseql.query`.
///
/// Queries are declarative bindings to database views/tables.
/// They describe *what* to fetch, not *how* to fetch it.
///
/// # Example
///
/// ```
/// use fraiseql_core::schema::QueryDefinition;
///
/// let query = QueryDefinition::new("users", "User");
/// ```
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct QueryDefinition {
/// Query name (e.g., "users").
pub name: String,
/// Return type name (e.g., "User").
pub return_type: String,
/// Does this query return a list?
#[serde(default)]
pub returns_list: bool,
/// Does this query return `COUNT(*)` over [`sql_source`](Self::sql_source)
/// instead of rows?
///
/// Compiled as the sibling of a list query that opted in (`count = true`),
/// named `<query>Count` and exposed as `Int!`. It exists because a bare
/// `[T]` list has nowhere to hang a total, so an offset-paginated client had
/// no way to learn how many rows match its filter — `totalCount` was
/// reachable only through a Relay connection, and a Relay connection is
/// keyset-only, so obtaining the count cost random access (#938).
///
/// [`return_type`](Self::return_type) stays the **entity** type rather than
/// `Int`: the filter machinery is keyed on it (`where` input types, native
/// column casts, RLS policy lookup), and re-pointing it at a scalar would
/// silently detach the count from the filters whose rows it is counting.
/// Only the *rendered* GraphQL return type differs.
///
/// The count reflects the full filtered set, independent of `limit`/`offset`
/// — which is the entire point — so the sibling carries `where` alone and
/// no pagination arguments.
#[serde(default, skip_serializing_if = "std::ops::Not::not")]
pub returns_count: bool,
/// Is the return value nullable?
#[serde(default)]
pub nullable: bool,
/// Query arguments.
#[serde(default)]
pub arguments: Vec<ArgumentDefinition>,
/// SQL source table/view (for direct table queries), or the set-returning function
/// this query reads when [`sql_source_kind`](Self::sql_source_kind) says so.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub sql_source: Option<String>,
/// What [`sql_source`](Self::sql_source) names.
///
/// A relation by default. A [`SourceKind::Function`] source is a `STABLE` or
/// `IMMUTABLE` set-returning function returning the rows a view would (`data jsonb`,
/// plus any declared native column). Its parameters bind positionally the way a
/// mutation's do: the query's own arguments in declaration order, then its
/// [`inject_params`](Self::inject_params) in map order. The executor reads
/// `FROM fn($1, …)`, so RLS, the client's `where`, ordering, pagination and
/// projection apply to the function's rows as they would to a view's.
///
/// A function root reads nothing another operation could identify: it is not an
/// entity source, so no Relay connection, `node(id:)`, `_entities`, count sibling,
/// stream or row-shaped read is served from it.
#[serde(default, skip_serializing_if = "SourceKind::is_relation")]
pub sql_source_kind: SourceKind,
/// The declared function that answers this root field, in place of reading a
/// relation (#1329).
///
/// Names an entry in the compiled `functions` section whose trigger is
/// `request:query`. The engine invokes it with this field's arguments, as the
/// requesting principal, and projects its result through this query's
/// `return_type` — so a function-backed field is introspectable, typed, and
/// governed by the same `requires_role` / `requires_actor` / field-RBAC rules
/// as any other root field.
///
/// # Root fields only
///
/// There is no nested-field equivalent, deliberately. A function attached to a
/// field *inside* a type would be invoked once per row, which is an N+1 in
/// isolates rather than in queries — measurably worse. Bounding it to root
/// fields makes "one invocation per query" a property of the shape rather than
/// a guideline, and the compiler refuses the nested spelling rather than
/// documenting against it.
///
/// # Mutually exclusive with [`sql_source`](Self::sql_source)
///
/// A field resolves one way. The compiler refuses a query declaring both, and
/// refuses one declaring neither where the SQL path needs a relation — there is
/// no precedence rule to remember and no silent winner.
///
/// # Cost
///
/// An invocation costs ~5–8 ms on top of the work the function itself does,
/// which is the same order as this repository's documented cold read and
/// roughly 5× a cache hit. That is a defensible price for computation SQL
/// cannot express and a poor one for anything a view could answer; it is
/// stated here, and in `docs/architecture/functions.md`, so the choice is made
/// knowingly.
///
/// A function-backed field is **not cached**: the result cache keys and invalidates
/// rows of a relation, and this field reads none, so every request runs the
/// function. [`cache_ttl_seconds`](Self::cache_ttl_seconds) and
/// [`additional_views`](Self::additional_views) are compile errors beside a
/// `function` rather than settings that are accepted and ignored.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub function: Option<String>,
/// Description.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub description: Option<String>,
/// Auto-wired parameters (where, orderBy, limit, offset).
#[serde(default)]
pub auto_params: AutoParams,
/// Deprecation information (from @deprecated directive).
/// When set, this query is marked as deprecated in the schema.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub deprecation: Option<DeprecationInfo>,
/// JSONB column name (e.g., "data").
/// Used to extract data from JSONB columns in query results.
#[serde(default = "default_jsonb_column")]
pub jsonb_column: String,
/// Whether this query is a Relay connection query.
///
/// When `true`, the compiler wraps the result in `XxxConnection` with
/// `edges { cursor node { ... } }` and `pageInfo` fields, using keyset
/// pagination on `pk_{snake_case(return_type)}` (BIGINT).
#[serde(default, skip_serializing_if = "std::ops::Not::not")]
pub relay: bool,
/// Keyset pagination column for relay queries.
///
/// Derived from the return type name: `User` → `pk_user`.
/// This BIGINT column lives in the view (`sql_source`) and is used as the
/// stable sort key for cursor-based keyset pagination:
/// - Forward: `WHERE {col} > $cursor ORDER BY {col} ASC LIMIT $first`
/// - Backward: `WHERE {col} < $cursor ORDER BY {col} DESC LIMIT $last`
///
/// Only set when `relay = true`.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub relay_cursor_column: Option<String>,
/// Type of the keyset cursor column.
///
/// Defaults to `Int64` for backward compatibility with schemas that use `pk_{type}`
/// BIGINT columns. Set to `Uuid` when the cursor column has a UUID type.
///
/// Only meaningful when `relay = true`.
#[serde(default, skip_serializing_if = "is_default_cursor_type")]
pub relay_cursor_type: CursorType,
/// The order an offset-paginated read of this query falls back to when the
/// client requests none (#1303).
///
/// Resolved at compile time for every list query that paginates, and `None`
/// for every query that does not — plus the one that does and whose author
/// declared `pagination_order = "none"`, which is how a view carrying its
/// own `ORDER BY` keeps it. That opt-out is *declared* rather than inferred:
/// the compiler cannot see a view's body, and ordering unconditionally would
/// silently destroy the escape hatch its own `auto_param_warnings` tells
/// authors to use.
///
/// See [`PaginationOrder`] for why this is decided here and not by the SQL
/// layer, and for what each variant costs.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub pagination_order: Option<PaginationOrder>,
/// Server-side parameters injected from JWT claims at runtime.
///
/// Keys are SQL column names. Values describe where to source the runtime value.
/// These params are NOT exposed as GraphQL arguments.
///
/// For queries: adds a `WHERE key = $value` condition per entry using the same
/// `WhereClause` mechanism as `TenantEnforcer`. Works on all adapters.
///
/// Clients cannot override these values.
#[serde(default, skip_serializing_if = "IndexMap::is_empty")]
pub inject_params: IndexMap<String, InjectedParamSource>,
/// Where this query's reads may be served from (#957).
///
/// Read-replica routing is otherwise a whole-server decision: the pin window
/// and the staleness budget apply to every query alike, so an operator sizing
/// them for the strictest query gives up the offload on all the others, and
/// sizing them for the common case silently serves the strict one stale.
///
/// FraiseQL defines and enforces this shape; an authoring language emits it —
/// A `@reads_from(...)` directive is one spelling of it.
/// Replica **topology** deliberately stays out of the compiled artifact: URLs
/// are server configuration and secrets.
///
/// See [`ReadRouting`] for what each answer guarantees, including why
/// `primary` also bypasses the result cache.
#[serde(default, skip_serializing_if = "ReadRouting::is_default")]
pub read_routing: ReadRouting,
/// Per-query result cache TTL in seconds.
///
/// Overrides the global `CacheConfig::ttl_seconds` for this query's view.
/// Common use-cases:
/// - Reference data (countries, currencies): `3600` (1 h)
/// - Live / real-time data: `0` (bypass cache entirely)
///
/// `None` → use the global cache TTL.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub cache_ttl_seconds: Option<u64>,
/// Additional database views this query reads beyond the primary `sql_source`.
///
/// When this query JOINs or queries multiple views, list all secondary views here
/// so that mutations touching those views correctly invalidate this query's cache
/// entries.
///
/// Without this list, only `sql_source` is registered for invalidation. Any mutation
/// that modifies a secondary view will NOT invalidate this query's cache — silently
/// serving stale data.
///
/// Each entry must be a valid SQL identifier (letters, digits, `_`) validated by the
/// CLI compiler at schema compile time.
///
/// # Example
///
/// ```python
/// @fraiseql.query(
/// sql_source="v_user_with_posts",
/// additional_views=["v_post"],
/// )
/// def users_with_posts() -> list[UserWithPosts]: ...
/// ```
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub additional_views: Vec<String>,
/// Role required to execute this query and see it in introspection.
///
/// When set, only users with this role can discover and execute this query.
/// Users without the role receive `"Unknown query"` (not `FORBIDDEN`)
/// to prevent role enumeration.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub requires_role: Option<String>,
/// Actor classes permitted to execute this query — an **allow-list** (#966).
///
/// Empty (the default) means unrestricted. Non-empty means the request's
/// derived [`ActorType`](crate::security::ActorType) must be one of these, or
/// the operation is refused — regardless of what roles the caller holds. That
/// independence is the point: "autonomous agents may not read this" is a
/// statement about the *kind* of principal, not about its permissions.
///
/// # An allow-list, not a deny-list
///
/// A deny-list would admit every actor class added after it was written. An
/// allow-list refuses them, which is the fail-closed direction: a new
/// [`ActorType`](crate::security::ActorType) variant is in nobody's list until
/// an author puts it there.
///
/// # Delegation is deliberately not consulted
///
/// For a delegated request (RFC 8693: an agent acting for a human), the
/// classification is `AiAgent` and the check does **not** fall back to the
/// permissions of the human in `acting_for`. Composite authorization already
/// happens through roles — a delegated token carries the human's roles, so
/// `requires_role` consults them — and having `requires_actor` do the same
/// would make it a no-op for exactly the case it exists for.
///
/// # Anonymous
///
/// A request with no security context has no classification, so a non-empty
/// list refuses it. Fail-closed, and it does not depend on
/// [`ActorType::default`](crate::security::ActorType) being the benign variant.
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub requires_actor: Vec<crate::security::ActorType>,
/// Custom REST path override (e.g., `"/users/{id}/posts"`).
#[serde(default, skip_serializing_if = "Option::is_none")]
pub rest_path: Option<String>,
/// REST HTTP method override (e.g., `"GET"`).
#[serde(default, skip_serializing_if = "Option::is_none")]
pub rest_method: Option<String>,
/// Whether this query may be exported as a stream over REST (#958).
///
/// Default `false`. `Accept: application/x-ndjson`, `text/csv` and the XLSX type
/// are refused with `406` on a route that does not opt in — the JSON
/// representation is unaffected.
///
/// # Why a per-route opt-in rather than a transport-wide switch
///
/// A streamed export is not a bigger page. It reads the **whole** filtered
/// relation, bypasses `max_page_size` by construction (an export total is not a
/// page), and holds a pooled database connection for as long as the client takes
/// to read it. Those are reasonable properties for a route meant to hand over a
/// dataset and unreasonable ones for the other kind of route, which is most of
/// them — so which routes have them is the schema author's decision, made per
/// route, rather than a consequence of the REST transport being on.
///
/// ```python
/// @fraiseql.query(sql_source="v_invoice", rest_stream=True)
/// def invoices() -> list[Invoice]: ...
/// ```
#[serde(default, skip_serializing_if = "std::ops::Not::not")]
pub rest_stream: bool,
/// Native columns detected at compile time for direct query arguments.
///
/// Maps argument name → the column's [`NativeColumn`]: its PostgreSQL type (e.g.,
/// `"uuid"`, `"int4"`, `""`; an empty string means no type cast is needed, e.g. `text`)
/// and whether PostgreSQL proves it `NOT NULL`.
///
/// At runtime, arguments present in this map generate `WHERE col = $N` (native column
/// lookup) instead of `WHERE data->>'col' = $N` (JSONB extraction), enabling B-tree
/// index usage for single-entity lookups.
///
/// Only populated when `fraiseql compile --database <url>` is used. Schemas compiled
/// without a database URL omit this field and fall back to JSONB extraction.
#[serde(default, skip_serializing_if = "HashMap::is_empty")]
pub native_columns: HashMap<String, NativeColumn>,
}
/// A native column a query reads directly instead of through its JSONB document.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct NativeColumn {
/// The column's PostgreSQL type, as a cast suffix (`"uuid"`, `"int4"`); empty for a column
/// that needs no cast.
pub pg_type: String,
/// Whether PostgreSQL proves the column `NOT NULL` (#1533): a base relation's column
/// declared so, as `compile --database` reads it from the catalog. A view's column is
/// never proven (PostgreSQL reports every view column nullable), nor is one inferred
/// without a database. An ordered relay page seeks its index with a row comparison only
/// when every sort key is a proven `NOT NULL` column.
pub not_null: bool,
}
impl NativeColumn {
/// A native column nothing proves `NOT NULL`.
#[must_use]
pub fn nullable(pg_type: impl Into<String>) -> Self {
Self {
pg_type: pg_type.into(),
not_null: false,
}
}
}
impl QueryDefinition {
/// Create a new query definition.
#[must_use]
pub fn new(name: impl Into<String>, return_type: impl Into<String>) -> Self {
Self {
name: name.into(),
return_type: return_type.into(),
returns_list: false,
returns_count: false,
nullable: false,
arguments: Vec::new(),
sql_source: None,
sql_source_kind: SourceKind::Relation,
function: None,
description: None,
auto_params: AutoParams::default(),
deprecation: None,
jsonb_column: "data".to_string(),
relay: false,
relay_cursor_column: None,
relay_cursor_type: CursorType::Int64,
pagination_order: None,
inject_params: IndexMap::new(),
read_routing: ReadRouting::default(),
cache_ttl_seconds: None,
additional_views: Vec::new(),
requires_role: None,
requires_actor: Vec::new(),
rest_path: None,
rest_method: None,
rest_stream: false,
native_columns: HashMap::new(),
}
}
/// Set this query to return a list.
#[must_use]
pub const fn returning_list(mut self) -> Self {
self.returns_list = true;
self
}
/// Set the SQL source.
#[must_use]
pub fn with_sql_source(mut self, source: impl Into<String>) -> Self {
self.sql_source = Some(source.into());
self
}
/// The relation this query reads, or `None` for a function root, a declared
/// function (`function`) or a query with no source.
///
/// What a lookup of "the query that reads type `T`" asks — the node lookup, the
/// `_entities` resolver, a nested level's own read: a function root computes its rows
/// from its arguments, so it is no relation of `T` to look a row up in.
#[must_use]
pub fn reads_relation(&self) -> Option<&str> {
match (self.sql_source_kind, self.function.as_ref()) {
(SourceKind::Relation, None) => self.sql_source.as_deref(),
_ => None,
}
}
/// The arguments a function root binds to its function's parameters, in declaration
/// order: every argument but the auto-params, which shape the read of the call
/// rather than the call. The query's `inject_params` follow them, one parameter each.
pub fn function_arguments(&self) -> impl Iterator<Item = &ArgumentDefinition> {
self.arguments
.iter()
.filter(|arg| !AUTO_PARAM_NAMES.contains(&arg.name.as_str()))
}
/// How many parameters a function root's function takes: its
/// [`function_arguments`](Self::function_arguments), then one per inject param.
#[must_use]
pub fn function_arity(&self) -> usize {
self.function_arguments().count() + self.inject_params.len()
}
/// Read this query from the set-returning function `function`, its arguments bound to
/// the function's parameters.
///
/// See [`sql_source_kind`](Self::sql_source_kind) for the binding and what a function
/// root does not serve.
#[must_use]
pub fn with_sql_source_function(mut self, function: impl Into<String>) -> Self {
self.sql_source = Some(function.into());
self.sql_source_kind = SourceKind::Function;
self
}
/// Back this root field with a declared function instead of a relation (#1329).
///
/// See [`function`](Self::function) for what the engine does with the name and
/// what it costs.
#[must_use]
pub fn with_function(mut self, function: impl Into<String>) -> Self {
self.function = Some(function.into());
self
}
/// Derive the `<name>Count` sibling of this list query (#938).
///
/// This is the **only** way a count query is built. A sibling query that
/// answers "how many rows match?" against the same view is a second door
/// onto the same rows, and a second door that forgets one of the first's
/// restrictions is an oracle: a count that ignores `inject_params` reports
/// other tenants' row totals, and one that ignores `requires_role` answers
/// callers who cannot see the list at all. Neither leaks a row, which is
/// exactly why it would survive review — so the inheritance is centralised
/// here rather than spelled out at each construction site (the `_entities`
/// lesson, #1030).
///
/// Inherited, deliberately: the entity `return_type` and `sql_source` (same
/// rows), `inject_params` (same tenant scoping), `requires_role` (same
/// visibility), explicitly declared `arguments` (they lower into the same
/// `WHERE`), `native_columns` (same casts, so the count uses the same
/// indexes), `additional_views` (same cache invalidation) and `deprecation`.
///
/// Dropped, deliberately: `limit`/`offset`/`orderBy` — a total that moved
/// with the page would answer a question nobody asked; `pagination_order`
/// with them, since a scalar total has no rows to order; `relay`, which has
/// its own `totalCount`; and the REST overrides, since the REST surface
/// already counts through `Prefer: count=exact`.
///
/// `function` is dropped for a different reason than the rest: a count is
/// `SELECT COUNT(*)` over a relation, and a function-backed field has none —
/// which is why `count = true` beside `function` is a compile error (#1329).
/// Dropping it here means a sibling hand-built through this constructor fails
/// as "no SQL source" rather than invoking the function and projecting its
/// object as a scalar total.
#[must_use]
pub fn count_sibling(&self) -> Self {
Self {
name: format!("{}Count", self.name),
function: None,
returns_list: false,
returns_count: true,
nullable: false,
auto_params: AutoParams {
has_where: self.auto_params.has_where,
has_order_by: false,
has_limit: false,
has_offset: false,
},
relay: false,
relay_cursor_column: None,
relay_cursor_type: CursorType::Int64,
pagination_order: None,
rest_path: None,
rest_method: None,
description: Some(format!(
"Total number of `{}` rows matching `where`, independent of any \
limit/offset applied to `{}`.",
self.return_type, self.name
)),
..self.clone()
}
}
/// Mark this query as deprecated.
///
/// # Example
///
/// ```
/// use fraiseql_core::schema::QueryDefinition;
///
/// let query = QueryDefinition::new("oldUsers", "User")
/// .deprecated(Some("Use 'users' instead".to_string()));
/// assert!(query.is_deprecated());
/// ```
#[must_use]
pub fn deprecated(mut self, reason: Option<String>) -> Self {
self.deprecation = Some(DeprecationInfo { reason });
self
}
/// Check if this query is deprecated.
#[must_use]
pub const fn is_deprecated(&self) -> bool {
self.deprecation.is_some()
}
/// Get the deprecation reason if deprecated.
#[must_use]
pub fn deprecation_reason(&self) -> Option<&str> {
self.deprecation.as_ref().and_then(|d| d.reason.as_deref())
}
/// The full set of GraphQL arguments this query accepts, for rendering into
/// the federation `_service` SDL, generated clients, and introspection.
///
/// The auto-wired `where`/`orderBy`/`limit`/`offset` arguments are gated by
/// [`auto_params`](Self::auto_params) and read directly from the argument map
/// at runtime, so they are deliberately *not* stored in
/// [`arguments`](Self::arguments) (where the runtime would otherwise mistake a
/// synthesized `limit`/`offset` for an explicit column filter). This method
/// materialises them so every consumer that renders from the argument list can
/// surface — and a generated client can actually pass — them.
///
/// `where`/`orderBy` are typed against the derived filter surface —
/// `{Entity}WhereInput` and `[{Entity}OrderByInput!]` — when `schema` carries
/// those types, and fall back to the `JSON` scalar when it does not. Either
/// way the runtime parses the raw value via `WhereClause::from_graphql_json`
/// / `OrderByClause::from_graphql_json`; the type is what clients see, not
/// what the executor reads.
///
/// # Why this takes a schema
///
/// The published type of an auto-wired argument is a property of the schema,
/// not of the query alone: [`derived_inputs::derive`] emits
/// `{Entity}WhereInput` only for a return type whose fields the schema can
/// adjudicate, and skips any name the author already declared. Reading the
/// answer from the same place that produced it is what makes a dangling type
/// reference unrepresentable — the argument is typed **iff** the type exists.
/// A cached answer on `QueryDefinition` would let a caller publish the name
/// without the schema that justifies it.
///
/// An explicit argument always wins: if the query already declares an argument
/// of the same name it is left untouched and no duplicate is synthesized.
///
/// Relay connection queries are returned unchanged — their pagination surface
/// (`first`/`after`/`last`/`before`) is owned by each renderer's dedicated
/// relay path, which adds [`connection_arguments`](Self::connection_arguments).
///
/// [`derived_inputs::derive`]: crate::schema::derived_inputs::derive
#[must_use]
pub fn graphql_arguments(
&self,
schema: &super::schema::CompiledSchema,
) -> Vec<ArgumentDefinition> {
let mut args = self.arguments.clone();
if self.relay {
return args;
}
let declared = |name: &str| self.arguments.iter().any(|a| a.name == name);
let ap = &self.auto_params;
if let Some(filter) = self.where_argument(schema) {
if !declared("where") {
args.push(filter);
}
}
if let Some(order_by) = self.order_by_argument(schema) {
if !declared("orderBy") {
args.push(order_by);
}
}
if ap.has_limit && !declared("limit") {
args.push(
ArgumentDefinition::optional("limit", FieldType::Int)
.with_description("Maximum number of items to return."),
);
}
if ap.has_offset && !declared("offset") {
args.push(
ArgumentDefinition::optional("offset", FieldType::Int)
.with_description("Number of items to skip before returning results."),
);
}
args
}
/// The `where` argument this query publishes (list or relay connection alike), or `None`
/// when it reads none.
#[must_use]
pub fn where_argument(
&self,
schema: &super::schema::CompiledSchema,
) -> Option<ArgumentDefinition> {
self.auto_params.has_where.then(|| {
ArgumentDefinition::optional("where", self.where_argument_type(schema))
.with_description(
"Filter predicate: a nested object of `{ field: { operator: value } }`, \
combined with `_and`/`_or`/`_not`.",
)
})
}
/// What a relay connection publishes beyond its cursor window: the `where` and `orderBy`
/// the relay runner reads, typed exactly as a list's are (#1159, #1535). Empty for a
/// list query, whose arguments are [`graphql_arguments`](Self::graphql_arguments).
#[must_use]
pub fn connection_arguments(
&self,
schema: &super::schema::CompiledSchema,
) -> Vec<ArgumentDefinition> {
if !self.relay {
return Vec::new();
}
self.where_argument(schema)
.into_iter()
.chain(self.order_by_argument(schema))
.collect()
}
/// The type `where` publishes: the derived `{Entity}WhereInput` when the
/// schema carries it, `JSON` when it does not.
///
/// The fallback is not a degraded mode to be fixed later — it is the honest
/// answer for a schema whose return type carries no field list, where a
/// derived input object would positively forbid every key the engine still
/// accepts.
fn where_argument_type(&self, schema: &super::schema::CompiledSchema) -> FieldType {
let name = crate::schema::derived_inputs::where_input_type_name(&self.return_type);
if schema.find_input_type(&name).is_some() {
FieldType::Input(name)
} else {
FieldType::Json
}
}
/// The `orderBy` argument this query publishes (list or relay connection alike), or
/// `None` when it publishes none.
///
/// Typed `[{Owner}OrderByInput!]` when the schema carries the item type
/// ([`order_by_type_names`](crate::schema::derived_inputs::order_by_type_names)); `JSON`
/// when the schema cannot adjudicate the return type (#939). A query whose type has no
/// sortable key publishes no `orderBy` at all: an argument no value of can be served
/// would be advertisement of nothing (#1159).
///
/// A list, because `OrderByClause::from_graphql_json`'s array branch is what
/// takes `{field, direction}` items and applies them in order. The object
/// branch (`{name: "DESC"}`) keeps executing but has no expression in this
/// type — its key order is not something a JSON object can promise.
#[must_use]
pub fn order_by_argument(
&self,
schema: &super::schema::CompiledSchema,
) -> Option<ArgumentDefinition> {
use crate::schema::derived_inputs::{order_by_type_names, sortable_keys};
if !self.auto_params.has_order_by {
return None;
}
let arg_type = match sortable_keys(schema, &self.return_type, &self.native_columns) {
None => FieldType::Json,
Some(keys) if keys.is_empty() => return None,
Some(_) => match order_by_type_names(schema, self) {
Some((item, _)) if schema.find_input_type(&item).is_some() => {
FieldType::list(FieldType::Input(item))
},
_ => FieldType::Json,
},
};
Some(ArgumentDefinition::optional("orderBy", arg_type).with_description(
"Sort order: a list of `{ field, direction }` keys, applied in order.",
))
}
/// The argument names a client document may write on this field
/// (GraphQL § 5.4.1), for [`validate_argument_names`].
///
/// [`graphql_arguments`](Self::graphql_arguments) is what introspection
/// *publishes*; this is what the runtime actually *reads*, which is wider in
/// two places:
///
/// * A relay connection's cursor window (`first`/`after`/`last`/`before`) is owned by each
/// renderer's relay path rather than by `auto_params`, and the relay runner also reads
/// `where`/`orderBy` from the merged argument map when the matching auto-param is on.
/// * `nearest` (#386, #959) is a runtime-only similarity-search argument. Accepting it here is
/// what lets its own diagnostics — not eligible on relay, needs a list query, unknown metric,
/// wrong dimension — be what the client sees, instead of a blanket "unknown argument". It is
/// refused on a count sibling, which never reads it.
///
/// [`validate_argument_names`]: crate::runtime::validate_argument_names
#[must_use]
pub fn accepted_argument_names(&self, schema: &super::schema::CompiledSchema) -> Vec<String> {
let mut names: Vec<String> =
self.graphql_arguments(schema).into_iter().map(|arg| arg.name).collect();
if self.relay {
names.extend(["first", "after", "last", "before"].map(String::from));
if self.auto_params.has_where && !names.iter().any(|n| n == "where") {
names.push("where".to_string());
}
if self.order_by_argument(schema).is_some() && !names.iter().any(|n| n == "orderBy") {
names.push("orderBy".to_string());
}
}
if !self.returns_count {
names.push("nearest".to_string());
}
names
}
}
impl Default for QueryDefinition {
fn default() -> Self {
Self::new("", "")
}
}