Delphi table Join - sql-server

I’ve been tasked with patching a Delphi software to work with a new database(mssql) structure.
In the previous database(mssql), all the columns being read were in the same table.
In the new version the file_name and class_name are in a different table as the quantity values.
I believe I can fix this by writing a Join for these two database tables.
Issue is, I’m not familiar with Delphi!
The current code is below.
How do I get these two databases to join into one?
dataTable=style001
dataTable1=style
THANKS!!!
dataTable.Active := True;
datatable.Open;
dataTable1.Active := True;
datatable1.Open;
while not datatable1.Eof do
begin
Application.ProcessMessages;
file_name := trim(datatable1.FieldByName('code').asString) + '.jpg';
class_name := trim(datatable1.FieldByName('category').asString);
if not FileExists(picfolder + file_name) then
begin
dataTable1.next;
continue;
end;
instock := datatable.FieldByName('onhand').asString;
TryStrToInt(instock, instock_num);
quantity := datatable.FieldByName('onorder').asString;
TryStrToInt(quantity, num);
num := instock_num - num;
is_active := ( num > 10 );
for i := 0 to file_count-1 do
begin
if is_active = active_class[file_class[i]] then
if SameText(files[i],file_name) then
begin // use TStringList instead
if SameText(class_name, classes[file_class[i]]) then // same class
begin
file_ok[i] := true;
class_ok[file_class[i]] := true;
end;
break;
end;
end;
if class_name <> '' then class_name := class_name + '\';
dest := picfolder + active_path[is_active] + class_name;
deldest := picfolder + active_path[not is_active] + class_name;
{$I-}
if FileExists(deldest + file_name) then
DeleteFile(PChar(deldest + file_name ));
if not FileExists(dest + file_name) then
begin
ForceDirectories(dest);
CopyFile(PChar(picfolder + file_name ), PChar(dest + file_name ), true );
end;
dataTable1.next;
end;
for i := 0 to file_count-1 do
if not file_ok[i] then
begin // delete wrong file if empty
// ShowMessage('problem: ' + picfolder + active_path[active_class[file_class[i]]] + classes[file_class[i]] + '\' + files[i]);
DeleteFile(picfolder + active_path[active_class[file_class[i]]] + classes[file_class[i]] + '\' + files[i]);
end;
for i := 0 to class_count-1 do
if not class_ok[i] then
begin // delete old class if empty
// ShowMessage('problem: ' + picfolder + active_path[active_class[i]] + classes[i] + '\' );
RemoveDir(picfolder + active_path[active_class[i]] + classes[i] + '\' );
end;
beep;
dataTable.Active := False;
dataTable1.Active := False;

The JOIN is inside the SQL request, not the consuming loop code you are showing here.
You have to use a TQuery instead of two TTable, and write a SQL select for joining the two tables.
You have to modify the SQL request, add the two tables in the FROM clause of the SELECT, and a JOINture in the WHERE clause. See this article about JOIN.

Use a TDataSource and connect its DataSet property to one of the tables. Then set the MasterSource property of the other table to that datasource. Click on the ellipsis button of the MasterFields property and select the connecting fields.
Assuming that the style fields are unique, when you navigate through the first table the second one will follow automatically.

Related

Eof not triggering

I have a function where I get data from a DB, my test data set returns 6500 rows (I extracted the formatted SQL statement from the SQLText Variable and ran it as a test), but then when I run the following code Eof never triggers and I have seen over 100k rows imported.
ADOQuery := TADOQuery.Create(nil);
ADOQuery.ConnectionString := CONNECT_STRING;
// Build SQL Query
SQLText := Format( 'Select Temp.Serial, Temp.QCSample , Temp.Scrap , Temp.StationID , Temp.Defect , Temp.AddData , Temp2.Serial as Parent_Serial ' +
'from TAB_ELEMENT as Temp ' +
'left join TAB_ELEMENT as Temp2 on Temp.Parent_Id = Temp2.Element_Id ' +
'where Temp.Batch_ID = %d and Temp.StationID = 0 ',[iSearchID]);
ADOQuery.SQL.Clear; // Clear query of garbage values
ADOQuery.SQL.Text := SQLText; // Add query text to query module
ADOQuery.Open;
// Handle Results
iIndexPos := 0;
tDataImport.BeginUpdate;
while not ADOQuery.Eof do
begin
tDataImport.Items[iIndexPos].Serial := ADOQuery.FieldByName('Serial').AsString;
tDataImport.Items[iIndexPos].QCStatus := ADOQuery.FieldByName('QCSample').AsBoolean;
tDataImport.Items[iIndexPos].Scrap := ADOQuery.FieldByName('Scrap').AsInteger;
tDataImport.Items[iIndexPos].StationID := ADOQuery.FieldByName('StationID').AsInteger;
tDataImport.Items[iIndexPos].Defect := ADOQuery.FieldByName('Defect').AsBoolean;
tDataImport.Items[iIndexPos].AddData := ADOQuery.FieldByName('AddData').AsString;
tDataImport.Items[iIndexPos].ParentSerial := ADOQuery.FieldByName('Parent_Serial').AsString;
inc(iIndexPos);
end;
So in summery running this query with these parameters I expect 6500 rows, when I run this it never ends even after 100k+ rows are processed.
Open() places the cursor on the first record and sets Eof accordingly. You are not calling Next() to advance the cursor to the next record and update Eof, so you are processing the same record over and over:
ADOQuery.Open;
while not ADOQuery.Eof do
begin
//...
ADOQuery.Next; // <-- add this!
end;
On a side note, you should be using a parameterized query instead of a formatted SQL query string. It is safer, faster, and more efficient on the DB:
ADOQuery := TADOQuery.Create(nil);
ADOQuery.ConnectionString := CONNECT_STRING;
ADOQuery.SQL.Text := 'Select Temp.Serial, Temp.QCSample , Temp.Scrap , Temp.StationID , Temp.Defect , Temp.AddData , Temp2.Serial as Parent_Serial ' +
'from TAB_ELEMENT as Temp ' +
'left join TAB_ELEMENT as Temp2 on Temp.Parent_Id = Temp2.Element_Id ' +
'where Temp.Batch_ID = :iSearchID and Temp.StationID = 0 ';
with ADOQuery.Parameters.ParamByName('iSearchID') do
begin
DataType := ftInteger;
Value := iSearchID;
end;
ADOQuery.Open;
try
iIndexPos := 0;
tDataImport.BeginUpdate;
try
while not ADOQuery.Eof do
begin
tDataImport.Items[iIndexPos].Serial := ADOQuery.FieldByName('Serial').AsString;
tDataImport.Items[iIndexPos].QCStatus := ADOQuery.FieldByName('QCSample').AsBoolean;
tDataImport.Items[iIndexPos].Scrap := ADOQuery.FieldByName('Scrap').AsInteger;
tDataImport.Items[iIndexPos].StationID := ADOQuery.FieldByName('StationID').AsInteger;
tDataImport.Items[iIndexPos].Defect := ADOQuery.FieldByName('Defect').AsBoolean;
tDataImport.Items[iIndexPos].AddData := ADOQuery.FieldByName('AddData').AsString;
tDataImport.Items[iIndexPos].ParentSerial := ADOQuery.FieldByName('Parent_Serial').AsString;
inc(iIndexPos);
ADOQuery.Next;
finally
tDataImport.EndUpdate;
end;
end;
finally
ADOQuery.Close;
end;

How can I display only specified database results based on TListbox items?

I have two forms: frmMakeQuote and frmQuoteTemp
In the frmMakeQuote there are two TListboxes: lboMtrlList and lboSelectedMtrl
lboMtrlList displays the Product Description column from the database.
procedure TfrmMakeQuote.FormCreate(Sender: TObject);
begin
con := TFDConnection.Create(nil);
query := TFDQuery.Create(con);
con.LoginPrompt := false;
con.Open('DriverID=SQLite;Database=C:\Users\kasio\Documents\Embarcadero\' +
'Studio\Projects\ProgramDatabase;');
query.Connection := con;
query.SQL.Text :=
'SELECT [Material Description] FROM MtrlDatabase ORDER BY MtrlID';
try
query.Open;
lboMtrlList.Items.Clear;
while not query.EOF do
begin
lboMtrlList.Items.Add(query.Fields[0].AsString);
query.Next;
end;
finally
query.Close;
end;
end;
When the person double clicks on any 'product' in the lboMtrlList, it's moved to the lboSelectedMtrl. (Basically, it shows the selected 'products'.)
procedure TfrmMakeQuote.lboMtrlListDblClick(Sender: TObject);
begin
lboSelectedMtrl.Items.Add(lboMtrlList.Items.Strings[lboMtrlList.ItemIndex]);
end;
I want to be able to display the Product Description and Price columns from the database, of ONLY the selected 'products' from the lboSelectedMtrl. They should be displayed in the TStringGrid called sgdMaterials on the frmQuoteTemp.
I wrote something like this:
procedure TfrmMakeQuote.performMtrlQuery;
var
i: integer;
begin
for i := 1 to frmMakeQuote.lboSelectedMtrl.ItemIndex do
begin
query.SQL.Text := 'SELECT [Material Description], Price FROM MtrlDatabase ' +
'WHERE [Material Description] = "'
+ frmMakeQuote.lboSelectedMtrl.Items.Strings[1]
+ '" ORDER BY MtrlID';
query.Open;
query.First;
end;
end;
It doesn't show any error, but it doesn't work and displays nothing and I'm aware that it's probably completely wrong.
Your loop inside of performMtrlQuery() is wrong. If nothing is actually selected in lboSelectedMtrl, its ItemIndex will be -1 and the loop will not iterate through any items. Not only that, but even if an item were selected, your loop would not iterate through ALL of the available items. Also, when you are indexing into the Strings[] property, you are using a hard-coded 1 instead of the loop variable i.
As for your TStringGrid, why not use a TDBGrid instead, and tie it to a DataSource that is filtering the database by the desired items? In any case, performMtrlQuery() is not doing anything to populate the grid at all, whether it is to store the search results in the grid directly, or to store the results in a list somewhere that frmQuoteTemp can then read from.
Try this instead:
procedure TfrmMakeQuote.performMtrlQuery;
var
i: integer;
begin
for i := 0 to frmMakeQuote.lboSelectedMtrl.Items.Count-1 do
begin
query.SQL.Text := 'SELECT [Material Description], Price FROM MtrlDatabase' +
' WHERE [Material Description] = "'
+ frmMakeQuote.lboSelectedMtrl.Items.Strings[i]
+ '" ORDER BY MtrlID';
query.Open;
query.First;
// do something with query.Fields[0] and query.Fields[1] ...
query.Close;
end;
end;
That being said, searching your materials by their descriptions is not the most efficient search option. You should search by their IDs instead. I would suggest an alternative approach to accomplish that - use your TListBox controls in virtual mode (Style=lbVirtual) instead, and store your search results in separate TStringList objects. That way you can store both IDs and Descriptions together in memory while displaying the descriptions in the UI and using the IDs in queries.
Try something more like this:
procedure TfrmMakeQuote.FormCreate(Sender: TObject);
begin
allmaterials := TStringList.Create;
selectedmaterials := TStringList.Create;
con := TFDConnection.Create(Self);
con.LoginPrompt := false;
con.Open('DriverID=SQLite;Database=C:\Users\kasio\Documents\Embarcadero\Studio\Projects\ProgramDatabase;');
query := TFDQuery.Create(con);
query.Connection := con;
query.SQL.Text := 'SELECT MtrlID, [Material Description] FROM MtrlDatabase ORDER BY MtrlID';
try
query.Open;
while not query.EOF do
begin
allmaterials.Add(query.Fields[0].AsString + '=' + query.Fields[1].AsString);
query.Next;
end;
finally
query.Close;
end;
lboMtrlList.Count = allmaterials.Count;
end;
procedure TfrmMakeQuote.FormDestroy(Sender: TObject);
begin
allmaterials.Free;
selectedmaterials.Free;
end;
// lboMtrlList OnData event handler
procedure TfrmMakeQuote.lboMtrlListData(Control: TWinControl; Index: Integer; var Data: string);
begin
Data := allmaterials.ValueFromIndex[Index];
end;
// lboSelectedMtrl OnData event handler
procedure TfrmMakeQuote.lboSelectedMtrlData(Control: TWinControl; Index: Integer; var Data: string);
begin
Data := selectedmaterials.ValueFromIndex[Index];
end;
procedure TfrmMakeQuote.lboMtrlListDblClick(Sender: TObject);
var
Idx: Integer;
begin
Idx := lboMtrlList.ItemIndex;
if Idx = -1 then Exit;
if selectedmaterials.IndexOfName(allmaterials.Names[Idx]) <> -1 then Exit;
selectedmaterials.Add(allmaterials.Strings[Idx]);
lboSelectedMtrl.Count := selectedmaterials.Count;
end;
procedure TfrmMakeQuote.performMtrlQuery;
var
i: integer;
begin
for i := 0 to selectedmaterials.Count-1 do
begin
query.SQL.Text := 'SELECT [Material Description], Price FROM MtrlDatabase' +
' WHERE MtrlID = '
+ selectedmaterials.Names[i];
query.Open;
query.First;
// do something with query.Fields[0] and query.Fields[1] ...
query.Close;
end;
end;
Lastly, if you switch to a single TCheckListBox or TListView control instead of 2 TListBox controls, you can take advantage of their ability to have checkboxes on each item, then you don't need to deal with the OnDblClick event anymore, and don't need to show two copies of your materials in your UI. The user can just check the desired items before invoking performMtrlQuery().
I would also suggest using a virtual TListView for the search results instead of a TStringGrid. The UI will look better (TStringGrid is not the best looking UI control), and you can utilize memory more efficiently (TStringGrid can be a memory hog if you have a lot of data to display).

Get last row data after insert into using Delphi AdoQuery

In Delphi 2007 using ADOQuery
when i add a row into a table using insert into
how do i get last row?
i'm adding row with this.
QD_TEMP1.close;
QD_TEMP1.sql.Clear;
QD_TEMP1.SQL.Add('insert into s_hasta_Kabul (Protokol,Muay_ID,Ocak_Kod,Tc_Kimlik_No) ');
QD_TEMP1.SQL.Add('values (:Protokol,:Muay_ID,:Ocak_Kod,:Tc_Kimlik_No) ');
QD_TEMP1.Parameters.ParamByName('Protokol').Value := 0;
QD_TEMP1.Parameters.ParamByName('Muay_ID').Value := 2;
QD_TEMP1.Parameters.ParamByName('Ocak_Kod').Value := 3;
QD_TEMP1.Parameters.ParamByName('Tc_Kimlik_No').Value := 4;
QD_TEMP1.ExecSQL;
How do i get last added row after execsql ?
You could use the OUTPUT clause to return the inserted recordset, whether or not you have an identity column (it seems form your comments you do not have one).
e.g.
QD_TEMP1.Close;
QD_TEMP1.sql.Clear;
QD_TEMP1.SQL.Add('insert into s_hasta_Kabul (Protokol,Muay_ID,Ocak_Kod,Tc_Kimlik_No) ');
QD_TEMP1.SQL.Add('OUTPUT inserted.*');
QD_TEMP1.SQL.Add('values (:Protokol,:Muay_ID,:Ocak_Kod,:Tc_Kimlik_No) ');
QD_TEMP1.Parameters.ParamByName('Protokol').Value := 0;
QD_TEMP1.Parameters.ParamByName('Muay_ID').Value := 2;
QD_TEMP1.Parameters.ParamByName('Ocak_Kod').Value := 3;
QD_TEMP1.Parameters.ParamByName('Tc_Kimlik_No').Value := 4;
QD_TEMP1.Open; // ExecSQL does NOT return recordset
// QD_TEMP1 now contains the inserted result set
ShowMessage(QD_TEMP1.FieldByName('Tc_Kimlik_No').AsString);
Note we use QD_TEMP1.Open (not ExecSQL) to return the inserted recordset.
It works if you set the parameter direction before "ExeSQL".
q.sql.text := 'insert into TABLE(x) values (:value) set :ID = scope_identity()';
q.Parameters.ParamByName('VALUE').value := 'XXXXX';
q.Parameters.ParamByName('ID').Direction := pdReturnValue;
q.ExecSQL;
ID := q.Parameters.ParamByName('ID').value;
Cheers
have not tested it but it should be something like this
QD_TEMP1.close;
QD_TEMP1.sql.Clear;
QD_TEMP1.SQL.Add('insert into s_hasta_Kabul (Protokol,Muay_ID,Ocak_Kod,Tc_Kimlik_No) ');
QD_TEMP1.SQL.Add('values (:Protokol,:Muay_ID,:Ocak_Kod,:Tc_Kimlik_No) SELECT :test = SCOPE_IDENTITY() ');
QD_TEMP1.Parameters.ParamByName('Protokol').Value := 0;
QD_TEMP1.Parameters.ParamByName('Muay_ID').Value := 2;
QD_TEMP1.Parameters.ParamByName('Ocak_Kod').Value := 3;
QD_TEMP1.Parameters.ParamByName('Tc_Kimlik_No').Value := 4;
QD_TEMP1.ExecSQL;
QD_TEMP1.Parameters.ParamByName('test').Value is your new id
qryTest.Close;
qryTest.SQL.Clear;
qryTest.SQL.Add(' INSERT INTO TEST_GET_IDX ');
qryTest.SQL.Add(' (SNAME, AGE) ');
qryTest.SQL.Add(' VALUES(:pSNAME, :pAGE) ' );
qryTest.SQL.Add(' SELECT IDX = SCOPE_IDENTITY() ' ); // IDX is IDENTITY
qryTest.Parameters.ParamByName('pSNAME').Value:= edSname.Text;
qryTest.Parameters.ParamByName('pAGE').Value:= edAge.Text;
qryTest.Open;
showMessage(dsTest.DataSet.FieldByName('IDX').AsString);

Initiating a SOAP Array on Delphi

I am trying to initialize or create an array of a soap call:
Array_Of_ProductIdentifierClinicalType = array of ProductIdentifierClinicalType;
This is the way that I am trying to initialize it:
Product[0].IdentifierType := Array_Of_ProductIdentifierClinicalType.Create();
When I run the application I get this error: Access Violation at address...
The question would be: How to initialize this soap call??
Thank you for your time!!!!
You can do a WSDL import on: http://axelcarreras.dyndns.biz:3434/WSAlchemy.wsdl
procedure TFrmMain.Button16Click(Sender: TObject);
Var
ExcludeExpiradas: String;
Serv: AlchemyServiceSoap;
req: AlchemyClinical;
element: AlchemyClinicalRequest;
Prescribed: PrescribedType;
//Prescribing: Prescribing
Prescribing: PrescribedType;
alc: AlchemyIdentifierType;
D: TXSDate;
Counter: Integer;
ProductStr: AlchemyIdentifierClinicalType;
begin
With DM do
begin
ExcludeExpiradas := ' and (' + chr(39) + DateToStr(Date) + chr(39) + ' < (FECHARECETA + 180)) ';
CDSRx_Procesadas.Close;
CDSRx_Procesadas.CommandText := 'SELECT * ' +
' FROM RX_PROCESADAS WHERE ' +
' (NUMERORECETA IS NOT NULL AND CANTIDAD_DISPONIBLE > 0)' +
ExcludeExpiradas +
' and NumeroCliente = ' + CDSPacientesNumeroCliente.asString +
' Order by NumeroReceta';
//ShowMessage(CDSRx_Procesadas.CommandText);
CDSRx_Procesadas.Open;
ProductStr := AlchemyIdentifierClinicalType.Create;
With ProductStr do
begin
Identifier := 1;
end;
element := AlchemyClinicalRequest.Create;
//Prescribed := PrescribedType.Create;
With element do
begin
With Prescribed do
begin
Counter := 0;
while not CDSRx_Procesadas.eof do
begin
Product := Array_Of_ProductIdentifierClinicalType.Create();
With Product[0] do
begin
IdentifierType := ProductIdentifierTypeEnum.NDC9;
Identifier := Copy(DM.CDSInventarioNDC.Value, 1, 9);
end;
Counter := Counter + 1;
CDSRx_Procesadas.Next;
end;
end;
With Prescribing do
begin
Counter := 0;
Product[0].IdentifierType := ProductIdentifierTypeEnum.AlchemyProductID;
Product[0].Identifier := Copy(DM.CDSInventarioNDC.Value, 1, 9);
Counter := Counter + 1;
end;
With PatientDemographics do
begin
while not CDSAlergies.Eof do
begin
Allergy.AllergySubstanceClass[0].Identifier := CDSAlergiesNOALERGIA.Value;
CDSAlergies.Next;
end;
if CDSPacientesSEXO.Value = 1 then
Gender := GenderTypeEnum.Male
else
Gender := GenderTypeEnum.Female;
D := TXSDate.Create;
D.AsDate := CDSPacientesFECHANACIMIENTO.AsDateTime;
DateOfBirth := D;
end;
With RequestedOperations do
begin
DrugToDrug := True;
//DuplicateTherapy
Allergy := True;
With WarningLabels do
begin
Request := True;
LanguageCode := 'en-US';
MaxLines := 5;
CharsPerLine := 24;
end;
With DoseScreening do
begin
Request := True;
end;
AdverseReactions.Request := True;
end;
IgnorePrescribed := False;
IncludeConsumerNotes := True;
IncludeProfessionalNotes := True;
end;
end;
end;*
Assuming that this line of code from the question is accurate:
Array_Of_ProductIdentifierClinicalType = array of ProductIdentifierClinicalType;
then the problem lies here:
Product := Array_Of_ProductIdentifierClinicalType.Create();
This is a dynamic array constructor. It creates a dynamic array of length equal to the number of parameters to the constructor. And then assigns each element of the array, in turn, to the parameters passed.
Consider an example using TBytes = array of Byte.
Bytes := TBytes.Create(1, 2, 3);
This initialises Bytes to be an array of length 3 and having values 1, 2 and 3.
Now, let's look at your code again. This initialises Product to be an array of length 0. So when you access Product[0] that results in a runtime error because the array index is out of bounds.
To solve the problem you will need to make sure that the array is initialised to have sufficient elements. One option is certainly to use a dynamic array constructor. Another is to use SetLength. I suspect that your understanding of Delphi's dynamic arrays is poor. I suggest that you consult the documentation.

PostgreSQL - Dynamic Tables, insert values from Text array in a function

A client wants to store anything in seperate tables. (Long story, it's nescessary).
To do this, i've build an Postgres function to create new tables on the fly in it's own namespace.
These tables can have 2, 4, or 100 columns, just what the user wants.
No problem, this works. The used datatypes in these dynamic tables are native, e.g. text, booleans, integers, etcetera.
Now comes the problem, i've got to insert data into these tables. The point is, the users can not access the tables directly, they'll do this through a function.
For a couple of datatypes is this not a problem, but for the text datatypes it's problematic.
Here is the function till now:
-- Function: add(integer, text[])
-- DROP FUNCTION add(integer, text[]);
CREATE OR REPLACE FUNCTION add(id integer, fields text[])
RETURNS integer AS
$BODY$
DECLARE
l_line_ending text := ')';
l_fieldtype integer;
l_ito_table_name text;
l_ito_fieldnames text;
l_field ito_fields%rowtype;
l_first_loop boolean := true;
l_values_to_insert text := 'VALUES (';
l_loop_counter integer := 0;
l_query text;
BEGIN
select into l_ito_table_name ito_table_name from ito where id = target_ito_id;
l_ito_fieldnames := 'insert into ' || l_ito_table_name || '(';
FOR l_field IN SELECT * FROM ito_fields
WHERE ito_fields.ito_id = target_ito_id
order by ito_fields.id asc
LOOP
l_loop_counter := l_loop_counter +1;
l_fieldtype := l_field.fieldtype;
if not l_first_loop THEN
l_values_to_insert := (l_values_to_insert || ', ');
end if;
if l_field.fieldtype = 1 THEN
l_values_to_insert := (l_values_to_insert || '''' || (fields[l_loop_counter]) || '''' );
elsif l_field.fieldtype = 2 THEN
l_values_to_insert := quote_literal(l_values_to_insert || private.cast_to_integer(fields[l_loop_counter]));
elsif l_field.fieldtype = 3 THEN
l_values_to_insert := quote_literal(l_values_to_insert || private.cast_to_boolean(fields[l_loop_counter]));
elsif l_field.fieldtype = 4 THEN
l_values_to_insert := quote_literal(l_values_to_insert || private.cast_to_float(fields[l_loop_counter]));
else
return 103;
end if;
if l_first_loop then
l_ito_fieldnames := l_ito_fieldnames || l_field.column_name;
l_first_loop := false;
else
l_ito_fieldnames := l_ito_fieldnames || ', ' || l_field.column_name;
end if;
END LOOP;
l_ito_fieldnames := l_ito_fieldnames || l_line_ending;
l_values_to_insert := ((l_values_to_insert) || (l_line_ending));
l_query := (l_ito_fieldnames || l_values_to_insert);
EXECUTE l_query;
return 0;
END;
$BODY$
LANGUAGE plpgsql VOLATILE
COST 100;
ALTER FUNCTION add(integer, text[])
OWNER TO postgres;
The table ito_fields stores all the field metadata, so the datatype, versions, descriptions are stored here.
the ito table stores all the dynamic table data.
The point in this function are the quotes. The insert function is created dynamicly, therefore i've got to add some quotes around the text fields in the insert function.
Postgres is giving errors as soon as i do that. Even with the quote_literal functions it's still a problem, because of the string concatenation (i know, security risks, but that's no problem for now).
I've tried to use quote_literal, quote_ident, even replacing the quotes (') with a replacement, until the execute function (replace(query, l_quote_rep, '''').. I really don't have a clue now how to fix this...
Thanks in advance.
Arrays, aggregates, quote_ident and quote_nullable are your friends.
This should work, and code is shorter:
CREATE OR REPLACE FUNCTION add(id integer, fields text[])
RETURNS integer AS
$BODY$
DECLARE
l_ito_table_name text;
l_query text;
l_fields text;
r_values text;
BEGIN
--get table name
SELECT INTO l_ito_table_name quote_ident(ito_table_name) FROM ito WHERE id = target_ito_id;
-- get column names
SELECT INTO l_fields
array_to_string( array_agg(quote_ident(column_name)), ',' )
FROM ito_fields
WHERE ito_fields.ito_id = target_ito_id
order by ito_fields.id asc;
-- prepare values
SELECT INTO r_values
array_to_string( array_agg(quote_nullable(u.name)), ',' )
FROM unnest(fields) u(name);
l_query := 'insert into ' || l_ito_table_name || '(' || l_fields || ') values (' || r_values || ')';
EXECUTE l_query;
return 0; -- why 0?
END;
$BODY$;

Resources