Creating Select statement with variable in single quotes - select

This relates to taking data from a Google Fusion table.
When I first set up my site, GF tableid was a numeric value, (var tableid = 123456;) and I built a query like this:
layer.setQuery("SELECT 'Latitude' FROM " + tableid + " WHERE 'Name' contains etc etc
Now tableid is something like var tableid = '12DFty24'; and I'm having trouble converting the setQuery to handle it.
I've tried adding an extra single quote around tableid, but that doesn't work. Nor do backslashes.
Ideas would be gratefully received!
Paul

You are using the old syntax that can't work with encrypted ID, numeric ID's are deprecated.
You have to change your code using the new syntax; here is the documentation
Example:
new google.maps.FusionTablesLayer({ query: {[FusionTablesQuery object]}});

And here's the one that works...need to be careful with parentheses and commas!
function searchAddress()
{
var searchString = document.getElementById('searchAddressString').value.replace("'", "\\'");
// layer.setQuery("SELECT 'Latitude' FROM " + tableid + " WHERE 'Address' contains ignoring case '" + searchString + "'");
var layer = new google.maps.FusionTablesLayer({
query: {
select: 'Latitude',
from: tableid,
where: 'Address' contains ignoring case '" + searchString + "'"
}
});
layer.setMap(map);
}

Related

Passing an string parameter in JPQL native query

I have the following JpaRepository method:
#Query(value = "select * from default_price_view where product_code #> '{:productCode}'", nativeQuery = true)
Page<DefaultPriceView> findDefaultPricesByProductCode(Pageable pageable,
#Param("productCode") String productCode);
product_code is an array of strings with the format in Postgresql:
{021715,X91778,W21722}
Can you please tell me how I could add the parameter productCode into the query because currently it doesn't work :-(
Thank you in advance for your help,
If I understand well you have product_code is an array in Java, and in Postgresql it's with this format {021715,X91778,W21722}
If this is the case, Try to define a string :
String productCodeString = "{" + productCode[0] + "," + productCode[1]+ "," +productCode[2]+ "}";
and use it in your request :productCodeString

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.

JPA - Find items from a list that don't exist in a table

Given a list of emails, I need to find which ones don't exist in a table. Using SQL, I can do the following:
SELECT e.email
FROM
(
VALUES('email1'),('email2'),('email3'),('email4')
) AS e(email)
EXCEPT
SELECT username FROM dbo.UsersTbl;
How can I write equivalent JPQL? In the application, values email1, email2... need be dynamically built (not hardcoded) based on passed in list. Using a Spring Data JPA native query, I can do the following:
#Query( value =
"SELECT e.email " +
" FROM " +
"( " +
" VALUES('email1'),('email2'),('email3'),('email4') " +
" ) AS e(email) " +
" EXCEPT " +
" SELECT username FROM dbo.UsersTbl ",
nativeQuery=true)
List<String> findMissingEmails(List<String> emails);
But how can I pass in the list of emails to the query?
For fixed number of email arguments, this could work:
#Query( value =
"SELECT e.email " +
" FROM " +
"( " +
" VALUES(:email1),(:email2),(:email3),(:email4) " +
" ) AS e(email) " +
" EXCEPT " +
" SELECT username FROM dbo.UsersTbl ",
nativeQuery=true)
List<String> findMissingEmails(String email1, String email2, String email3, String email4);
For high and/or dynamic number of emails, a better approach could be to use NativeQuery constructed at runtime.
Old answer - more or less exactly the opposite of what was asked for, but I'll keep it here as reference.
Using of named parameter:
#Query("SELECT u.email FROM User AS u WHERE u.email NOT IN (:emails)")
List<String> findMissingEmails(#Param("emails")Collection<String> emails);
Alternatively, you could use a JPA query method:
#Repository
public interface UserRepository extends JpaRepository<User, Long> {
List<User> findAllByEmailNotIn(Collection<String> emails);
}
Unfortunately that method would fetch and return a list of Users instead of list of their emails.
To fetch just emails you could use a JPA projection.
Assuming that User entity has a field of type String named email, the following projection could be used:
public interface UserEmail {
String getEmail();
}
And this is the repository method:
#Repository
public interface UserRepository extends JpaRepository<User, Long> {
List<UserEmail> findAllByEmailNotIn(Collection<String> emails);
}

How to fix: Error thrown mapping result set into return type

I am using JDBI 3 to run update query which might update multiple rows. I want to get updated rows from the resultset.
However, I'm getting ArrayIndexOutOfBoundsException: Error thrown mapping result set into return type
Tried to add #SingleValue to return signature, but still stuck with the same issue.
Unable to use #SqlBatch as this is a single query and #SqlBatch requires list.
#SqlUpdate(
"UPDATE task_sync SET "
+ " is_active = false, "
+ " version = version+1 "
+ " WHERE task_id IN (<taskIdList>) "
+ " AND barcode IN (<barcodeList>) "
+ " AND is_active = true ")
#GetGeneratedKeys("id")
List<Long> deactivateTaskSyncByTaskIdInAndBarcodeList(
#BindList("taskIdList") List<Long> taskIdList,
#BindList("barcodeList") Set<String> barcodeList,
#Bind("lastUpdatedById") Long lastUpdatedById);
Query generated:
UPDATE task_sync SET is_active = false, version = version+1 WHERE task_id IN (26) AND barcode IN ('8606850380_0', '8696930120_0', '6907922280_0', '4605723180_0', '2354050010_0', '5259987660_0', '6392185330_0'
) AND is_active = true
RETURNING "id"
I expect this to return a list of updated ids.
You are in the right track.
To make it work you need to tell Postgres that you want to return the id column of all affected rows. You can do this by a adding RETURNING id; to the end of your query. The code would look like this:
#SqlUpdate(
"UPDATE task_sync SET "
+ " is_active = false, "
+ " version = version+1 "
+ " WHERE task_id IN (<taskIdList>) "
+ " AND barcode IN (<barcodeList>) "
+ " AND is_active = true RETURNING id;")
#GetGeneratedKeys("id")
List<Long> deactivateTaskSyncByTaskIdInAndBarcodeList(
#BindList("taskIdList") List<Long> taskIdList,
#BindList("barcodeList") Set<String> barcodeList,
#Bind("lastUpdatedById") Long lastUpdatedById);
Notice that you can also return multiple columns (e.g.: RETURNING id, version;) or event the entire row (e.g: RETURNING *;).

Sequelize -- Use options.distinct with a Where Clause?

I'm trying to use Sequelize to find all distinct fields in a column, using a query with a where clause. I've searched the Sequelize docs and tried a number of different things, but haven't yet found the correct syntax.
Here's my current draft syntax:
var searchResults = connectors.cars.findAll({
attributes: [
connectors.Sequelize.options.distinct
],
where: {
condition: connectors.Sequelize.where(connectors.Sequelize.fn('LOWER', connectors.Sequelize.col('mfgr')), 'LIKE', '%' + searchString + '%')
}
});
What is the correct way to use options.distinct alongside a where clause?
Note: edited to remove a bunch of extra code that had been requested in the comments, but which in retrospect may have been obfuscating the issue.
Really more of a comment, but what's going on with this code?
}).then((searchResults) => searchResults.map((item) => item.dataValues));
debugger;
return searchResults; <== ERROR IS THROWN HERE
1) What is the destination of the map()? 2) Won't the return occur before the results are returned, as it's not in the .then() block? Should it not be more like this:
}).then((searchResults) => {
var new_results = searchResults.map((item) => item.dataValues));
debugger;
return new_results;
}
Am I missing something?
I'm getting the impression that this is hard to do in raw sql, let alone Sequelize. I found an answer that uses raw sql here:
const myQuery = "WITH cte AS\n" +
"( SELECT id, mfgr, ROW_NUMBER() OVER (PARTITION BY mfgr ORDER BY mfgr DESC) AS rn\n" +
" FROM cars\n" +
" WHERE LOWER(mfgr) like '%" + searchString + "%'\n" +
")\n" +
"SELECT *\n" +
"FROM cte\n" +
"WHERE rn = 1";
let searchResults = connectors.db.query(myQuery);