postrust-graphql 2.4.1

GraphQL API and realtime subscriptions generated from a PostgreSQL schema
Documentation
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
//! Table to GraphQL ObjectType conversion.

use crate::types::{pg_type_to_graphql, GraphQLType};
use postrust_core::schema_cache::{Column, Table};

/// Represents a GraphQL field derived from a database column.
#[derive(Debug, Clone)]
#[non_exhaustive]
pub struct GraphQLField {
    /// Field name (same as column name).
    pub name: String,
    /// Field description from column comment.
    pub description: Option<String>,
    /// GraphQL type for this field.
    pub graphql_type: GraphQLType,
    /// Whether the field is nullable.
    pub nullable: bool,
    /// Whether this is a primary key field.
    pub is_pk: bool,
    /// The arguments a computed field takes from the caller, as `(name,
    /// PostgreSQL type, required)`. Empty for a column, and for a computed
    /// field that takes only the row and the session.
    pub arguments: Vec<(String, String, bool)>,
}

impl GraphQLField {
    /// Create a GraphQL field from a database column.
    pub fn from_column(column: &Column) -> Self {
        let graphql_type = pg_type_to_graphql(&column.nominal_type);
        let nullable = column.nullable && !column.is_pk;

        Self {
            name: column.name.clone(),
            description: column.description.clone(),
            graphql_type,
            nullable,
            is_pk: column.is_pk,
            arguments: Vec::new(),
        }
    }

    /// Get the GraphQL type string with nullability.
    pub fn type_string(&self) -> String {
        let base = format!("{}", self.graphql_type);
        if self.nullable {
            base
        } else {
            format!("{}!", base)
        }
    }
}

/// Represents a GraphQL ObjectType derived from a database table.
#[derive(Debug, Clone)]
#[non_exhaustive]
pub struct TableObjectType {
    /// The original table.
    pub table: Table,
    /// GraphQL type name (PascalCase).
    pub name: String,
    /// Base name for generated helper types owned by this table.
    pub local_name: String,
    /// Fields derived from columns: the ones a read may name.
    ///
    /// Empty where the role may write this table and not read it, which is a
    /// table with no GraphQL type -- see [`crate::role`].
    pub fields: Vec<GraphQLField>,
    /// Fields a write may name, before the write permission narrows them.
    ///
    /// The same list before the read permission was applied, which is what
    /// makes a column a role may set without seeing expressible: `fields` is
    /// what the type shows and this is what the insert and update inputs are
    /// built from. Equal to `fields` where nothing narrowed them.
    pub writable_fields: Vec<GraphQLField>,
    /// The type's description: the table's comment, or the one metadata gave
    /// instead. `Some("")` is a description that was given and is empty, which
    /// is how metadata says the type has none.
    pub description: Option<String>,
}

impl TableObjectType {
    /// Create a GraphQL ObjectType from a database table.
    ///
    /// The type is named after the table. Use [`Self::from_table_named`] when
    /// the name must be disambiguated (for example when the same table name
    /// appears in more than one exposed schema).
    pub fn from_table(table: &Table) -> Self {
        Self::from_table_named(table, &table.name, &crate::names::NameOverrides::default())
    }

    /// Create a GraphQL ObjectType using an explicit base name.
    /// A field for a computed column.
    ///
    /// A function of one argument of the table's own row type, which
    /// PostgreSQL lets a query read as though it were a column. Always
    /// nullable: the function decides, and nothing in the catalogue says it
    /// cannot return null.
    fn computed_field(
        name: &str,
        computed: &postrust_core::schema_cache::ComputedColumn,
    ) -> GraphQLField {
        GraphQLField {
            name: name.to_string(),
            // The function it calls, where it has no comment of its own --
            // which is what Hasura says, and is the one thing a reader of the
            // schema cannot otherwise find out.
            description: computed.description.clone().or_else(|| {
                Some(format!(
                    "A computed field, executes function \"{}\"",
                    computed.function.name
                ))
            }),
            graphql_type: pg_type_to_graphql(&computed.data_type),
            nullable: true,
            is_pk: false,
            arguments: Vec::new(),
        }
    }

    /// Build the field for a table, under a name chosen by the caller.
    ///
    /// Separate from the unnamed constructor because a custom table name has
    /// to reach the field before its type name is derived from it.
    pub fn from_table_named(
        table: &Table,
        base_name: &str,
        names: &crate::names::NameOverrides,
    ) -> Self {
        // Named exactly like the table. A GraphQL type is conventionally
        // PascalCase, but the schema a Hasura client was generated against
        // spells this `author`, and a client cannot be told otherwise: the
        // type name is in its generated types, its fragments and its cache
        // keys.
        let name = base_name.to_string();
        // Columns first, then the computed ones. A computed column named
        // after a real one is left out for the same reason a relationship is:
        // two fields of one name abort the schema build, and the column is the
        // table's own data.
        let mut fields: Vec<GraphQLField> = table
            .columns
            .values()
            .map(|column| {
                let mut field = GraphQLField::from_column(column);
                // The database type remains the source of truth for SQL. A
                // metadata override changes only the scalar in the public
                // GraphQL contract.
                if let Some(given) = names.column_type(&table.schema, &table.name, &column.name) {
                    field.graphql_type = given;
                }
                // A column may be exposed under another name. This is the one
                // place the schema decides that; every resolver reads it back
                // the other way, from the field to the column.
                if let Some(given) = names.column(&table.schema, &table.name, &column.name) {
                    field.name = given.to_string();
                }
                // A description given in metadata replaces the column's own
                // comment, and an empty one removes it.
                if let Some(comment) =
                    names.column_comment(&table.schema, &table.name, &column.name)
                {
                    field.description = Some(comment.to_string()).filter(|c| !c.is_empty());
                }
                field
            })
            .collect();
        let mut computed: Vec<(&String, &postrust_core::schema_cache::ComputedColumn)> =
            table.computed_columns.iter().collect();
        computed.sort_by_key(|(name, _)| (*name).clone());
        for (function, definition) in computed {
            // A computed field is named in Hasura's metadata rather than after
            // its function, so a migrated schema says which is which.
            let exposed = names
                .computed_field(&table.schema, &table.name, function)
                .unwrap_or(function);
            if fields.iter().any(|f| f.name == exposed) {
                continue;
            }
            let mut field = Self::computed_field(exposed, definition);
            if let Some(comment) = names.computed_comment(&table.schema, &table.name, function) {
                field.description = Some(comment.to_string()).filter(|c| !c.is_empty());
            }
            fields.push(field);
        }

        let description = names
            .table_comment(&table.schema, &table.name)
            .map(str::to_string)
            .or_else(|| table.description.clone());

        Self {
            table: table.clone(),
            local_name: name.clone(),
            name,
            // Nothing has narrowed the read yet, so the two lists start equal.
            // A role's schema splits them where its object type is built.
            writable_fields: fields.clone(),
            fields,
            description,
        }
    }

    /// Get the GraphQL type name.
    pub fn name(&self) -> &str {
        &self.name
    }

    /// Get the description from table comment.
    pub fn description(&self) -> Option<&str> {
        self.description.as_deref()
    }

    /// The name of the table itself, which is not always the type's: a
    /// configured base name renames the type and leaves the table alone.
    pub fn table_name(&self) -> &str {
        &self.table.name
    }

    /// Get all fields.
    pub fn fields(&self) -> &[GraphQLField] {
        &self.fields
    }

    /// Get a field by name.
    pub fn get_field(&self, name: &str) -> Option<&GraphQLField> {
        self.fields.iter().find(|f| f.name == name)
    }

    /// Check if a field exists.
    pub fn has_field(&self, name: &str) -> bool {
        self.get_field(name).is_some()
    }

    /// Get primary key fields.
    pub fn pk_fields(&self) -> Vec<&GraphQLField> {
        self.fields.iter().filter(|f| f.is_pk).collect()
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use indexmap::IndexMap;
    use pretty_assertions::assert_eq;

    fn create_test_table() -> Table {
        let mut columns = IndexMap::new();
        columns.insert(
            "id".into(),
            Column {
                name: "id".into(),
                description: Some("Primary key".into()),
                nullable: false,
                data_type: "integer".into(),
                nominal_type: "int4".into(),
                max_len: None,
                default: Some("nextval('users_id_seq')".into()),
                enum_values: vec![],
                is_pk: true,
                position: 1,
                always_generated: false,
                domain_type: None,
            },
        );
        columns.insert(
            "name".into(),
            Column {
                name: "name".into(),
                description: Some("User name".into()),
                nullable: false,
                data_type: "text".into(),
                nominal_type: "text".into(),
                max_len: None,
                default: None,
                enum_values: vec![],
                is_pk: false,
                position: 2,
                always_generated: false,
                domain_type: None,
            },
        );
        columns.insert(
            "email".into(),
            Column {
                name: "email".into(),
                description: None,
                nullable: true,
                data_type: "text".into(),
                nominal_type: "text".into(),
                max_len: None,
                default: None,
                enum_values: vec![],
                is_pk: false,
                position: 3,
                always_generated: false,
                domain_type: None,
            },
        );
        columns.insert(
            "metadata".into(),
            Column {
                name: "metadata".into(),
                description: Some("JSON metadata".into()),
                nullable: true,
                data_type: "jsonb".into(),
                nominal_type: "jsonb".into(),
                max_len: None,
                default: None,
                enum_values: vec![],
                is_pk: false,
                position: 4,
                always_generated: false,
                domain_type: None,
            },
        );

        Table {
            schema: "public".into(),
            name: "users".into(),
            description: Some("User accounts".into()),
            is_view: false,
            insertable: true,
            updatable: true,
            deletable: true,
            pk_cols: vec!["id".into()],
            unique_constraints: Vec::new(),
            columns,
            computed_columns: Default::default(),
            is_partitioned: false,
        }
    }

    #[test]
    fn test_table_to_graphql_object_name() {
        let table = create_test_table();
        let obj = TableObjectType::from_table(&table);

        assert_eq!(obj.name(), "users"); // named exactly like the table
    }

    #[test]
    fn test_table_to_graphql_object_description() {
        let table = create_test_table();
        let obj = TableObjectType::from_table(&table);

        assert_eq!(obj.description(), Some("User accounts"));
    }

    #[test]
    fn test_table_to_graphql_object_fields() {
        let table = create_test_table();
        let obj = TableObjectType::from_table(&table);
        let fields = obj.fields();

        assert_eq!(fields.len(), 4);
        assert!(obj.has_field("id"));
        assert!(obj.has_field("name"));
        assert!(obj.has_field("email"));
        assert!(obj.has_field("metadata"));
    }

    #[test]
    fn test_field_types() {
        let table = create_test_table();
        let obj = TableObjectType::from_table(&table);

        let id_field = obj.get_field("id").unwrap();
        assert_eq!(id_field.graphql_type, GraphQLType::Int);

        let name_field = obj.get_field("name").unwrap();
        assert_eq!(name_field.graphql_type, GraphQLType::String);

        let metadata_field = obj.get_field("metadata").unwrap();
        assert_eq!(metadata_field.graphql_type, GraphQLType::Json);
    }

    #[test]
    fn metadata_can_expose_a_database_column_as_graphql_id() {
        let table = create_test_table();
        let names = crate::names::NameOverrides::parse(
            r#"{"tables": {"public.users": {"column_types": {"id": "ID"}}}}"#,
        )
        .unwrap();
        let obj = TableObjectType::from_table_named(&table, "users", &names);

        let id_field = obj.get_field("id").unwrap();
        assert_eq!(id_field.graphql_type, GraphQLType::Id);
        assert_eq!(id_field.type_string(), "ID!");
        assert_eq!(obj.table.get_column("id").unwrap().nominal_type, "int4");
    }

    #[test]
    fn test_field_nullability() {
        let table = create_test_table();
        let obj = TableObjectType::from_table(&table);

        let id_field = obj.get_field("id").unwrap();
        assert!(!id_field.nullable); // PK is never nullable

        let name_field = obj.get_field("name").unwrap();
        assert!(!name_field.nullable); // Not nullable in DB

        let email_field = obj.get_field("email").unwrap();
        assert!(email_field.nullable); // Nullable in DB
    }

    #[test]
    fn test_field_descriptions() {
        let table = create_test_table();
        let obj = TableObjectType::from_table(&table);

        let id_field = obj.get_field("id").unwrap();
        assert_eq!(id_field.description, Some("Primary key".into()));

        let email_field = obj.get_field("email").unwrap();
        assert_eq!(email_field.description, None);
    }

    #[test]
    fn test_field_type_string() {
        let table = create_test_table();
        let obj = TableObjectType::from_table(&table);

        let id_field = obj.get_field("id").unwrap();
        assert_eq!(id_field.type_string(), "Int!"); // Non-null

        let email_field = obj.get_field("email").unwrap();
        assert_eq!(email_field.type_string(), "String"); // Nullable
    }

    #[test]
    fn test_pk_fields() {
        let table = create_test_table();
        let obj = TableObjectType::from_table(&table);

        let pk_fields = obj.pk_fields();
        assert_eq!(pk_fields.len(), 1);
        assert_eq!(pk_fields[0].name, "id");
    }

    #[test]
    fn test_table_with_underscore_name() {
        let mut table = create_test_table();
        table.name = "user_accounts".into();

        let obj = TableObjectType::from_table(&table);
        assert_eq!(obj.name(), "user_accounts");
    }
}