pass array to postgres in JDBC - postgresql

I want to do the following query in Postgres using JDBC:
with things as (values(1),(2)) select * from things;
So my Java code looks like this:
String sql = "with things as (?) select * from things";
PreparedStatement pstmt = conn.prepareStatement(sql);
pstmt.setArray(1, conn.createArrayOf("INTEGER", new Integer[]{1, 2});
But this is throwing the following error:
org.postgresql.util.PSQLException: ERROR: syntax error at or near "$1"

You can do what you need using unnest like this:
Integer[] id = {1, 2};
Array array = connection.createArrayOf("int4", id);
try (PreparedStatement stmt = connection.prepareStatement(
"with things as (select unnest((?)::integer[])) select * from things")) {
stmt.setArray(1, array);
ResultSet rs = stmt.executeQuery();
// use the result set
}

Related

Do "$1" parameters in an ilike expression need to be escaped when used with the postgres crate's query function?

I'm using the postgres crate which makes a query with postgres::Connection. I query a table based on a string value in an ilike '%search_string%' expression:
extern crate postgres;
use std::error::Error;
//DB Create queries
/*
CREATE TABLE TestTable (
Id SERIAL primary key,
_Text varchar(50000) NOT NULL
);
insert into TestTable (_Text) values ('test1');
insert into TestTable (_Text) values ('test1');
*/
fn main() -> Result<(), Box<dyn Error>> {
let conn = postgres::Connection::connect(
"postgres://postgres:postgres#localhost:5432/notes_server",
postgres::TlsMode::None,
)?;
let text = "test";
// //Does not work
// let query = &conn.query(
// "
// select * from TestTable where _text ilike '%$1%'
// ",
// &[&text],
// )?;
//Works fine
let query = &conn.query(
"
select * from TestTable where Id = $1
",
&[&1],
)?;
println!("Rows returned: {}", query.iter().count());
Ok(())
}
If I uncomment the //Does not work part of the code, I will get the following error:
thread 'main' panicked at 'expected 0 parameters but got 1'
It appears it doesn't recognize the $1 parameter that is contained in the ilike expression. I've tried escaping the single quotes and that doesn't change it.
The only dependencies are:
postgres = { version = "0.15.2", features = ["with-chrono"] }
To my surprise, here was the fix:
let text = "%test%";
let query = &conn.query(
"
select * from TestTable where _text like $1
",&[&text],
)?;
Apparently the postgres function knows to add single quotes around strings in this scenario.
I found out about this from here: https://www.reddit.com/r/rust/comments/8ltad7/horrible_quote_escaping_conundrum_any_ideas_on/
An example should do the magic.
At the top, I am using pg. So, import it. My code looks like
const title = req.params.title;
const posts = await db.query("SELECT * FROM postsTable INNER JOIN usersTable ON postsTable.author = usersTable.username WHERE title ILIKE $1 ORDER BY postsTable.created_on DESC LIMIT 5;", [`%${title}℅`])

How convert java type to domain of postgres with hibernate(springData)?

i created domain in postgres:
create domain arrayofids as numeric[];
Now i want to use the domain in spring data like this:
String fakeQuery = "unnest(CAST (:ids AS arrayofids))";
Query nativeQuery = entityManager.createNativeQuery(fakeQuery);
BigInteger[] arrayOfids = new BigInteger[] {new BigInteger("1"),new BigInteger("2)} //or It can be List. It is not important
nativeQuery.setParameter("ids", arrayOfids);
List resultList = nativeQuery.getResultList();
Of course i get Error:
org.postgresql.util.PSQLException: ERROR: cannot cast type bytea to arrayofIds
Before i used https://dalesbred.org/docs/api/org/dalesbred/datatype/SqlArray.html and it worked fine or did custom types in JDBC myself. Hibernate doesn't allow use my domain easy.
Query like that:
select * from mtTbale where id in :ids
is not interested. I should use the domain with unnest and CAST
Make :ids as a text representation of an array of numbers, i.e. "{1, 2}" and add SELECT to the query.
Try this:
String fakeQuery = "SELECT unnest(CAST (:ids AS arrayofids))";
Query nativeQuery = entityManager.createNativeQuery(fakeQuery);
String arrayOfids = "{" + 1 + ", " + 2 + "}"; // obtain the string as is relevant in your case
nativeQuery.setParameter("ids", arrayOfids);
List resultList = nativeQuery.getResultList();
and the second query should look like this:
select * from mtTbale where id = ANY(CAST(:ids AS arrayofids));
You may also use Postgres shorthand (and more readable) cast syntax.
Instead of CAST(:ids AS arrayofids) use :ids::arrayofids.

Error when using "ALL" operator when execute query

I need to execute following query using phalcon framework:
"SELECT id FROM table GROUP BY id HAVING '31' = ALL(array_agg(status))"
How can I execute this query using phalcon?
When I do following:
Model::query()
->columns(['id'])
->groupBy('id')
->having('31 = ALL(array_agg(status))')
->execute();
I get this error message:
Syntax error, unexpected token ALL, near to '(array_agg(status)) ', when parsing: SELECT id FROM [SomeNameSpace\Model] GROUP BY [id] HAVING 31 = ALL(array_agg(status)) (137)
I'm not 100% sure which Postgres functions are supported, but you can try like this:
Model::query()
->columns([
'id',
'ALL(array_agg(status)) AS statusCounter'
])
->groupBy('id')
->having('31 = statusCounter')
->execute();
Notice that I moved the aggregation functions in the select, rather in having clause.
UPDATE: here is an example of very custom query. Most functions used are not supported and it's sometimes cleaner just to write a simple SQL query and bind the desired Model to it:
public static function findNearest($params = null)
{
// A raw SQL statement
$sql = '
SELECT *, 111.045 * DEGREES(ACOS(COS(RADIANS(:lat))
* COS(RADIANS(X(coords)))
* COS(RADIANS(Y(coords)) - RADIANS(:lng))
+ SIN(RADIANS(:lat))
* SIN(RADIANS(X(coords)))))
AS distance_in_km
FROM object_locations
ORDER BY distance_in_km ASC
LIMIT 0,5;
';
// Base model
$model = new ObjectLocations();
// Execute the query
return new \Phalcon\Mvc\Model\Resultset\Simple(
null,
$model,
$model->getReadConnection()->query($sql, $params)
);
}
// How to use:
\Models\ObjectLocations::findNearest([
'lat' => 42.4961756,
'lng' => 27.471543300000008
])
You need to add ALL as dialect extension. Check this topic for example https://forum.phalconphp.com/discussion/16363/where-yearcurrenttimestamp-how-to-do-this

How to get List of Table Entity with only selected columns in Hibernate using native SQL?

I am trying to execute SQL query using session.createSQLQuery() method of Hibernate.
test table has 3 columns :
col1
col2
col3
Working
String sql = "SELECT * FROM test";
SQLQuery query = session.createSQLQuery(sql);
query.addEntity(Test.class);
List<Test> testEntityList = query.list();
Not Working
String sql = "SELECT col1, col2 FROM test";
SQLQuery query = session.createSQLQuery(sql);
query.addEntity(Test.class);
List<Test> testEntityList = query.list();
Error:
The column col3 was not found in this ResultSet.
I need to retrieve only a few specific columns from the table rather than the whole table.
How can I achieve this?
You can use hibernate projections, see this answer Hibernate Criteria Query to get specific columns or you can do this by changing the return type to
List<Object[]> and parsing it to List<Test>
List<Object[]> testEntityList = query.list();
List<Test> res = new ArrayList<Test>(testEntityList.size());
for (Object[] obj : testEntityList) {
Test test = new Test();
test.setCol1(obj[0]);
test.setCol2(obj[1]);
res.add(test);
}

I can't get the getGeneratedKeys with the PostgreSQL JDBC driver

I'm blocked on a stupid problem in one of my functions.
I want to get the generatedKey of one of my Sql query. I can't and i don't understand why. The problem is that resultSet.next() it return false even if the line have been inserted when I check the data in the table.
Here is my code :
Statement statement = connection.createStatement();
statement.executeUpdate("INSERT INTO calamar.calamar.application (nom,criticite,autorise) VALUES ('"+nom+"','"+criticite+"','"+false+"');");
ResultSet resultSet = statement.getGeneratedKeys();
resultSet.next();
Solution : Add Statement.RETURN_GENERATED_KEYS
Statement statement = connection.createStatement();
statement.executeUpdate("INSERT INTO calamar.calamar.application (nom,criticite,autorise) VALUES ('"+nom+"','"+criticite+"','"+false+"');", Statement.RETURN_GENERATED_KEYS);
ResultSet resultSet = statement.getGeneratedKeys();
resultSet.next();