0

I want to create a mutation query which inserts current time by default if no value is passed for that argument.

Schema:

CREATE TABLE A (
  id INT PRIMARY KEY,
  a_time TIME DEFAULT NOW() 
);

The following isn't valid as a GraphQl mutation query (since graphQl doesn't support Time as a datatype), but it shows what I'm attempting:

type Mutation {
    insertInA(id: Int!, a_time: Time! = NOW())
}

schema {
    mutation: Mutation
}

How can I achieve the above functionality?

outis
  • 75,655
  • 22
  • 151
  • 221
Abhishek
  • 29
  • 4
  • Is there a reason why the column is a `Time`, rather than a `DateTime`? Are you specifically looking for a solution in GraphQL terms, or in terms of the whole system (including the C# host language and DB backend)? – outis Apr 22 '22 at 01:30

1 Answers1

0

Computed Default

In the current version of the GraphQL schema spec, default input values must be constants or variable names; no expressions are supported. Thus this can't be handled in GraphQL, which leaves the host language and the DB backend, either of which can handle it easily.

Whichever is used, the field argument in GraphQL should be made nullable, with a default value of null. Additionally, the ID is a synthetic key and should be left to the DBMS to generate, so should be left out of the query field.

scalar Time

type Mutation {
    insertInA(a_time: Time = null)
}

Note that for more complex models, the argument should be an object input type, rather than a scalar.

The insertInA resolver should check for null and then either set it itself (getting the current time using DateTime.UtcNow):

A insertInA(TimeOnly? a_time = null) {
    a_time ??= TimeOnly.FromDateTime(DateTime.UtcNow);
    A newA = new A { a_time = a_time };
    // …
}

or leave it to the DBMS:

A insertInA(TimeOnly? a_time = null) {
    A newA = new A { a_time = a_time };
    // …
}

If not using some ORM, your code may need to choose among different SQL statements, depending on whether or not a_time is null.

Time type

Though GraphQL doesn't have native date/time types, custom scalars can easily be added (specifics are beyond the scope of this Q&A).

outis
  • 75,655
  • 22
  • 151
  • 221