stop further date conversion which is already in UTC - postgresql

By default any date/timestamp stored in postgres is in standard UTC. Postgres has the DATE column type that stores only the date part of a full timestamp.
When using typeorm for postgres, and using the repositories the date is fetched as is. Yet, when you do something with a raw query like this:
const queryRunner = await this.connection.createQueryRunner();
await queryRunner.connect()
const response = await queryRunner.query('SELECT * FROM MY_VIEW WHERE AGE=23');
For the same date(only) column I receive something like this, which has its value as '1999-01-02'
{
name: 'mleko',
age : '23',
dob : '1999-01-01:T22:00:00:000Z',
address: 'xyz'
}
I'm not sure where exactly is this conversion taking place, probably the underlying driver that typeorm uses, yet, how do I tell typeorm to not do this conversion for a date already in UTC into again a UTC.

So, the way I got around this was doing a cast on the raw query:
const queryRunner = await this.connection.createQueryRunner();
await queryRunner.connect()
const response = await queryRunner.query('SELECT name, age, dob::VARCHAR, address FROM MY_VIEW WHERE AGE=23');
this would avoid any conversions

Related

Why passing firestore timestamp to ``moment`` gives the output as invalid date?

In my project, I am using moment.js. When I pass firestore timestamp to moment it throws the output as invalid date.
Here is my code:
moment({seconds: 1663679594, nanoseconds: 42000000}).format('MM-DD-YYYY')
Please guide me on how to resolve this error.
Firestore stores Dates as a Timestamp object. This is not the same as a Javascript Date() object. You have to convert it first into a Javascript Date object using the .toDate() method that Firestore has provided. See Sample code below:
var db = firebase.firestore();
db
.collection('collection-name')
.doc('document-id')
.get()
.then((doc) => {
const converted = doc.data().timestamp.toDate();
const momentDate = moment(converted).format('MM-DD-YYYY')
console.log(momentDate);
})
For more information, you may check out this documentation.

Prisma: Finding items where two fields have the same value

I would like to find items in a Prisma db where the values for two columns are the same. The use case is to compare the 'created_at' and 'updated_at' fields to find items that have never been updated after their initial creation. In raw SQL I would do something like:
select updated_at,
cast(sign(sum(case when updated_at = created_at then
1
else
0
end)) as int) as never_modified
from tab
group by updated_at
Is it possible to achieve this in Prisma?
You would need to use Raw Queries to compare time values from the same table.
Here's an example of how you could achieve this, assuming a PostgreSQL database for the following query.
import { PrismaClient } from '#prisma/client'
const prisma = new PrismaClient()
async function initiateDatesComparisonRawQuery() {
const response =
await prisma.$queryRaw`SELECT * FROM "public"."Project" WHERE "created_at" = "updated_at";`;
console.log(response);
}
await initiateDatesComparisonRawQuery();
you can use the preview feature fieldReference of prisma.
schema.prisma
generator client {
provider = "prisma-client-js"
previewFeatures = ["fieldReference"]
}
your code
prisma.project.findMany({
where: { created_at: prisma.project.fields.updated_at }
})

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.

I am unable to extract numeric fields from a PostgreSQL database using Dart and the Postgres package

I have a simple, single row, PostgreSQL database table that includes a numeric(8,2) field, set to 120.00, and a character field set to 'N'.
This is a Windows 10 setup.
When I run the following Dart program the result is unexpected:
import 'package:postgres/postgres.dart';
void main() async {
print('Attaching to DB...');
final conn = PostgreSQLConnection(
'localhost',
5432,
'pdpdb',
username: 'XXXXXXX',
password: 'XXXXXXX',
);
await conn.open();
print('Connected to DB');
var results = await conn.query('''
SELECT verification, balance FROM contacts
''');
print(results);
await conn.close();
}
My result is this:
Attaching to DB...
Connected to DB
[[N, ╔ ╗ 2]]
So the 'N' is clear, but the numeric field is gibberish!
Why am I not seeing 120.00 as I do when I run the same command using pgAdmin's query tool:
I have tried to parse the field as if it were a double, but that gives me:
Unhandled exception:
FormatException: Invalid double
I am sure this must be something obvious so any hints will be gratefully received. Thank you.
If I write a similar process using toMaps():
final results = await conn.query('''
SELECT verification, balance FROM contacts
''').toMaps();
print(results);
I get the output:
[{verification: N, balance:
Suggesting that something has broken the output.
This isn't really an answer - more of a work around:
It seems that the Postgres package doesn't support NUMERIC fields as Dart doesn't have an equivalent type.
This workaround:
github issue
suggests the use of CASTing the numeric field to a float within the SELECT statement.
I've tried it and it does work. Granted it is not ideal, but as it works that helps me out a lot at the moment.

Save a birthDate via qraphql in postgres

I would like to save a birthdate from an (react) input (type = 'date'), send it via GraphQL to node backend and persist it in postgres in a date format.
Input in HTML: 09.07.2000
In GraphQL resolver: 2000-07-09T00:00:00.000Z
Date format in Postgres (original output in console): 09.07.2000
Well, that's what i expected. But now, if i request the same field:
Date format in Postgres (original output in console): 09.07.2000
Graphql response: 08.07.2000
HTML Input: 08.07.2000
If I change the scalar in graphQl schema to String, the following string returns: Fri Jul 09 2000 00:00:00 GMT+0200 (CEST)
Code
schema
scalar Date
type Child {
...
birthDate: Date
...
}
resolvers
const { GraphQLDate } = require('graphql-iso-date')
...
Date: GraphQLDate,
Problem
It looks like there is a problem in converting the date format from different timezones. If there is no timezone the scalar resolver guess a timezone. But this is a birthdate, it hast to be the same date on every timezone. How can I fix this? Do I have to use a string instead of date in prostgres?
Thanks for any support 🙏 I'm really lost
UPDATE
It looks like knex.js is the problem.
A normal SQL query responds the expected date. But a query with knex.js response a datetime.