Apollo/GraphQL: Field Type to Use for Timestamp? - postgresql

I'm storing a value to a postgres field that is of type timestamp with time zone. I was defining the field as an int in my Apollo schema, but I'm getting this error message in the resolver:
column "apptDateTime" is of type timestamp with time zone but expression is of type integer
Looking up GraphQL data types, I don't yet see any type that is cited as corresponding to a field of type timestamp.
What's the correct field type to use in the Apollo schema for a field that is of type timestamp in the database?

I find this way to work with input in forms, needed convert from client (input form) to the server, and from the server to client (input form)
Graphql:
updatedAt: String
Sequelize:
updatedAt: { type: Sequelize.DATE },
Postgresql:
"createdAt" timestamp(6) with time zone DEFAULT now(),
Value transform to the Server:
value = dateToISO(value);
Value transform to the Client:
if ( isNil(value) ) {
value = '';
} else {
value = value.toLocaleDateString() +' '+ value.toLocaleTimeString();
}
the helpers:
let dateToISO = function (dateString) {
if (!dateString) {
return null;
}
let p = dateString.split(/\D/g);
/* It's up your date on input in this case come from DD-MM-YYYY
for MM-DD-YYY use: return [p[1], p[2], p[0]].join('-'); */
return [p[2], p[1], p[0]].join('-');
};

I got my mutation working that includes a field of type Timestamp with Time Zone. I did it by changing the schema for my apptDateTime field from Int to String, and passing in an ISO string. Sequelize and Postgres took care of changing it into a field of type Timestamp with Time Zone.
Update 2021:
Here's what I'm using these days.
Sequelize:
timeOfNonce: {type: Sequelize.DATE}
Schema:
scalar DATETIME
.....
timeOfNonce: DATETIME
These days I let Sequelize define my SQL tables via:
const deleteAllData_fromThisModel = false;
const alterThisTableToMatchDBConnectorsModel = true;
myDataModel.sync({force: deleteAllData_fromThisModel,
alter: alterThisTableToMatchDBConnectorsModel}).then(err => {
console.log('myDataModel has been synced')
}).catch(err => {
throw err
});

Related

How to add a date to a prisma typescript form?

I am trying to figure out how to post a date to a prisma database.
I have a prisma.schema which has a createdAt field as follows:
createdAt DateTime #default(now()) #db.Timestamptz(6)
I made a model with a date field in it as follows:
#Field()
createdAt: Date;
And a create.input.ts with a similar field:
#IsNotEmpty()
#Field()
createdAt: Date;
then, in the form, I'm trying to add the createdAt date as the date the form is submitted, as follows:
return form.handler(() => createIssueGroup({ variables: { data: { ...data, createdAt: Date.now() } } })),
However, I get an error that says type number is not assignable to type string. I don't think I'm using a string in any of the date fields.
How can I post a date to prisma?
From your schema definition,
createdAt DateTime #default(now()) #db.Timestamptz(6)
The date will be automatically generated due to the now() method you specified in #default(). You don't need to pass a date to the database as that will be handled for you by Prisma. See the docs for more information on using now() and defining a default value.

Save Date.now() to timestamp column but get date/time field value out of range

My project (NestJS with TypeScript) is using TypeOrm on PostgreSQL database.
My table has a column (in migration file):
new TableColumn({
name: 'managed_at',
type: 'timestamp',
isNullable: true,
}),
Associated field in entity class:
#Column({ type: 'timestamp', nullable: true })
managedAt: Date | null;
I would like the column managed_at holds value of date and time.
If I save a data to the table with:
import { Repository } from 'typeorm';
...
// repo is the Repository of typeorm
repo.update(
{ managedAt: Date.now() }
);
I get error:
QueryFailedError: date/time field value out of range: "1651495656811"
How to solve this problem that using Date.now() and hold value of data and time?
import { Repository } from 'typeorm';
...
// repo is the Repository of typeorm
repo.update(
{ managedAt: new Date() }
);
Change Date.now() -> new Date().
You need to save Date type data to column in timestamp type.
Btw, you can add this in your entity class.
It will update column before update data.
#BeforeUpdate()
updateManagedAt(): void {
this.managedAt = new Date();
}
The static Date.now() method returns the number of milliseconds elapsed since January 1, 1970 00:00:00 UTC, as per documentation here Date.now().
Whereas valid input for the time stamp types consists of the concatenation of a date and a time, followed by an optional time zone (if you are using timestamptz type instead of timestamp type), followed by an optional AD or BC. (Alternatively, AD/BC can appear before the time zone, but this is not the preferred ordering.
You can read more about Date/Time types in pgSQL here.
In your case, you can do it like this
repo.update({ managedAt: (new Date()).toISOString() });
You'd use toISOString for sharing a date with another machine or process.

Using the Dart/Flutter Postgres Package to store dates and null dates needs two separate commands

I am using the Postgres Package (On the pub.dev site) to UPDATE records in a very simple database. It has two fields: a Text field prime key named number, and a Date field named date_of_birth.
If the date_of_birth is a valid DateTime string then all is well (as can be seen from the code below). But if date_of_birth is unknown (so I set to null) the UPDATE fails:
import 'package:postgres/postgres.dart';
void main() async {
final conn = PostgreSQLConnection(
'localhost',
XXXXX,
'XXXXX',
username: 'XXXXX',
password: 'XXXXX',
);
await conn.open();
DateTime dob = DateTime.now();
var results;
results = await conn.query('''
UPDATE account_details
SET date_of_birth = '$dob'
WHERE number = '123123'
''');
await conn.close();
}
If I set:
dob = null;
The program fails with the error:
Unhandled exception:
PostgreSQLSeverity.error 22007: invalid input syntax for type date: "null"
So I need to include a check on the dob field and the program now looks like this:
DateTime dob = DateTime.now();
dob = null;
var results;
if (dob == null) {
results = await conn.query('''
UPDATE account_details
SET date_of_birth = null
WHERE number = '123123'
''');
} else {
results = await conn.query('''
UPDATE account_details
SET date_of_birth = '$dob'
WHERE number = '123123'
''');
}
That works fine for my simple database, but in my real App. I have a number of date fields in one table. So I have to do a check for each possible combination of those date values - writing a code block for each!
Can anyone tell me how I can UPDATE both null and a valid date using a single statement please?
You are quoting the query parameters yourself. NEVER do this. In addition to the sort of problem you have just seen it also leaves you open to a trivial SQL injection attack.
The library you are using will have some way of putting placeholders into the query text and passing variables when executing the query. Use that.

Prevent Json.NET from interpreting a string as a date

I have some attributes returned from a rest service that are served as an array of name-value pairs.
In some cases the value is a date expressed in universal sortable format:
{
"name": "Modification-Date",
"value": "2017-11-13T15:15:13.968Z"
}
When it gets parsed by the deserialiser, the value is identified as a date but given that the object the pair is deserialised into has type string for both name and value, the date is then converted to string and it loses precision: "13/11/2017 15:15:13"
This is easily visible by using a converter for the NameValue type.
if (reader.TokenType == JsonToken.StartObject)
{
var item = JObject.Load(reader);
return new NameValueFacet()
{
Name = item["name"].Value<string>(),
Value = item["value"].Value<string>()
};
}
item["value"].Type shows the type is Date.
How do I get to have Json.NET leave it as a string, "unparsed"?
You can try with Newtonsoft. See below.
JsonConvert.DeserializeObject<your_object>(your_json, new IsoDateTimeConverter{ DateTimeFormat = "dd/MM/yyy" });

Mirth Connect SQL Server Error : Conversion failed when converting date and/or time from character string

I am trying to insert into SQL Server DateTime field. Trying simple scenario of one table having datetime column named start_date only.
Query I am trying is
INSERT INTO test (start_date) values (${start_date})
start_date is channelMap variable of Type java.util.Date , It was created using :
var start_date = DateUtil.getDate('yyyyMMddHHmmss', msg['date'].toString());
Here start_date is of java.util.Date, why mirth treats it as String when it tries to insert into database ??
You can handle the conversion even in SQL. Hope it helps
var start_date = msg['PID']['PID.7']['PID.7.1'].toString(); // 19831123 - YYYYMMDD format
try {
sql="INSERT INTO test (start_date) values (convert(datetime,'" + start_date + "',5))";
logger.info(sql);
rst = dbConn.executeUpdate(sql);
}
catch(err) {
logger.info('ERR: ' + err);
}
Out in DB will be below.
select * from test
start_date |
----------
1983-11-23 00:00:00.000
2nd Approach
If you still want to use util try below
var start_date = msg['PID']['PID.7']['PID.7.1'].toString(); // 19831123 - YYYYMMDD format
/*
Input is yyyyMMdd and
output is yyyyMMddHHmmss format
*/
var datestring = DateUtil.convertDate('yyyyMMdd', 'yyyyMMddHHmmss', start_date);
try {
sql="INSERT INTO test (start_date) values ('" + start_date + "')";
logger.info(sql);
rst = dbConn.executeUpdate(sql);
}
catch(err) {
logger.info('ERR: ' + err);
}
I believe your data is inserting in DB as 'Mon Feb 19 09:25:16 IST 1968' along with quotes.
I used formatDate function, but data inserted into DB will be like 1968-02-19 09:25:16
var pidDate = msg['PID']['PID.7']['PID.7.1'].toString();
var value = DateUtil.getDate("yyyyMMddHHmmss",pidDate);
var data = DateUtil.formatDate("yyyyMMddHHmmss", value)
channelMap.put("start_date",data);
Inserting to DB:
var dateValue = $('start_date')
dbConn = DatabaseConnectionFactory.createDatabaseConnection(dbDriver, dbAddress, userName,passwd);
result = dbConn.executeUpdate("INSERT INTO test (startdate) values ('"+dateValue+"')");
I'm sending date value as 19680219092516,inside DB value is 1968-02-19 09:25:16.Datatype of my DB is DateTime type.
the getDate function returns a java.util.Date object, but when I tried with getCurrentDate function, it returns a formatted String. I guess formatting the date object is one way of inserting data into DB.