Delete tuple from libpq’s PGresult

I wrote how to modify result set in underlying libpq’s PGresult object with new ones.

But there was no solution for deletion. Here I want to propose one solution. The main idea is to copy existing PGresult content to the new record except deleted tuple. For this we will use PQcopyResult function. Delphi code looks like this:

var 
  CurrentRecNum: LongInt;
  DeletedRecNum: LongInt;
  ATempCopyStmt: PGResult;
  fval: PAnsiChar;
  flen, i, j: integer;

...
     //FStatement - is our active result set
     ATempCopyStmt := PQcopyResult(FStatement, PG_COPYRES_ATTRS);
     if not Assigned(ATempCopyStmt) then
       raise Exception.Create('Cannot copy results');
     j := 0;
     for CurrentRecNum := 0 to PQntuples(FStatement) - 1 do
      begin
       if CurrentRecNum = DeletedRecNum then 
          Continue; //exclude row from new set
       for i := 0 to PQnfields(FStatement) - 1 do
         begin
           fval := PQgetvalue(FStatement, j, i);
           flen := PQgetlength(FStatement, j, i);
           if PQsetvalue(ATempCopyStmt, j, i, fval, flen) = 0 then
             raise Exception.Create('Refresh for deleted fiels failed');
         end;
       inc(j);
      end;
     PQclear(FStatement); //clear old result set 
     FStatement := ATempCopyStmt; //switch to the new
...
Advertisements