Oracle PLSQL - Error handling in UTL_FILE - sql

My script as below, it will load a csv file to PRODUCT_TBL and it any error happened during the process, the script will rollback transaction and output an error message, however it does not print out the message when it hit UTL_FILE error, example invalid file operations. Any help are appreciated. Thanks
DECLARE
V_error_code NUMBER;
V_error_message VARCHAR2(255);
V_ignore_headerlines NUMBER := 1;
V_eof BOOLEAN := FALSE;
F UTL_FILE.FILE_TYPE;
V_LINE VARCHAR2 (32767);
V_PRD_ID PRODUCT_TBL.PRD_ID%TYPE;
V_PATTERN PRODUCT_TBL.PATTERN%TYPE;
V_REMARK PRODUCT_TBL.REMARK%TYPE;
V_CREATED_BY PRODUCT_TBL.CREATED_BY%TYPE;
V_CREATED_DATE PRODUCT_TBL.CREATED_DATE%TYPE;
V_MODIFIED_BY PRODUCT_TBL.MODIFIED_BY%TYPE;
V_MODIFIED_DATE PRODUCT_TBL.MODIFIED_DATE%TYPE;
BEGIN
F := UTL_FILE.FOPEN ('DATA_DIR', 'PRODUCT_TBLv51.csv', 'R');
IF V_ignore_headerlines > 0
THEN
BEGIN
FOR i IN 1 .. V_ignore_headerlines
LOOP
UTL_FILE.get_line(F, V_LINE);
END LOOP;
EXCEPTION
WHEN NO_DATA_FOUND
THEN
V_eof := TRUE;
END;
END IF;
WHILE NOT V_eof
LOOP
BEGIN
UTL_FILE.GET_LINE(F, V_LINE, 32767);
IF V_LINE IS NULL THEN
EXIT;
END IF;
V_PRD_ID := REGEXP_SUBSTR(V_LINE, '([^,\(]*(\([^\)]*\)[^,\(]*)*)(,|$)', 1, 1, 'i', 1);
V_PATTERN := REGEXP_SUBSTR(V_LINE, '([^,\(]*(\([^\)]*\)[^,\(]*)*)(,|$)', 1, 2, 'i', 1);
V_REMARK := REGEXP_SUBSTR(V_LINE, '([^,\(]*(\([^\)]*\)[^,\(]*)*)(,|$)', 1, 12, 'i', 1);
V_CREATED_BY := REGEXP_SUBSTR(V_LINE, '([^,\(]*(\([^\)]*\)[^,\(]*)*)(,|$)', 1, 13, 'i', 1);
V_CREATED_DATE := REGEXP_SUBSTR(V_LINE, '([^,\(]*(\([^\)]*\)[^,\(]*)*)(,|$)', 1, 14, 'i', 1);
V_MODIFIED_BY := REGEXP_SUBSTR(V_LINE, '([^,\(]*(\([^\)]*\)[^,\(]*)*)(,|$)', 1, 15, 'i', 1);
V_MODIFIED_DATE := REGEXP_SUBSTR(V_LINE, '([^,\(]*(\([^\)]*\)[^,\(]*)*)(,|$)', 1, 16, 'i', 1);
INSERT INTO PRODUCT_TBL (PRD_ID,PATTERN,REMARK,CREATED_BY,CREATED_DATE,MODIFIED_BY,MODIFIED_DATE)
VALUES(V_PRD_ID, V_PATTERN, V_REMARK, V_CREATED_BY, V_CREATED_DATE, V_MODIFIED_BY, V_MODIFIED_DATE);
EXCEPTION
WHEN OTHERS THEN
ROLLBACK;
v_error_code := SQLCODE;
v_error_message := SQLERRM;
dbms_output.put_line(v_error_code || SQLERRM);
EXIT;
END;
END LOOP;
COMMIT;
UTL_FILE.FCLOSE(F);
EXCEPTION
WHEN UTL_FILE.INVALID_OPERATION THEN
UTL_FILE.FCLOSE(F);
dbms_output.put_line('File could not be opened or operated on as requested.');
END;
/

add an EXCEPTION ... OTHER Block after the UTL_FILE part and see what kind of Exceptions actually go throuhg to catch them.
EXCEPTION
WHEN UTL_FILE.INVALID_OPERATION THEN
UTL_FILE.FCLOSE(F);
dbms_output.put_line('File could not be opened or operated on as requested.');
WHEN OTHERS THEN
dbms_output.put_line('other trouble'||SQLCODE||SQLERRM);
When you know which one happened you will know how to catch it.

Related

Before insert trigger doesn't change column value

I have this simple trigger, which should change the data before insert.
CREATE OR REPLACE function product_fts_create_trg() returns TRIGGER AS $$
BEGIN
new.name := 'example';
return new;
end
$$ LANGUAGE 'plpgsql';
CREATE TRIGGER "product_fts_create_trigger" BEFORE INSERT ON "productmodel" FOR EACH ROW EXECUTE procedure product_fts_create_trg();
But it doesn't change column value. I thought, that this trigger doesn't processed, but if i change new.name to null (this column has a not null constraint), i got a error, which indicates, that trigger are works.
I use Tortoise ORM with sql query down below (i guess that this didn't ruin trigger, but mb it will be useful for discussion)
INSERT INTO "productmodel" ("id","created_at","modified_at","deleted","deleted_at","fts","name","short_description","long_description","price","old_price","currency","status","weight","length","width","height","count_available","address","text_verification","product_verified","delivery_types","delivery_payed_by","user_id","video_id","video_verification_id") VALUES ($1,$2,$3,$4,$5,$6,$7,$8,$9,$10,$11,$12,$13,$14,$15,$16,$17,$18,$19,$20,$21,$22,$23,$24,$25,$26): ['41ab62f0-1cab-47b5-a360-fcc9fbaf3b69', datetime.datetime(2022, 11, 1, 9, 39, 33, 360691, tzinfo=<UTC>), datetime.datetime(2022, 11, 1, 9, 39, 33, 360713, tzinfo=<UTC>), False, None, None, 'Iphone 20', None, None, 100.0, 100.0, 'rub', 'review', None, None, None, None, 0, None, None, False, '["pickpoint"]', 'self-delivery', 3, None, None]
Very interesting that I have BEFORE UPDATE trigger and it works.
create function product_fts_trg() returns trigger
language plpgsql
as
$$
BEGIN
if old.name <> new.name or old.short_description <> new.short_description or old.long_description <> new.long_description
then new.fts := 'example';
end if;
RETURN new;
end
$$;
alter function product_fts_trg() owner to vlad;

While loop doesn't exit when eof is detected

I'm having troubles with the eof sequence at the while loop. Basically I have to read a txt file (sequence) and each character has a different character that will be printed on an exit.txt file. But my while loop doesn't recognize the eof. Here's my code.
program LaboratorioPascal;
uses crt;
var
sec, sal: Textfile;
v: char;
por_especial, cont_palabra, cont_caracter, cont_especial: integer;
vocales2: set of char;
pares: set of char;
impares: set of char;
consonantes: set of char;
consonantes2: set of char;
procedure numeros(var x: char);
begin
case x of
'0': Write(sal, '0');
'1': Write(sal, '1');
'2': Write(sal, '4');
'3': begin
Write(sal, '2');
Write(sal, '7');
end;
'4': Write(sal, '8');
'5': begin
Write(sal, '1');
Write(sal, '2');
Write(sal, '5');
end;
'6': begin
Write(sal, '1');
Write(sal, '2');
end;
'7': begin
Write(sal, '3');
Write(sal, '4');
Write(sal, '3');
end;
'8': begin
Write(sal, '1');
Write(sal, '6');
end;
'9': begin
Write(sal, '7');
Write(sal, '2');
Write(sal, '9');
end;
else Exit;
end;
end;
function vocales(var s: char): char;
begin
case s of
'e': vocales := 'u';
'a': vocales := 'o';
'i': vocales := 'a';
'o': vocales := 'e';
else vocales := 'i';
end;
end;
begin
assign(sec, 'input.txt'); // Le asignamos un archivo del cual lea
reset(sec); // arrancamos la secuencia
read(sec, v); // leemos la secuencia. avz(sec, v)
assign(sal, 'salida.txt');
rewrite(sal);
vocales2 := ['a', 'e', 'i', 'o', 'u'];
pares := ['0', '2', '4', '6', '8'];
impares := ['1', '3', '5', '7', '9'];
consonantes := ['b', 'c', 'd', 'f', 'g', 'h', 'j','k','l','m', 'n'];
consonantes2 := ['p', 'q', 'r', 's', 't', 'v', 'w', 'x', 'y', 'z'];
por_especial := 0;
cont_palabra := 0;
cont_caracter := 0;
cont_especial := 0;
writeln('El objetivo de este programa es cifrar un mensaje para favorecer a la inteligencia Rusa.');
while not eof(sec) do
begin
while v = ' ' do
begin
write(sal, ' ');
read(sec, v);
end;
cont_palabra := cont_palabra + 1;
while v <> ' ' do
begin
if (v in consonantes) or (v in consonantes2) then
begin
write(sal, '1');
end
else
begin
if v in vocales2 then
begin
Write(sal, vocales(v));
end
else
begin
if v in pares then;
begin
numeros(v);
end;
begin
if v in impares then
begin
numeros(v);
end
else
begin
cont_especial := cont_especial + 1;
Write(sal, '#');
end;
end;
end;
end;
read(sec, v);
end;
end;
write(cont_palabra, ' se crifraon con [Exito]');
close(sec);
close(sal);
end.
But the result I have in the exit file (salida.txt) is
1o1ao i1o 1u1 i1 1e1111ie 1iu 1u 1e1ae o i1o 11a11u1o### 1a1########################################################################################################################################################################################################
I've done my research about the eof topic, but I can't find anything about pascal. And if I try to put an
if eof then
Exit;
end;
inside the while loop, and it just read one character from the input.txt file.
The problem is that you are in the inner loop ("while v <> ' ' do") when you come to the end of your input file.
If the last character in the input file is a space, you jump out of the inner loop and out of the outer loop, because you reached eof.
But if it isn't, you stay in the inner loop, and keep reading beyond the eof, until you encounter a space or a problem.
You can change the inner loop's
"while v <> ' ' do"
to
"while (v <> ' ') and (not eof(sec)) do".
Or make it one loop and handle the space in an if statement.

Get values after and before specific character in SQL/PL SQL?

I have a string value as a parameter and I need to parse it. My value is :
param := ('1234#5432#4567#8763');
I have to get 1234, 5432, 4567 and 8763 values partially. I will set these values different parameters.
How can I solve it with SQL?
Thanks,
select level, regexp_substr(a,'\d+',1,level)
from(select '1234#5432#4567#8763' a from dual)
connect by level <= regexp_count(a,'#') + 1
Assuming that you are in PL/SQL and you need to split a value of a parameter or a variable into four variables, this could be a way:
declare
param varchar2(100);
param1 varchar2(100);
param2 varchar2(100);
param3 varchar2(100);
param4 varchar2(100);
begin
param := '1234#5432#4567#8763';
--
param1 := substr(param, 1, instr(param, '#', 1, 1)-1);
param2 := substr(param, instr(param, '#', 1, 1) +1 , instr(param, '#', 1, 2) - instr(param, '#', 1, 1)-1);
param3 := substr(param, instr(param, '#', 1, 2) +1 , instr(param, '#', 1, 3) - instr(param, '#', 1, 2)-1);
param4 := substr(param, instr(param, '#', 1, 3) +1 );
--
dbms_output.put_line('Param1: ' || param1);
dbms_output.put_line('Param2: ' || param2);
dbms_output.put_line('Param3: ' || param3);
dbms_output.put_line('Param4: ' || param4);
end;
With regular expressions, you can get the same result by searching the 1st, 2nd, ... occurrence of a string that is followed by a # or by the end of the line ('$'); a better explanation of this approach is described in the link gave by Gary_W in his comment
...
param1 := regexp_substr(param, '(.*?)(#|$)', 1, 1, '', 1 );
param2 := regexp_substr(param, '(.*?)(#|$)', 1, 2, '', 1 );
param3 := regexp_substr(param, '(.*?)(#|$)', 1, 3, '', 1 );
param4 := regexp_substr(param, '(.*?)(#|$)', 1, 4, '', 1 );
...

Pandas HDFStore strange behaviour on shape

i am facing this strange behaviour, i got a HDFStore containing DataFrames.
For 2 keys in the store , shape information differs depending how they are query.
Example:
In [1]: mystore = pandas.HDFStore('/store')
In [2]: mystore
Out[2]:
<class 'pandas.io.pytables.HDFStore'>
File path: /store
/chunk_data frame (shape->[1,1])
/enrich_data_kb frame (shape->[1,11])
/inputs frame (shape->[105,4])
/prepare_data frame (shape->[105,7])
/reduce_data frame (shape->[18,4])
In [3]: mystore['chunk_data'].shape
Out[3]: (0, 1)
In [4]: mystore['enrich_data_kb'].shape
Out[4]: (18, 11)
In [5]: mystore['inputs'].shape
Out[5]: (105, 4)
Any Idea ?
As Jeff suggest, here is the result of ptdump (restricted to enrich_data_kb key):
/enrich_data_kb (Group) ''
/enrich_data_kb._v_attrs (AttributeSet), 13 attributes:
[CLASS := 'GROUP',
TITLE := '',
VERSION := '1.0',
axis0_variety := 'regular',
axis1_variety := 'regular',
block0_items_variety := 'regular',
block1_items_variety := 'regular',
block2_items_variety := 'regular',
encoding := None,
nblocks := 3,
ndim := 2,
pandas_type := 'frame',
pandas_version := '0.15.2']
/enrich_data_kb/axis0 (Array(11,)) ''
atom := StringAtom(itemsize=10, shape=(), dflt='')
maindim := 0
flavor := 'numpy'
byteorder := 'irrelevant'
chunkshape := None
/enrich_data_kb/axis0._v_attrs (AttributeSet), 7 attributes:
[CLASS := 'ARRAY',
FLAVOR := 'numpy',
TITLE := '',
VERSION := '2.4',
kind := 'string',
name := None,
transposed := True]
/enrich_data_kb/axis1 (Array(18,)) ''
atom := Int64Atom(shape=(), dflt=0)
maindim := 0
flavor := 'numpy'
byteorder := 'little'
chunkshape := None
/enrich_data_kb/axis1._v_attrs (AttributeSet), 7 attributes:
[CLASS := 'ARRAY',
FLAVOR := 'numpy',
TITLE := '',
VERSION := '2.4',
kind := 'integer',
name := None,
transposed := True]
/enrich_data_kb/block0_items (Array(8,)) ''
atom := StringAtom(itemsize=10, shape=(), dflt='')
maindim := 0
flavor := 'numpy'
byteorder := 'irrelevant'
chunkshape := None
/enrich_data_kb/block0_items._v_attrs (AttributeSet), 8 attributes:
[CLASS := 'ARRAY',
FLAVOR := 'numpy',
TITLE := '',
VERSION := '2.4',
freq := None,
kind := 'string',
name := None,
transposed := True]
/enrich_data_kb/block0_values (VLArray(1,)) ''
atom = ObjectAtom()
byteorder = 'irrelevant'
nrows = 1
flavor = 'numpy'
/enrich_data_kb/block0_values._v_attrs (AttributeSet), 5 attributes:
[CLASS := 'VLARRAY',
PSEUDOATOM := 'object',
TITLE := '',
VERSION := '1.4',
transposed := True]
/enrich_data_kb/block1_items (Array(2,)) ''
atom := StringAtom(itemsize=10, shape=(), dflt='')
maindim := 0
flavor := 'numpy'
byteorder := 'irrelevant'
chunkshape := None
/enrich_data_kb/block1_items._v_attrs (AttributeSet), 8 attributes:
[CLASS := 'ARRAY',
FLAVOR := 'numpy',
TITLE := '',
VERSION := '2.4',
freq := None,
kind := 'string',
name := None,
transposed := True]
/enrich_data_kb/block1_values (Array(18, 2)) ''
atom := Float64Atom(shape=(), dflt=0.0)
maindim := 0
flavor := 'numpy'
byteorder := 'little'
chunkshape := None
/enrich_data_kb/block1_values._v_attrs (AttributeSet), 5 attributes:
[CLASS := 'ARRAY',
FLAVOR := 'numpy',
TITLE := '',
VERSION := '2.4',
transposed := True]
/enrich_data_kb/block2_items (Array(1,)) ''
atom := StringAtom(itemsize=8, shape=(), dflt='')
maindim := 0
flavor := 'numpy'
byteorder := 'irrelevant'
chunkshape := None
/enrich_data_kb/block2_items._v_attrs (AttributeSet), 8 attributes:
[CLASS := 'ARRAY',
FLAVOR := 'numpy',
TITLE := '',
VERSION := '2.4',
freq := None,
kind := 'string',
name := None,
transposed := True]
/enrich_data_kb/block2_values (Array(18, 1)) ''
atom := Int64Atom(shape=(), dflt=0)
maindim := 0
flavor := 'numpy'
byteorder := 'little'
chunkshape := None
/enrich_data_kb/block2_values._v_attrs (AttributeSet), 5 attributes:
[CLASS := 'ARRAY',
FLAVOR := 'numpy',
TITLE := '',
VERSION := '2.4',
transposed := True]

Line pieces in Tee chart lite XE5

I'm trying to create this type of graph in Delphi XE5 with teechart lite:
So I have points (x1,y1),(x2,y2), ....,(xk,yk).
Points (x1,y1), (x2,y2) form line piece no. 1.
The second line piece is (x3,y3), (x4,y4) and so on. Note that (x2,y2) is different than (x3,y3) they are not the same point.
With the tee chart lite is it possible to create such a graph in XE5?
There are different options to do this with TeeChart.
One series and null points. You can add a null point after each segment so the lines in your series won't be connected. Ie:
uses Series;
procedure TForm1.FormCreate(Sender: TObject);
procedure AddSegment(Series: TChartSeries; X0, Y0, X1, Y1: Double);
begin
Series.AddXY(X0, Y0);
Series.AddXY(X1, Y1);
Series.AddNullXY(X1, Y1);
end;
var fastLine1: TFastLineSeries;
begin
Chart1.View3D:=false;
fastLine1:=Chart1.AddSeries(TFastLineSeries) as TFastLineSeries;
fastLine1.TreatNulls:=tnDontPaint;
AddSegment(fastLine1, 0, 1, 1, 2);
AddSegment(fastLine1, 2, 1, 3, 0);
AddSegment(fastLine1, 4, 2, 5, 3);
end;
Multiple series.. You can have a series for each segment. Ie:
uses Series;
procedure TForm1.FormCreate(Sender: TObject);
procedure AddSegment(Chart: TChart; X0, Y0, X1, Y1: Double);
begin
with Chart.AddSeries(TFastLineSeries) do
begin
AddXY(X0, Y0);
AddXY(X1, Y1);
Color:=Chart[0].Color;
end;
end;
begin
Chart1.View3D:=false;
AddSegment(Chart1, 0, 1, 1, 2);
AddSegment(Chart1, 2, 1, 3, 0);
AddSegment(Chart1, 4, 2, 5, 3);
end;
A DrawLineTool. This tool allows you to draw line segments directly with the mouse, or add them by code. Ie:
uses Series, TeeTools;
procedure TForm1.FormCreate(Sender: TObject);
procedure AddSegment(tool: TDrawLineTool; X0, Y0, X1, Y1: Double);
begin
tool.Lines.AddLine(X0, Y0, X1, Y1);
end;
var drawLineTool1: TDrawLineTool;
begin
Chart1.View3D:=false;
Chart1.Axes.Bottom.SetMinMax(0, 5);
Chart1.Axes.Left.SetMinMax(0, 3);
Chart1.AddSeries(TFastLineSeries);
drawLineTool1:=Chart1.Tools.Add(TDrawLineTool) as TDrawLineTool;
AddSegment(drawLineTool1, 0, 1, 1, 2);
AddSegment(drawLineTool1, 2, 1, 3, 0);
AddSegment(drawLineTool1, 4, 2, 5, 3);
end;