Prisma 2 unable to fetch DateTime column with null value - prisma2

await this.prisma.fee_collections.findMany({
where: whereClauseWithTransactionDateCondition,
include: {
student_master: {
select: {
fee_start_month: true,
}
}
}
});
In my DB, fee_start_month column schema :
fee_start_month DateTime? #db.Date
At the fee_start_month column, some of the values are null so prisma2 unable to fetch those records, and It's thrown an exception.
Generated Error :
[Nest] 21275 - 15/03/2021, 13:09:21 [ExceptionsHandler]
Invalid prisma.fee_collections.findMany() invocation:
Value out of range for the type. The column fee_start_month contained an invalid DateTime value with either day or month set to zero. +3337ms

Related

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.

Invalid Date Format - Flutter/Dart

It might be a simple solution but I have some problems with it. I have JSON response with user data like name, address, and birthday. However, birthDay is empty and I cannot parse it.
Error (only those lines occure):
Exception has occurred.
FormatException (FormatException: Invalid date format
)
I'm using tryParse and DateFormatter with null check but it seems to not work as I expect. Below you'll find part of code and JSON response:
Part of response:
birthDay: "" // as you see it's empty
bioInfo: ""
badges: List(6 items)
agreement5: false
Part of Profile Entity:
class ProfileEntity {
final String birthDay;
ProfileEntity.fromJson(Map<String, dynamic> json)
: birthDay = json['birthDay'],
}
Part of Profile Model:
class ProfileModel {
final DateTime birthDate;
ProfileModel({#required this.birthDate});
ProfileModel.fromEntities(
ProfileEntity profileEntity,
) : birthDate = DateTime.tryParse(profileEntity.birthDay), //place where I'm getting an error - value is null in this case.
//here I'm sending it to form field
Map<String, String> toFormFields() {
return {
'jform[birthDay]':
birthDate != null ? DateFormat("yyyy-MM-dd").format(birthDate) : "", //null check
}
}
}
Do you have any idea how to get rid of this? (Error message do not provide any info despite what I paste above in error part)
DateTime.tryParse does not expect null value.
You can replace this with DateTime.tryParse(profileEntity.birthDay ?? '') which will return null instead of throwing exception.
For ref: tryParse method
DateFormat('dd-MM-yyyy').parse(widget.initialDate);
remember you can change date format according to which you api sends date in my case 'dd-MM-yyy' in your case may be different format.

SpringBoot-Single value to multiple parameter using PostgreSQL

PostgreSQL Query
select date,count(*) from table1
where (DATE_PART('day', current_date::timestamp - table1.date::timestamp ))
<(SELECT value from keyvaluepair where priority='Important')
and priority = 'Important' group by date
order by date
I will be calling from api where
http://localhost:8080/get/getDates?priority=Important
I will be passing as ? in both places as shown
select date,count(*) from table1
where (DATE_PART('day', current_date::timestamp - table1.date::timestamp))
<(SELECT value from keyvaluepair where priority=?)
and priority = ? group by date
order by date
I'm getting error like this
No value specified for parameter 2.; nested exception is org.postgresql.util.PSQLException: No value specified for parameter 2.
org.springframework.dao.DataIntegrityViolationException: PreparedStatementCallback;
In java I'm just getting this query data date and count.
public Map<String,Object> getDates(String priority) {
Map<String,Object> map = new Map<String,Object>();
List<Object> count = new ArrayList<Object>();
List<Object> date = new ArrayList<Object>();
try {
jdbcTemplate.query(query, new Object[] { priority }, new RowMapper<Object>() {
#Override
public Object mapRow(ResultSet rs, int rowNum) throws SQLException {
date.add(rs.getString("date"));
count.add(rs.getInt("count"));
return null;
}
});
} catch (DataAccessException e) {
e.printStackTrace();
}
return map;
}
How to give priority once and use it twice in query?
select t1.date,count(*) from table1 t1
where (DATE_PART('day', current_date::timestamp - t1.date::timestamp ))
<(SELECT value from keyvaluepair k where k.priority=t1.priority)
and t1.priority = 'Important' group by t1.date
order by t1.date
This changes in query helped me in resolving error which I had as shown
No value specified for parameter 2.; nested exception is org.postgresql.util.PSQLException: No value specified for parameter 2.
org.springframework.dao.DataIntegrityViolationException: PreparedStatementCallback;
where two column names of table are same and I have to pass value once for all parameters as in link show below
http://localhost:8080/get/getDates?priority=Important
select t1.date,count(*) from table1 t1
where (DATE_PART('day', current_date::timestamp - t1.date::timestamp ))
<(SELECT value from keyvaluepair k where k.priority=t1.priority)
and t1.priority = ? group by t1.date
order by t1.date
here in this link single value that is priority Important is taken to query where it is used for both tables parameter of same column name.

How to add not null constraint in seqeulize if records with null already exist?

I had a table.
I added a new column.
Even though I had set default value in sequelize model, those columns still ended up empty.
So I get error Unhandled rejection SequelizeDatabaseError: column "col_name" contains null values
How do you populate new column with default values upon creation so not null constraint is not broken.
You can update the values first:
update t
set col_name = ?
where col_name is null;
Then add the not null constraint.
Even though I had set default value in sequelize model
I suspect there is a discrepancy between the migration and model. To insert the column with a migration containing a default value use defaultValue in your migration.
The following is a working example:
module.exports = {
up: (queryInterface, Sequelize) => {
return queryInterface.addColumn('tests', 'new_column', {
defaultValue: 'test',
type: Sequelize.STRING
})
}
}
Before running sequelize db:migrate
After sequelize db:migrate:
The documentation for the options object in addColumn is hard to find, it's listed for a different method

Apollo/GraphQL: Field Type to Use for Timestamp?

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
});