ERROR : The column index is out of range: 1, number of columns: 0 - postgresql

I'm using wso2dss 3.0.0.I'm trying to execute a postgresql query i.e.
SELECT addressid, geocode
FROM maddress
WHERE geocode::point <# circle '((18.9750,72.8258), 5)';
It is working fine in PostgreSQL.When i'm using same query in wso2dss i.e.
SELECT addressid, geocode
FROM maddress
WHERE geocode::point <# circle '((?,?), ?)';
It gives me error like :
DS Fault Message: Error in 'SQLQuery.processNormalQuery'
DS Code: DATABASE_ERROR
Source Data Service:-
Name: Geofence_DataService
Location: /Geofence_DataService.dbs
Description: N/A
Default Namespace: http://ws.wso2.org/dataservice
Current Request Name: adding_geofence_op
Current Params: {longitude=72.8258, radius=4, latitude=18.9750}
Nested Exception:-
DS Fault Message: Error in 'createProcessedPreparedStatement'
DS Code: UNKNOWN_ERROR
Nested Exception:-
org.postgresql.util.PSQLException: The column index is out of range: 1, number of columns: 0.
if i remove " ' "(quotation mark) of circle then also it will not execute. query '' look like this :
SELECT addressid, geocode
FROM maddress
WHERE geocode::point <# circle ((?,?), ?);
it'll give following error :
Caused by: javax.xml.stream.XMLStreamException: DS Fault Message: Error in 'SQLQuery.processNormalQuery'
DS Code: DATABASE_ERROR
Source Data Service:-
Name: Geofence_DataService
Location: /Geofence_DataService.dbs
Description: N/A
Default Namespace: http://ws.wso2.org/dataservice
Current Request Name: geofence_op
Current Params: {longitude=72.8258, radius=4, latitude=18.9750}
Nested Exception:-
org.postgresql.util.PSQLException: ERROR: function circle(record, double precision) does not exist
Hint: No function matches the given name and argument types. You might need to add explicit type cast
But circle is inbuilt geographical function of PostgreSQL then is it necessary to write explicit function? else where is the exact error? Even if i put the query with input parameter as i execute in PostgreSQL then also it's working.If so then why it is not accepting dynamic parameters? Please let me know..

Geometric types can be input in multiple ways.
In the first form, your ? parameters are not replaced with values because they are literal parts of a string. So 0 parameters are expected ...
In the second form without single quotes, your ? parameters are replaced, but ((18.9750,72.8258), 5) is interpreted to be a row type, which doesn't work with circle().
You are trying to invoke the geometric function circle() that takes a point and a double precision ("center and radius to circle"). These are valid syntax variants:
SELECT circle '((18.9750,72.8258), 5)' AS cast_literal
' <(18.9750,72.82580),5>'::circle AS cast_literal2
, circle(point '(18.9750,72.8258)', '5') AS literal_point_n_radius
, circle(point(18.9750,72.8258), '5') AS point_n_literal_radius
, circle(point(18.9750,72.8258), 5) AS point_n_radius
SQL fiddle.
The cast to ::text is just to sanitize the deranged display in SQL fiddle
In your case, to provide numeric values (not a string literal), use the last form and it should work:
SELECT addressid, geocode
FROM maddress
WHERE geocode::point <# circle(point(?,?), ?);
If wso2dss (which I have no experience with) does not accept functions, you have to use one of the first two forms and provide a single parameter as string literal:
SELECT addressid, geocode
FROM maddress
WHERE geocode::point <# circle ?;
... where the parameter is the concatenated literal as displayed above.
You could let Postgres do the concatenation and still pass three numeric values:
SELECT addressid, geocode
FROM maddress
WHERE geocode::point <# ('(('::text || ? || ',' || ? || '),' || ? || ')')::circle;

Related

The column index is out of range: 2, number of columns: 1 error while updating jsonb column

I am trying to update jsonb column in java with mybatis.
Following is my mapper method
#Update("update service_user_assn set external_group = external_group || '{\"service_name\": \"#{service_name}\" }' where user=#{user} " +
" and service_name= (select service_name from services where service_name='Google') " )
public int update(#Param("service_name")String service_name,#Param("user") Integer user);
I am getting the following error while updating the jsonb (external_group) cloumn.
### Error updating database. Cause: org.postgresql.util.PSQLException: The column index is out of range: 2, number of columns: 1.
### The error may involve com.apds.mybatis.mapper.ServiceUserMapper.update-Inline
I am able to update with the same way for non-jsonb columns.
Also if I am putting hardcoded value it's working for jsonb columns.
How to solve this error while updating jsonb column?
You should not enclose #{} in single quotes because it will become part of a literal rather than a placeholder. i.e.
external_group = external_group || '{"service_name": "?"}' where ...
So, there will be only one placeholder in the PreparedStatement and you get the error.
The correct way is to concatenate the #{} in SQL.
You may also need to cast the literal to jsonb type explicitly.
#Update({
"update service_user_assn set",
"external_group = external_group",
"|| ('{\"service_name\": \"' || #{service_name} || '\" }')::jsonb",
"where user=#{user} and",
"service_name= (select service_name from services where service_name='Google')"})
The SQL being executed would look as follows.
external_group = external_group || ('{"service_name": "' || ? || '"}')::jsonb where ...

DB2 SQL Error: SQLCODE=-302 while executing prepared statement

I have a SQL query which takes user inputs hence security flaw is present.
The existing query is:
SELECT BUS_NM, STR_ADDR_1, CITY_NM, STATE_CD, POSTAL_CD, COUNTRY_CD,
BUS_PHONE_NB,PEG_ACCOUNT_ID, GDN_ALERT_ID, GBIN, GDN_MON_REF_NB,
ALERT_DT, ALERT_TYPE, ALERT_DESC,ALERT_PRIORITY
FROM ( SELECT A.BUS_NM, AE.STR_ADDR_1, A.CITY_NM, A.STATE_CD, A.POSTAL_CD,
CC.COUNTRY_CD, A.BUS_PHONE_NB, A.PEG_ACCOUNT_ID, 'I' ||
LPAD(INTL_ALERT_DTL_ID, 9,'0') GDN_ALERT_ID,
LPAD(IA.GBIN, 9,'0') GBIN, IA.GDN_MON_REF_NB,
DATE(IAD.ALERT_TS) ALERT_DT,
XMLCAST(XMLQUERY('$A/alertTypeConfig/biqCode/text()' passing
IAC.INTL_ALERT_TYPE_CONFIG as "A") AS CHAR(4)) ALERT_TYPE,
, ROW_NUMBER() OVER () AS "RN"
FROM ACCOUNT A, Other tables
WHERE IA.GDN_MON_REF_NB = '100'
AND A.PEG_ACCOUNT_ID = IAAR.PEG_ACCOUNT_ID
AND CC.COUNTRY_CD = A.COUNTRY_ISO3_CD
ORDER BY IA.INTL_ALERT_ID ASC )
WHERE ALERT_TYPE IN (" +TriggerType+ ");
I changed it to accept TriggerType from setString like:
SELECT BUS_NM, STR_ADDR_1, CITY_NM, STATE_CD, POSTAL_CD, COUNTRY_CD,
BUS_PHONE_NB,PEG_ACCOUNT_ID, GDN_ALERT_ID, GBIN, GDN_MON_REF_NB,
ALERT_DT, ALERT_TYPE, ALERT_DESC,ALERT_PRIORITY
FROM ( SELECT A.BUS_NM, AE.STR_ADDR_1, A.CITY_NM, A.STATE_CD, A.POSTAL_CD,
CC.COUNTRY_CD, A.BUS_PHONE_NB, A.PEG_ACCOUNT_ID,
'I' || LPAD(INTL_ALERT_DTL_ID, 9,'0') GDN_ALERT_ID,
LPAD(IA.GBIN, 9,'0') GBIN, IA.GDN_MON_REF_NB,
DATE(IAD.ALERT_TS) ALERT_DT,
XMLCAST(XMLQUERY('$A/alertTypeConfig/biqCode/text()' passing
IAC.INTL_ALERT_TYPE_CONFIG as "A") AS CHAR(4)) ALERT_TYPE,
ROW_NUMBER() OVER () AS "RN"
FROM ACCOUNT A, other tables
WHERE IA.GDN_MON_REF_NB = '100'
AND A.PEG_ACCOUNT_ID = IAAR.PEG_ACCOUNT_ID
AND CC.COUNTRY_CD = A.COUNTRY_ISO3_CD
ORDER BY IA.INTL_ALERT_ID ASC )
WHERE ALERT_TYPE IN (?);
Setting trigger type as below:
if (StringUtils.isNotBlank(request.getTriggerType())) {
preparedStatement.setString(1, triggerType != null ? triggerType.toString() : "");
}
Getting error as
Caused by: com.ibm.db2.jcc.am.SqlDataException: DB2 SQL Error: SQLCODE=-302, SQLSTATE=22001, SQLERRMC=null, DRIVER=4.19.26
The -302 SQLCODE indicates a conversion error of some sort.
SQLSTATE 22001 narrows that down a bit by telling us that you are trying to force a big string into a small variable. Given the limited information in your question, I am guessing it is the XMLCAST that is the culprit.
DB2 won't jam 30 pounds of crap into a 4 pound bag so to speak, it gives you an error. Maybe giving XML some extra room in the cast might be a help. If you need to make sure it ends up being only 4 characters long, you could explicitly do a LEFT(XMLCAST( ... AS VARCHAR(64)), 4). That way the XMLCAST has the space it needs, but you cut it back to fit your variable on the fetch.
The other thing could be that the variable being passed to the parameter marker is too long. DB2 will guess the type and length based on the length of ALERT_TYPE. Note that you can only pass a single value through a parameter marker. If you pass a comma separated list, it will not behave as expected (unless you expect ALERT_TYPE to also contain a comma separated list). If you are getting the comma separated list from a table, you can use a sub-select instead.
Wrong IN predicate use with a parameter.
Do not expect that IN ('AAAA, M250, ABCD') (as you try to do passing a comma-separated string as a single parameter) works as IN ('AAAA', 'M250', 'ABCD') (as you need). These predicates are not equivalent.
You need some "string tokenizer", if you want to pass such a comma-separated string like below.
select t.*
from
(
select XMLCAST(XMLQUERY('$A/alertTypeConfig/biqCode/text()' passing IAC.INTL_ALERT_TYPE_CONFIG as "A") AS CHAR(4)) ALERT_TYPE
from table(values xmlparse(document '<alertTypeConfig><biqCode>M250, really big code</biqCode></alertTypeConfig>')) IAC(INTL_ALERT_TYPE_CONFIG)
) t
--WHERE ALERT_TYPE IN ('AAAA, M250, ABCD')
join xmltable('for $id in tokenize($s, ",\s?") return <i>{string($id)}</i>'
passing cast('AAA, M250 , ABCD' as varchar(200)) as "s"
columns token varchar(200) path '.') x on x.token=t.ALERT_TYPE
;
Run the statement as is. Then you may uncomment the string with WHERE clause and comment out the rest to see what you try to do.
P.S.:
The error you get is probably because you don't specify the data type of the parameter (you don't use something like IN (cast(? as varchar(xxx))), and db2 compiler assumes that its length is equal to the length of the ALERT_TYPE expression (4 bytes).

Database fragment query error "parameters must be of length 0 for query"

I am trying to query a json array in the building table, jsonb metadata column, and within google_place_ids property, which is an array.
Elixir is giving me an error:
Here's the query the fragment is generating:
SELECT b0."id", b0."base_sku", b0."name", b0."logo", b0."email", b0."active", b0."sync", b0."building_group_id", b0."operating_region_id", b0."building_package_id", b0."metadata", b0."location", b0."inserted_at", b0."updated_at" FROM "buildings" AS b0 WHERE (b0."metadata"->'google_place_ids' #> '["$1"]') AND (b0."active" = TRUE) ["1234231223123"]
Here's the code:
defp query_by_google_place_id(query, google_place_id) do
from(b in query,
where: fragment("?->'google_place_ids' #> '[\"?\"]'", b.metadata, ^google_place_id),
where: b.active == true,
limit: 1)
end
Here is the error:
[error] #PID<0.1340.0> running Proxy.InstrumentedPlug terminated
Server: localhost:4000 (http)
Request: GET /something/google_place_id/1234231223123
** (exit) an exception was raised:
** (ArgumentError) parameters must be of length 0 for query %Postgrex.Query{columns:
This is not how PostgreSQL will understand it. The problem is that Ecto's fragment do not know anything about SQL (or other query language) you can use there, so it ends treating ? as a query parameter while PostgreSQL treats it as a raw string "$1". What you need to do is to pass string directly in form of:
fragment("?->'google_place_ids' #> ?", b.metadata, ^"[\"#{google_place_id}\"]")
This works, less quotes and no brackets
defp query_by_google_place_id(query, google_place_id) do
from(b in query,
where: fragment("?->'google_place_ids' #> ?", b.metadata, ^google_place_id),
where: b.active == true,
limit: 1)
end

SQL Command failed with: ERROR: operator does not exist: character varying?

i am trying to get values from database by using following query
SELECT Distinct org.name AS org, sto.ad_org_id AS wh_nearstoredetails_id, sum(sto.qtyonhand) AS qty, pro.name AS product
FROM ad_org org, m_storage_detail sto, m_product pro
WHERE sto.ad_org_id::text = org.ad_org_id::text
AND (sto.m_locator_id::text IN ( select cast(m_locator.m_locator_id as text)
from m_locator,m_warehouse
where m_warehouse.isactive = cast('Y' as varchar)
and m_warehouse.em_ai_warehouseparent::text not like cast('' as text)
and m_warehouse.m_warehouse_id::text = m_locator.m_warehouse_id::text
and m_locator.isdefault = cast('Y' as varchar)))
AND sto.m_product_id::text = pro.m_product_id::text
AND sto.qtyonhand >= cast(1 as numeric)
AND sto.ad_org_id::text IN ( SELECT cast(m_warehouse.ad_org_id as text)
FROM m_warehouse
WHERE m_warehouse.em_ai_warehouseparent::text not like cast('' as text))
GROUP BY org.name,sto.ad_org_id,pro.name
ORDER BY org.name, pro.name;
after creating this i also created a class to call this query and get data but when i deploy my project i am getting following error
WARN - SQL Command failed with: ERROR: operator does not exist: character varying !
Hint: No operator matches the given name and argument type(s). You might need to add explicit type casts.
please help to solve this issue.
i finally found the mistake what i made.
the problem in the above query is i'm trying to make type cast of null value
now i changed the condition to check 'is not null' than "not like ''"
and even i don't need to add cast operation it's useless.
anyways thanks for you response. :)

Why can't I enter a NULL value using Numeric or Date type in Postgresql?

I'm doing a little application for the work and it includes a form. When the person using the form doesn't put a value in a data type "numeric" (lets say a PIN number) or even a date in one of my "date" Data Type fields (lets say his anniverssary), it returns me with the errors as follow:
Error Type – Type d'erreur
_Microsoft OLE DB Provider for ODBC Drivers (0x80004005)_
ERROR: invalid input syntax for type numeric: ""; Error while executing the query
Error Type – Type d'erreur
_Microsoft OLE DB Provider for ODBC Drivers (0x80004005)_
ERROR: syntax error at or near ")"; Error while executing the query
So it seems that when the person using the form enters nothing, it returns the string "empty" that is "".
Why can't the numeric type and data type read that as a NULL entry? These fields are not mandatory and so I need to have them be sometimes blank.
How can I make it possible? Is their a way to keep using "numeric" and "date" type so that when the user enters nothing in those fields, the table fills with a blank case insted of giving me this error?
Here is my sql statement :
trsConn.EXECUTE "INSERT INTO ""TRS"".employeetbl ( "& _
"""firstName"", " & _
"""lastName"" , " & _
"""detContract"", " & _
"sle, " & _
"""posNumber"" "& _
") VALUES (" & _
"'" & Request.Form("empFirst") & "', " & _**
"'" & Replace(Request.Form("empLast"), "'", "`") & "', " & _
"'" & Request.Form("dateContract") & "', " & _
"'" & Request.Form("sle") & "', " & _
"'" & Request.Form("posNum") & "');"
(The posNum and dateContract are both respectivly of type "numeric" and "date"
Thanks so much for the help. Looking forward for hearing what you geniuses have to say.
The concept of NULL in SQL is pretty muddled and inconsistent ... but it's very clear that '' is distinct from NULL.
'' isn't NULL, it's '', the empty string. You can't convert it to a date, number, etc:
regress=# SELECT CAST('' AS DATE);
ERROR: invalid input syntax for type date: ""
LINE 1: SELECT CAST('' AS DATE);
^
regress=# SELECT CAST('' AS NUMERIC);
ERROR: invalid input syntax for type numeric: ""
LINE 1: SELECT CAST('' AS NUMERIC);
^
Some products - notably Microsoft Access and old versions of MySQL - are confused about that matter. NULL is NULL, '' is the empty string; they aren't the same thing. You can't convert one to the other.
So it seems that when the person using the form enters nothing, it
returns the string "empty" that is "". Why can't the numeric type and
data type read that as a NULL entry? These fields are not mandatory
and so I need to have them be sometimes blank.
That's your application's job. When your app it sees the empty string come in on a form field for a numeric, date, or similar, it should send NULL to the database, not ''. That's normally a routine part of converting data from user input before it's supplied to the database. It is vital that you do such conversion; you should never just send values from the user straight to the database.
A quick search suggests that asp classic uses null or undefined as its null values; you should be able to pass them into your prepared statements when something is null.
The fact that you get a syntax error after the error about '' suggests that you're building your SQL statements as strings, not using prepared statements with placeholders. (Thanks JayC for the SO question ref). This is begging for SQL injection; in other words your application is critically insecure. Imagine what happens if the user enters the "date":
2012-01-01'); DROP SCHEMA public;--
and your app happily turns that into
INSERT INTO sometable (blah, blah, blah) VALUES (1, 2, DATE '2012-01-01'); DROP SCHEMA public;--');
The DROP SCHEMA then merrily executes and whoops, splat, there goes your database. That's just the dumbest, simplest kind of SQL injection attack too.