How to retrieve data from data_type RAW in Oracle with Groovy? - sql

I have a table in oracle db with data type RAW.
I would like export into an xml file but when I retrieve the data from the RAW column I get a [#4r5... instead of the value in db (123454678...)
How can I write this value in xml (the goal is to export in another db)
Thanks a lot.

You don't say what code you're using to access the column, but it looks like you are getting back a byte[]
You should be able to print the actual bytes in groovy using:
println obj.toList().join(',')
But if you were expecting a string or something, you'll need to know how it was converted to bytes in the first place...
If you want the byte array converted to an array of integers, you can just do:
List byteList = a.toList()
(or if you want your bytes to be treated as unsigned, you can do)
List byteList = a.collect { it & 0xff }
It depends what you intend to do with the array though... It is probably best left as an array...

Did you try PL/SQL?
declare
a mytable.rawcol%TYPE;
begin
select rawcol into a from mytable;
-- now do something with "a"
end;

Related

Convert rawstring (Byte String) into readable String

Requirement:
To convert SRT_MMASTER table's MESSAGE_DATA field data into readable string format or in internal table.
I have tried different function modules to convert Byte String (Blob) data stored in SRT_MMASTER table's MESSAGE_DATA field but none of it returned readable string format or at least generate an XML file in return.
I have tried Function modules like :
SCMS_BINARY_TO_STRING,
SDIXML_XML_TO_DOM,
SDIXML_DOM_TO_DATA,
SMUM_XML_PARSE
and methods like :
cl_soap_xml_parser=>get_data
cl_soap_xml_parser=>get_formatted_data
CALL METHOD cl_bcs_convert=>raw_to_string
and more, but none were able to convert it to correct readable format.
Can you suggest which function module or class/method can be used to solve the purpose?
You can use IMPORT from DATA BUFFER and cl_soap_xml_helper=>xstring_to_string
DATA:
lt_message_item TYPE srt_persistency_item_t,
lx_message_data TYPE xstring.
SELECT SINGLE message_data FROM srt_mmaster INTO lx_message_data.
IMPORT message_data = lt_message_item FROM DATA BUFFER lx_message_data.
DATA(lv_string) = cl_soap_xml_helper=>xstring_to_string( lt_item[ 1 ]-value ).

Convert String to array and validate size on Vertica

I need to execute a SQL query, which converts a String column to a Array and then validate the size of that array
I was able to do it easily with postgresql:
e.g.
select
cardinality(string_to_array('a$b','$')),
cardinality(string_to_array('a$b$','$')),
cardinality(string_to_array('a$b$$$$$','$')),
But for some reason trying to convert String on vertica to array is not that simple, Saw this links:
https://www.vertica.com/blog/vertica-quick-tip-dynamically-split-string/
https://forum.vertica.com/discussion/239031/how-to-create-an-array-in-vertica
And much more that non of them helped.
I also tried using:
select REGEXP_COUNT('a$b$$$$$','$')
But i get an incorrect value - 1.
How can i Convert String to array on Vertica and gets his Length ?
$ has a special meaning in a regular expression. It represents the end of the string.
Try escaping it:
select REGEXP_COUNT('a$b$$$$$', '[$]')
You could create a UDx scalar function (UDSF) in Java, C++, R or Python. The input would be a string and the output would be an integer. https://www.vertica.com/docs/9.2.x/HTML/Content/Authoring/ExtendingVertica/UDx/ScalarFunctions/ScalarFunctions.htm
This will allow you to use language specific array logic on the strings passed in. For example in python, you could include this logic:
input_list = input.split("$")
filtered_input_list = list(filter(None, input_list))
list_count = len(filtered_input_list)
These examples are a good starting point for writing UDx's for Vertica. https://github.com/vertica/UDx-Examples
I wasn't able to convert to an array - but Im able to get the length of the values
What i do is convert to Rows an use count - its not best performance wise
But with this way Im able to do also manipulation like filtering of each value between delimiter - and i dont need to use [] for characters like $
select (select count(1)
from (select StringTokenizerDelim('a$b$c','$') over ()) t)
Return 3

Find records where length of array equal to - Rails 4

In my Room model, I have an attribute named available_days, which is being stored as an array.
For example:
Room.first.available_days
=> ["wed", "thurs", "fri"]
What is the best way to find all Rooms where the size of the array is equal to 3?
I've tried something like
Room.where('LENGTH(available_days) = ?', 3)
with no success.
Update: the data type for available_days is a string, but in order to store an array, I am serializing the attribute from my model:
app/models/room.rb
serialize :available_days
Can't think of a purely sql way of doing it for sqlite since available_days is a string.
But here's one way of doing it without loading all records at once.
rooms = []
Room.in_batches(of: 10).each_record do |r|
rooms << r if r.available_days.length == 3
end
p rooms
If you're using postgres you can parse the serialized string to an array type, then query on the length of the array. I expect other databases may have similar approaches. How to do this depends on how the text is being serialized, but by default for Rails 4 should be YAML, so I expect you data is encoded like this:
---
- first
- second
The following SQL will remove the leading ---\n- as well as the final newline, then split the remaining string on - into an array. It's not strictly necessary to cleanup the extra characters to find the length, but if you want to do other operations you may find it useful to have a cleaned up array (no leading characters or trailing newline). This will only work for simple YAML arrays and simple strings.
Room.where("ARRAY_LENGTH(STRING_TO_ARRAY(RTRIM(REPLACE(available_days,'---\n- ',''),'\n'), '\n- '), 1) = ?", 3)
As you can see, this approach is rather complex. If possible you may want to add a new structured column (array or jsonb) and migrate the serialized string into the a typed column to make this easier and more performant. Rails supports jsonb serialization for postgres.

postgresql to_json() function escapes all doublequote characters

I've written a plpgsql script which generates an array of json objects in a string but after I use to_json() method passing a variable with that string to it, it returns a result which is doublequoted and also every doublequote character is escaped. But I need that string as is.
initial content of jsonResult variable is:
[{"key":{04949429911,"Code":"400"},"value":"20000.00"},{"key":{"InsuranceNumber":"04949429911","Code":"403"},"value":"10000.00"},...]
but after to_json() it looks like this:
"[{\"key\":{04949429911,\"Code\":\"400\"},\"value\":\"20000.00\"},{\"key\":{\"InsuranceNumber\":\"04949429911\",\"Code\":\"403\"},\"value\":\"10000.00\"}...]"
This is the place where everything stored in jsonResult breakes:
UPDATE factor_value SET params = to_json(jsonResult) WHERE id = _id;
What am I doing wrong?
This answer points out that simply casting to json should suffice:
UPDATE factor_value SET params = jsonResult::json WHERE id = _id;
The weird escaping you see is probably due to postgresql not realizing you already have valid JSON and your varchar is just converted to a plain javascript/JSON string.
I needed to convert a bytea column to jsonb and I ended up with escaped characters when using to_json. I also used bytea_data_column::jsonb and postgres said cannot cast to jsonb. Here is how I worked around it:
bytea_data_column::text::jsonb

Return binary as string, NOT convert or cast

Is there a simple way (like convert or cast) to return a binary field as a string without actually converting it or casting it?
The data I want looks like this in the database:
0x24FC40460F58D64394A06684E9749F30
When using convert(varchar(max), binary_field), it comes back like this:
$ü#FXÖC” f„étŸ0
cast(binary_field as varchar(max)) had the same results.
I'm trying to modify a datasource in an old vb.net application, so I want it to be a string like the existing values, but still look like the original data. I don't have to do it in the query, but I'd like to if possible to avoid modifying the old vb code too much.
Here is my select statement:
SELECT strName, strDesc, binUUID
FROM MyTableName
where intFamily = '1234'
order by strName
Alternatively, if I do cast/convert it, would it be safe to compare "$ü#FXÖC” f„étŸ0" stored as a string at a later time to another value gathered in the same way?
There is a built in function to generate hex strings from binary values
SELECT sys.fn_varbintohexstr (0x24FC40460F58D64394A06684E9749F30)