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
use std::collections::HashMap;
use indexmap::IndexMap;
use serde::{Deserialize, Serialize};
use super::argument::{ArgumentDefinition, AutoParams};
use crate::schema::{
field_type::{DeprecationInfo, FieldType},
graphql_type_defs::default_jsonb_column,
security_config::InjectedParamSource,
};
/// 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
}
/// 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,
/// 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).
#[serde(default, skip_serializing_if = "Option::is_none")]
pub sql_source: 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,
/// 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>,
/// 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>,
/// 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>,
/// Native columns detected at compile time for direct query arguments.
///
/// Maps argument name → PostgreSQL cast suffix (e.g., `"uuid"`, `"int4"`, `""`).
/// An empty string means the column exists but needs no type cast (e.g. `text`).
///
/// 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, String>,
}
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,
nullable: false,
arguments: Vec::new(),
sql_source: 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,
inject_params: IndexMap::new(),
cache_ttl_seconds: None,
additional_views: Vec::new(),
requires_role: None,
rest_path: None,
rest_method: None,
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
}
/// 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` carry dynamic, per-field shapes, so they are typed as the
/// `JSON` scalar; the runtime parses the raw value via
/// `WhereClause::from_graphql_json` / `OrderByClause::from_graphql_json`.
///
/// 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, not by `auto_params`.
#[must_use]
pub fn graphql_arguments(&self) -> 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 ap.has_where && !declared("where") {
args.push(ArgumentDefinition::optional("where", FieldType::Json).with_description(
"Filter predicate: a nested object of `{ field: { operator: value } }`, \
combined with `_and`/`_or`/`_not`.",
));
}
if ap.has_order_by && !declared("orderBy") {
args.push(ArgumentDefinition::optional("orderBy", FieldType::Json).with_description(
"Sort order: `{ field: \"ASC\" | \"DESC\" }` or \
`[{ field, direction }]`.",
));
}
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
}
}
impl Default for QueryDefinition {
fn default() -> Self {
Self::new("", "")
}
}