default date value to store in a table in snowflake - date

I created below snowflake procedure and from that procedure I want to
insert default date value into a table. Below is the script.
create or replace procedure test_dt() returns string not null language
javascript //execute as owner
as
$$
try {
var c_dt=`select current_date()`;
snowflake.execute({sqlText:c_dt});
var sql_query = `insert into test_date values (:1)`;
var resultSet = snowflake.execute( {sqlText: sql_query, binds:c_dt});
}
catch(err) {
return err.message;
}
$$;
call test_dt();
while executing the procedure I am getting below error.
"Date 'select current_date()' is not recognized"
Please help me on this.

you are binding the "date" in the second query, to the input sql that "gets the current_date()" and not the actual result, thus it's the same as
insert into test_date values ('select current_date()');
so you ether want to save the result of the first query OR just use the current date aka CURRENT_DATE
insert into test_date values (CURRENT_DATE);
create or replace procedure test_dt() returns string not null language
javascript //execute as owner
as
$$
try {
var sql_query = `insert into test_date values (current_date)`;
var resultSet = snowflake.execute( {sqlText: sql_query});
}
catch(err) {
return err.message;
}
$$;```

Related

Create Postgres with knex.js trigger to update time after updating the table

I have a table with id, username, job, job_id, created_at, and updated_at columns. I used knex.js to create the table and I want the table to capture the time if there are any modifications on the table, for example, if the column job is updated from the frontend, the column updated_at should store the time at which the column was updated.
I am new to Postgres triggers, but I tried to implement this;
const FUNCTION_NAME = 'on_time_update';
CREATE OR REPLACE FUNCTION ${FUNCTION_NAME}()
RETURNS TRIGGER AS
$BODY$
BEGIN
NEW.updated_at = now();
RETURN NEW
END;
$BODY$ LANGUAGE PLPGSQL;
export async function up(knex: Knex): Promise<void> {
await knex.raw(createOnUpdateTrigger('jobs', FUNCTION_NAME));
}
export async function drop(knex: Knex): Promise<void> {
await knex.raw(dropTrigger('jobs', FUNCTION_NAME));
}
using knex, I created a trigger;
createOnUpdateTrigger: (name, table, procedure) => `
CREATE TRIGGER ${name}
BEFORE UPDATE on ${table}
FOR EACH ROW
EXECUTE PROCEDURE ${procedure}();
`
dropTrigger: (name, table) => `
DROP TRIGGER ${name} ON ${table};
`
by doing this, I am able to successfully create the migration, but my column is not being updated and I am not getting errors. I am not sure what am I doing wrong. Any help would be appreciated as I am new to this! Thanks!

Calling a function on insert with JDBC

I have the following function and table in my PostgreSQL database:
CREATE OR REPLACE FUNCTION generate_uid(size INT) RETURNS TEXT AS $$
DECLARE
characters TEXT := 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
bytes BYTEA := gen_random_bytes(size);
l INT := length(characters);
i INT := 0;
output TEXT := '';
BEGIN
WHILE i < size LOOP
output := output || substr(characters, get_byte(bytes, i) % l + 1, 1);
i := i + 1;
END LOOP;
RETURN output;
END;
$$ LANGUAGE plpgsql VOLATILE;
create table users
(
userid text primary key default generate_uid(50)
, username varchar (50) not null
, pass varchar (50) not null
, firstname varchar (100) not null
, lastname varchar (100) not null
, email varchar (150) not null
, roleid int not null
, constraint fkrole foreign key(roleid) references userrole(roleid)
);
Then I call on the function in my DAO in JDBC with this block of code:
Account A = new Account();
String sha256hex = Hashing.sha256()
.hashString(password, StandardCharsets.UTF_8)
.toString();
try (Connection conn = CustomClassFactory.getConnection()) {
String sql = "INSERT INTO users (username, pass, firstname, lastname, email, roleid) VALUES (?,?,?,?,?,?)";
PreparedStatement ps = conn.prepareStatement(sql);
ps.setString(1, userName);
ps.setString(2, sha256hex);
ps.setString(3, firstName);
ps.setString(4, lastName);
ps.setString(5, email);
ps.setInt(6, roleId);
System.out.println(ps.toString());
int i = ps.executeUpdate(); // <---update not query. this line is what sends the information to the DB
if (i == 0) {
System.out.println("Sorry, database was not updated. Returning to menu");
return null;
}
} catch (SQLException e) {
System.out.println("Sorry, database was not contacted. Bring your developer coffee. In the Insert Statement");
e.printStackTrace();
return null;
}
I am receiving the following error from the Stack Trace:
org.postgresql.util.PSQLException: ERROR: function gen_random_bytes(integer) does not exist
Hint: No function matches the given name and argument types. You might need to add explicit type casts.
Where: PL/pgSQL function generate_uid(integer) line 8 during statement block local variable initialization
at org.postgresql.core.v3.QueryExecutorImpl.receiveErrorResponse(QueryExecutorImpl.java:2552)
at org.postgresql.core.v3.QueryExecutorImpl.processResults(QueryExecutorImpl.java:2284)
at org.postgresql.core.v3.QueryExecutorImpl.execute(QueryExecutorImpl.java:322)
at org.postgresql.jdbc.PgStatement.executeInternal(PgStatement.java:481)
at org.postgresql.jdbc.PgStatement.execute(PgStatement.java:401)
at org.postgresql.jdbc.PgPreparedStatement.executeWithFlags(PgPreparedStatement.java:164)
at org.postgresql.jdbc.PgPreparedStatement.executeUpdate(PgPreparedStatement.java:130)
at dao.AccountDaoImp.CreateAccount(AccountDaoImp.java:35)
at testing.Tester.main(Tester.java:11)
Exception in thread "main" java.lang.NullPointerException: Cannot invoke "models.Account.toString()" because the return value of "dao.AccountDaoImp.CreateAccount(String, String, String, String, String, int)" is null
at testing.Tester.main(Tester.java:11)
How do I make sure it sees the function when I create a new user? The function is designed to generate a random string of text to use as a unique ID.
gen_random_bytes is part of the pgcrypto extension.
So run this in your database:
CREATE EXTENSION pgcrypto SCHEMA public;
To make sure you don't have to rely on search_path, you can prefix public to the function call, like in public.gen_random_uuid().

NpgSql and PostgreSQL 12.4 - Only getting the cursor name from data reader instead of the rows of data

I'm trying to pull back data from PostgreSQL using a data reader. Each time I run my code the only value returned is the name of the refcursor.
I created the following to illustrate my problem. I'm using NpgSql .net core 3.1 aginst a PostgreSQL 12.4 database. Can anyone point out what I'm doing wrong?
Here is a simple table of cities with a function that is supposed to return the list of cities stored in the tblcities table.
CREATE TABLE public.tblcities
(
cityname character varying(100) COLLATE pg_catalog."default" NOT NULL,
state character varying(2) COLLATE pg_catalog."default",
CONSTRAINT tblcities_pkey PRIMARY KEY (cityname)
);
INSERT INTO public.tblcities(cityname, state) VALUES ('San Francisco','CA');
INSERT INTO public.tblcities(cityname, state) VALUES ('San Diego','CA');
INSERT INTO public.tblcities(cityname, state) VALUES ('Los Angeles','CA');
CREATE OR REPLACE Function getcities() RETURNS REFCURSOR
LANGUAGE 'plpgsql'
AS $BODY$
DECLARE
ref refcursor := 'city_cursor';
BEGIN
OPEN ref FOR
select *
from tblcities;
Return ref;
END;
$BODY$;
The following is the .net code.
public static void GetCities()
{
using (var cn = new NpgsqlConnection(dbconn_string))
{
if (cn.State != ConnectionState.Open)
cn.Open();
using (NpgsqlCommand cmd = cn.CreateCommand())
{
cmd.CommandText = "getcities";
cmd.Connection = cn;
cmd.CommandType = CommandType.StoredProcedure;
NpgsqlDataReader dr = cmd.ExecuteReader();
while (dr.Read())
{
//There is only one row returned when there should be 3.
//The single value returned is the name of the refcursor - 'city_cursor'
//Where are the city rows I'm expecting?
var value1 = dr[0];
}
}
}
}
In PostgreSQL, rather than returning a refcursor, you generally return the data itself - change the function to have RETURNS TABLE instead of RETURNS REFCURSOR (see the docs for more details). If you return a cursor to the client, the client must then perform another roundtrip to fetch the results for that cursor, whereas when returning a table directly no additional round-trip is needed.
This is one of the main reasons Npgsql doesn't automatically "dereference" cursors - lots of people coming from other databases write functions returning cursors, when in reality doing that is very rarely necessary.
For some discussions around this, see https://github.com/npgsql/npgsql/issues/1785 and https://github.com/npgsql/npgsql/issues/438.

Error: cannot insert multiple commands into a prepared statement

I am trying to move a row from one table to another.
The problem is that if I put both queries together, I get "error: cannot insert multiple commands into a prepared statement". What can I do?
exports.deletePost = function(id) {
return db.query(`INSERT INTO deletedjobs
SELECT *
FROM jobs
WHERE id = $1;
DELETE FROM jobs WHERE id = $1;`, [id]).then(results => {
console.log("succesfull transfer");
return results.rows[0];
});
};
EDIT: Following Docs v7.0.0, I found out db.multi can execute a multi-query string, you can try this:
db.multi(`INSERT INTO deletedjobs
SELECT *
FROM jobs
WHERE id = $1;DELETE FROM jobs WHERE id = $1`, [id])
Other way I think the better solution is that you should wrap the query into a function for insert-delete at same time, like below:
CREATE FUNCTION moveJob(id character varying) RETURNs void AS
$BODY$
BEGIN
INSERT INTO deletedjobs
SELECT *
FROM jobs
WHERE id = id;
DELETE FROM jobs WHERE id = id;
END;
$BODY$
LANGUAGE plpgsql VOLATILE SECURITY DEFINER
COST 100;
And call it as postgresql function in your js:
db.any('select moveJob($1)', [id]);
You can also use a WITH ... AS clause (https://www.postgresql.org/docs/9.1/queries-with.html) to execute both queries in one go. So it could look something like that:
exports.deletePost = function(id) {
return db.query(`
WITH
A AS (SELECT * FROM jobs WHERE id = $1),
B AS (INSERT INTO deletedjobs FROM A),
DELETE FROM jobs WHERE id IN (SELECT id FROM A);
`, [id]).then(results => {
console.log("succesfull transfer");
return results.rows[0];
});
};
Maybe you should not use AND clause, try semicolon ;.
You used select * you should enter columns name, because in later
times you may add a new column, your function does not execute.

Zend: Inserting Large data in CLOB and BLOB?

I am pulling data from Google Places API and trying to insert reviews into oracle database using zend framework. But reviews that are very long are giving error like :
ORA-01461: can bind a LONG value only for insert into a LONG
When i try to run the insert query in Orqcle SQL Developer its giving the following error:
I tried some of the solutions i got on google and stackoverflow but still not working.
Here is my db code in zend:
public function addReview($bind) {
$bind['STATUS'] = 1;
$bind['CREATED_TIME'] = $this->_curDate;
$text = htmlentities($bind['TEXT']);
$query = "Insert INTO ".$this->_name." (LID,AUTHOR_NAME,AUTHOR_URL,RATINGS,TYPE,TIME,STATUS,TEXT)
VALUES (".$bind['LID'].",
'".$bind['AUTHOR_NAME']."',
'".$bind['AUTHOR_URL']."',
'".$bind['RATINGS']."',
'".$bind['TYPE']."',
'".$bind['TIME']."',
".$bind['STATUS'].",'".$text."')";
try {
$insert = $this->_dbAdpt->query($query);
} catch (Exception $e) {
echo $query; exit;
}
}
Somehow creating a procedure for inserting the reviews worked! Below is the procedure :
create or replace procedure google_review (lid in int,author_name in varchar2, author_url in varchar2,ratings in varchar2,
type in varchar2,time in varchar2,status int,text in varchar2)
as
begin
INSERT INTO TBL_REVIEWS
(
LID,
AUTHOR_NAME,
AUTHOR_URL,
RATINGS,
TYPE,
TIME,
STATUS,
TEXT
)
VALUES
(
LID,
AUTHOR_NAME,
AUTHOR_URL,
RATINGS,
TYPE,
TIME,
STATUS,
TEXT
);
end;