Cast values in update query - sql

I have this SQL native query which I want to use from Spring JPA repository:
update words
set low_range = :lowRange, high_range = :highRange
where keyword = :keyword
Error:
ERROR: column "low_range" is of type numeric but expression is of type bytea
I use this column definition:
#Column(name = "low_range")
private Float lowRange;
How I can convert or cast the value into this update query?

Related

PDI: How to change unspecified fields meta type?

I'm handling random tables from a database, I have a field with table's schema, and another with table's name, that way I'm able to do a table input like the following inside a child transformation:
SELECT * FROM ${SCHEMA}.${TABLENAME};
After getting the table values as columns, I want to dynamically generate an SQL with dynamic WHERE clauses, with something like this within a User Defined Java class:
Object[] in = getRow();
String sql = String.format("SELECT %s FROM %s.%s WHERE ",
getParameter("KEYS"),
getParameter("SCHEMA"),
getParameter("TABLE"));
Object[] out = createOutputRow(in, data.outputRowMeta.size());
ArrayList<String> fieldNames = new ArrayList<String>(Arrays.asList(data.inputRowMeta.getFieldNames()));
for(String field: fieldNames){
sql += String.format("\"%s\" = \'%s\' AND ", field, get(Fields.In, field).getString(in));
get(Fields.Out, field).setValue(out, get(Fields.In, field).getString(in));
}
sql = sql.substring(0, sql.length()-4);
sql += ";";
Resulting in a column like this:
SELECT keys, from, the, table FROM SCHEMA.TABLE WHERE "unknown_field" = 'value' AND "unknown_field_1" = '0';
Now, that's all good until I receive a non String type from the SELECT, where I can't do get(Fields.In, field).getString(in)
since it returns
Conversion error: field Integer(9): There was a data type error: the data type of java.lang.String.object [0] does not correspond to value meta [Integer (9)]
Can you change every unspecified field's meta type? If not, is there a way to cast every non String field type within the custom Java Class to String?

POSTGRES JSON: Updating array value in column

I am using POSTGRES SQL JSON.
In json column the value is stored as array which I want to update using SQL query
{"roles": ["Admin"]}
The output in table column should be
{"roles": ["SYSTEM_ADMINISTRATOR"]}
I tried different queries but it is not working.
UPDATE public.bo_user
SET json = jsonb_set(json, '{roles}', to_jsonb('SYSTEM_ADMINISTRATOR')::jsonb, true);
UPDATE public.bo_user
SET json = jsonb_set(json, '{roles}', to_jsonb('["SYSTEM_ADMINISTRATOR"]')::jsonb, true);
ERROR: could not determine polymorphic type because input has type unknown
SQL state: 42804
Kindly help me with the query
but at the moment it is to update the value at 0 index
That can be done using an index based "path" for jsonb_set()
update bo_user
set "json" = jsonb_set("json", '{roles,0}'::text[], '"SYSTEM_ADMINISTRATOR"')
where "json" #>> '{roles,0}' = 'Admin'
The "path" '{roles,0}' references the first element in the array and that is replaced with the constant "SYSTEM_ADMINISTRATOR"' Note the double quotes inside the SQL string literal which are required for a valid JSON string
The WHERE clause ensures that you don't accidentally change the wrong value.
So this worked.
UPDATE public.bo_user
SET json = jsonb_set(json, '{roles}', ('["SYSTEM_ADMINISTRATOR"]')::jsonb, true)
where id = '??';

Returning a tuple column type from slick plain SQL query

In slick 3 with postgres, I'm trying to use a plain sql query with a tuple column return type. My query is something like this:
sql"""
select (column1, column2) as tup from table group by tup;
""".as[((Int, String))]
But at compile time I get the following error:
could not find implicit value for parameter rconv: slick.jdbc.GetResult[((Int, String), String)]
How can I return a tuple column type with a plain sql query?
GetResult[T] is a wrapper for function PositionedResult => T and expects an implicit val with PositionedResult methods such as nextInt, nextString to extract positional typed fields. The following implicit val should address your need:
implicit val getTableResult = GetResult(r => (r.nextInt, r.nextString))
More details can be found in this Slick doc.

Nhibernate and like statement on XML field

I have a wrapped fluent nhibernate framework that I'm reusing and have no control over the actual mapping.
In my entity object I have a property mapped as string to an XML column in sql.
Hence when I run a query like:
var myResult = (from myTable in DataManager.Session.Query<Table>()
where myTable.thatXmlFieldWhichIsMappedAsString.Contains(AnXmlSnippet))
select myTable).FirstOrDefault();
It is trying to use the LIKE operator in SQL which is invalid on that column type.
How can I get around this without having to select all the rows and converting to List first?
In case, that we do not need .Query() (LINQ), and we can use Criteria query or QueryOver, we can use conversion:
// the projection of the column with xml
// casted to nvarchar
var projection = Projections
.Cast(NHibernateUtil.StringClob
, Projections.Property("thatXmlFieldWhichIsMappedAsString"));
// criteria filtering with LIKE
var criteria = Restrictions.Like(projection, "searched xml");
// query and result
var query = session.QueryOver<MyEntity>()
.Where(criteria)
;
var result = query
.SingleOrDefault<MyEntity>()
;
From my experience this could lead to conversion into small nvarchar(255) - sql server... Then we can do it like this:
var projection = Projections
.SqlProjection("CAST(thatXmlFieldWhichIsMappedAsString as nvarchar(max)) AS str"
, new string[]{}
, new NHibernate.Type.IType[]{}
);

Error using Join on uniqueidentifier - convert uniqueidentifier to numeric

I am using Fluent NHibernate on sqlserverce.
Using NHibernate QueryOver I try to retrieve a row - NHibernate generate automatically a a join query
and I get the following Exception:
[SQL: SELECT tag FROM CheckpointToProtectionGroup cp2pg
JOIN CheckpointStorageObject cp ON cp.id = cp2pg.checkpoint_id
JOIN ProtectionGroupCheckpointStorageObject pg ON pg.id = cp2pg.vpg_id
WHERE cp.CheckpointIdentifierIdentifier = 1111 AND
pg.ProtectionGroupIdentifierGroupGuid =
11111111-1111-1111-1111-111111111111]
---> System.Data.SqlServerCe.SqlCeException:
The conversion is not supported.
[ Type to convert from (if known) = uniqueidentifier,
Type to convert to (if known) = numeric ]
From what I see, it seems that it tries to convert the value - 11111111-1111-1111-1111-111111111111 to numeric but this value is a Guid field:
CheckpointToProtectionGroup checkpointToProtectionGroup = Session
.QueryOver<CheckpointToProtectionGroup>()
.JoinQueryOver( row => row.ProtectionGroup)
.Where(row => row.ProtectionGroupIdentifier.GroupGuid ==
protectionGroupIdentifier.GroupGuid)
.SingleOrDefault();
ProtectionGroupIdentifier.GroupGuid is of Guid type
Looks like your GroupGuid value is not correctly converted to SQL. It should have single quotes around the value.
pg.ProtectionGroupIndentifierGroupGuidId = '11111111-1111-1111-1111-111111111111'
SQL Server tried to convert left hand value from uniqueidentifier (Guid) to numeric, since the right hand value is numeric value - numeric subtract operation with few operands.
You have protectionGroupIdentifier.GroupGuid value in Where part of your QueryOver expression. Check if GroupGuid is indeed Guid property. If it's an object property, cast it to Guid.