PostgreSQL outputs different TimeStamp format than Javascript TimeStamp format - javascript

I'm having trouble binding the results from SQL to my Model in Javascript /Typescript.
In my model, I have a property of created_at with types of Date.
When I use JSON functions in the Postgres SQL statement to avoid duplicate parent rows for a relationship, I will get a different format for the timestamp.
Here is a simple example
SELECT
a.*,
(
SELECT
ROW_TO_JSON(profile)
FROM
(
SELECT
*
FROM
profile p
WHERE
p.account_id = a.id
)
profile
)
AS profile
FROM
account a
WHERE
a.id = 16
And here are the results in JSON
{
"id":16,
"email":"test#gmail.com",
"password":"$password",
"role_id":0,
"created_at":"2020-04-01T22:03:44.324Z",
"profile":{
"id":8,
"username":"firmanjml",
"gender":0,
"bio":null,
"avatar":"www.firmanjml.me/test.jpg",
"account_id":16,
"created_at":"2020-04-02T06:03:44.32498"
}
}
I noticed that the parent row which is from the account table has the Z at the end of created_at whereas the child table that is converted to JSON has a different timestamp format.
Is there a way that I could make all the timestamp be in Javascript format?
Query to create schema and insert data
CREATE TABLE "account"(
id SERIAL primary key,
email varchar(50) not null,
password varchar(50) not null,
role_id int2 default 0 not null,
created_at timestamp default now() not null
);
CREATE TABLE "profile"(
id SERIAL primary key,
username varchar(50) not null,
gender int2 not null,
bio varchar(50),
avatar varchar(50),
account_id integer not null REFERENCES account (id),
created_at timestamp default now() not null
);
INSERT INTO "account" (email,"password","role_id",created_at) VALUES
('test#gmail.com','$password',0,'2020-04-02 06:03:44.324');
INSERT INTO "profile" (username,gender,bio,avatar,account_id,created_at) VALUES
('fimrnajml',0,NULL,'www.firmanjml.me/test.jpg',1,'2020-04-02 06:03:44.324');

Use the TO_CHAR() function to format the timestamp in your SQL, like https://www.postgresqltutorial.com/postgresql-to_char/
A format of 'YYYY-MM-DD"T"HH24:MI:SS.US"Z"' should do it. This assumes all your timestamps are in UTC (the way the pros do it :-)
Your SQL then looks like:
SELECT
a.*,
(
SELECT
ROW_TO_JSON(profile)
FROM
(
SELECT
username,gender,bio,avatar,account_id,to_char(created_at, 'YYYY-MM-DD"T"HH24:MI:SS.US"Z"') created_at
FROM
profile p
WHERE
p.account_id = a.id
)
profile
)
AS profile
FROM
account a
WHERE
a.id = 16
try it here

Related

Why is TIMESTAMP column always zero after updating using Node JS?

query("CREATE TABLE IF NOT EXISTS `discount_codes` (`discount_code` VARCHAR(50), `expirationDate` TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, `claimedBy` VARCHAR(15), `type` TEXT)")
exports.claimDiscount = function(code, user) {
var queryString = "UPDATE discount_codes SET expirationDate=NOW(), claimedBy = ? WHERE discount_code = ?"
try{
query(queryString, [user, code])
} catch(err){
console.log(err)
}
}
The column is always 0000-00-00 00:00:00, both on insert query and update query, the other column is updated correctly. I have no idea what I am doing wrong, punching my head in wall for hours because of this. Any help is really appreciated
I think you are missing some parentheses.
Use TIMESTAMP DEFAULT CURRENT_TIMESTAMP() ON UPDATE CURRENT_TIMESTAMP() instead of TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP

How to pass Parameter to Snowflake procedure using JavaScript

I am trying to write a snowflake procedure but I am getting an "invalid identified A"
following is the statement:
create or replace procedure sp_procedureName (A date, B string)
return string Null
language Javascript
EXECUTE As Caller
AS
$$
with cte as (Select column1, column2 from table1 where colA >= A and colB = B),
cte1 as (Select column1, column2 from table2 where colA >= A and colB = B)
Select column1, column2, column1, column2 from cte1, cte2 //Example select statement
so when I am passing those paramteres my procedure is failing with "invalid identified error"
can someone help me to get the correct way to pass those parameter values to procedure
Here's how to get started. You can reference the Snowflake Stored Procedure API: https://docs.snowflake.com/en/sql-reference/stored-procedures-api.html
Note that the date must be passed using the .toISOString() function because Javascript stringifies Date types into a string that Snowflake does not like. Snowflake is okay with the ISO string version.
create or replace procedure sp_procedureName (A date, B string)
returns string
language javascript
execute As caller
AS
$$
var sql = `with cte as (Select column1, column2 from table1 where colA >= :1 and colB = :2),
cte1 as (Select column1, column2 from table2 where colA >= :1 and colB = :2)
Select column1, column2, column1, column2 from cte1, cte2 //Example select statement`;
var rs = snowflake.execute({sqlText: sql, binds:[A.toISOString(), B]});
while (rs.next()){
// Do something for each row here.
}
$$;
call sp_procedureName('2020-01-01', 'Hello world');

How to SELECT from multiple tables in MySQL?

I have a lot of tables with the same _ips endings. Example:
first-domain.com_ips
secons-domain.com_ips
...
I'm trying to get UNION result table which will contains all rows from all _ips tables. For this I use:
SELECT id, expirationDate FROM `first-domain.com_ips` WHERE isBlocked = 1
UNION
SELECT id, expirationDate FROM `secons-domain.com_ips` WHERE isBlocked = 1
...;
I have an array which consists of domain names. So I'm looking for a way to use this domain array in SQL query. Maybe something like we use with SELECT. Example:
const ids = [3, 4, 6, 8];
const query = 'SELECT * FROM table WHERE id IN (' + ids.join() + ')';
Is there a way to use array for tables names in SQL? Thank you in advance!
You can do this by using dynamic queries and regexps:
This dynamic query does what you want :
SELECT
GROUP_CONCAT(
CONCAT(
'SELECT * FROM `',
TABLE_NAME,
'`') SEPARATOR ' UNION ALL ')
FROM
`INFORMATION_SCHEMA`.`TABLES`
WHERE
`TABLE_NAME` REGEXP '_ips$'
INTO #sql;
SELECT #sql;
PREPARE stmt FROM #sql;
EXECUTE stmt;
This query gives two outputs, first is the final SQL query string which looks like :
SELECT * FROM `first-domain.com_ips` UNION ALL SELECT * FROM `second-domain.com_ips`
and the other output is the actual data from all tables, if you want only the final data, you can remove this statement:
SELECT #sql;

Angular ng-repeat list value spliting

I'm storing below data in localstorage and i wanted to retrieve these values in html page for search history(assume search history is an list).
hotelSearchCriteria = {
destination : location,
datesInfo:{
checkInDate : '2017/05/22',
checkOutDate: '2017/05/30'
}
}
localStorage.setItem("hotelSearchCriteria", JSON.stringify(hotelSearchCriteria));
var storedInfoArray = JSON.parse(localStorage.getItem('hotelSearchCriteria'));
if(storedInfoArray != null){
$scope.storedInfoArrayAngular = storedInfoArray;
}
I want to retrieve these value using ng-repeat and i need to split checkInDate and checkOutDate as follows "05/22 (Mon) - 05/30 (Tue)"
I can able store data in localStorage successfully as a list but i'm facing issue in retrieving these list of values. How can i split dates in ng-repeat ?
<li ng-repeat="storedInfo in storedInfoArrayAngular">
<p>{{storedInfo.destination}}</p>
<span>{{storedInfo.checkInDate}}</span> - <span>{{storedInfo.checkOutDate}}</span>
</li>
Expected result
Search History
Singapore
05/22 (Mon) - 05/30 (Tue)
Tokyo
05/22 (Mon) - 05/30 (Tue)
Anybody can help me out ? Thanks in advance
It looks like checkInDate and checkOutDate are properties of the storedInfo.datesInfo, so you should use the full object path when referring to it:
<li ng-repeat="storedInfo in storedInfoArrayAngular">
<p>{{storedInfo.destination}}</p>
<span>{{storedInfo.datesInfo.checkInDate}}</span> - <span>{{storedInfo.datesInfo.checkOutDate}}</span>
</li>
And to format your dates as 05/22 (Mon) you can use the date filter as follows:
{{ storedInfo.datesInfo.checkInDate | date: "MM/dd (EEE)" }}

column is of type timestamp without time zone but expression is of type integer

I get error message like below , when I create this table just like others set column timestamp timestamp without time zone NOT NULL , but when I tried to insert 2015-08-16 18:51:05 to this table, then I get error, but other table is work, why and how to solve it?
CREATE TABLE IF NOT EXISTS "UserForgetPasswordPending"(
"UserForgetPasswordPendingId" SERIAL NOT NULL,
"Email" varchar(50) NOT NULL,
"TokenTimestamp" timestamp without time zone NOT NULL,
"Token" varchar(100) NOT NULL,
PRIMARY KEY ("UserForgetPasswordPendingId")
);
ALTER TABLE "UserForgetPasswordPending"
OWNER TO db_admin;
error
[error: column "TokenTimestamp" is of type timestamp without time zone but expression is of type integer]
name: 'error',
length: 216,
severity: 'ERROR',
code: '42804',
detail: undefined,
hint: 'You will need to rewrite or cast the expression.',
insert
var utc = moment(new Date()).unix();
var tokenTimestamp = moment.unix(utc).format('YYYY-MM-DD HH:mm:ss');
var upsertUserForgetPasswordPending = function(userEmail, tokenTimestamp, token) {
return new Promise(function (fulfill, reject){
var queryInsert = 'INSERT INTO "UserForgetPasswordPending" ("Email","TokenTimestamp","Token") SELECT $1,2,$3';
var queryUpsert = 'UPDATE "UserForgetPasswordPending" SET "TokenTimestamp" = $2, "Token" = $3 WHERE "Email" = $1';
var query = 'WITH upsert AS ('+queryUpsert+' RETURNING *) '+queryInsert+' WHERE NOT EXISTS (SELECT * FROM upsert)';
console.log(tokenTimestamp);
dbClient.query(query, [userEmail,tokenTimestamp,token], function(error, result) {
if (error) {
reject(error);
} else {
fulfill(result);
}
});
});
};
This because you are inserting integer data to time stamp column.
Correct the following syntax:
var queryInsert = 'INSERT INTO "UserForgetPasswordPending ("Email","TokenTimestamp","Token") SELECT $1,2,$3';
In above query you are selecting 2 for TokenTimestamp that's why you are getting this error.
you should replace 2 with some date time format yyyy-mm-dd hh:mm:ss .
For example: '2015-08-07 05:00:01'
For me casting the type explicitely worked.
Please note, I used joda Datetime
#CreatedDate
#Column(name = "created_on", updatable = false, nullable = false)
#Type(type = "org.jadira.usertype.dateandtime.joda.PersistentDateTime")
private DateTime createdOn;

Categories

Resources