Friday, February 3, 2012

Deleting a row

Deleting a row from a table through the input label is simple: send a rowop with OP_DELETE, it will find the row and delete it. That's not even interesting for an example: same code as for the insert, different opcode. In the procedural way the same can be done with the method deleteRow(). The added code for "Hello, table" is:

    elsif ($data[0] =~ /^delete$/i) {
      my $res = $tCount->deleteRow($rtCount->makeRowHash(
        address => $data[1],
      ));
      die "$!" unless defined $res;
      print("Address '", $data[1], "' is not found\n") unless $res;
    }

The result allows to differentiate between 3 cases: row found and deleted (1), row not found (0), a grossly misformatted call (undef). If the absence of the row doesn't matter, it could be written in an one-liner form:

die "$!" unless defined $tCount->deleteRow(...);

However we already find the row handle in advance. For this case a more efficient form is available:

    elsif ($data[0] =~ /^remove$/i) {
      if (!$rhFound->isNull()) {
        $tCount->remove($rhFound) or die "$!";
      } else {
        print("Address '", $data[1], "' is not found\n");
      }
    }

It removes a specific row handle from the table. In whichever way you find it, you can remove it. Removing a NULL handle would be an error.

After a handle is removed from the table, it continues to exist, as long as there are references to it. It could even be inserted back into the table. However until (and unless) it's inserted back, it can not be used for iteration any more. Calling $table->next() on a handle that is not in the table would just return a NULL handle.

So, as an example, here is the implementation of the command "clear" for "Hello, table" that clears all the table contents:

    elsif ($data[0] =~ /^clear$/i) {
      my $rhi = $tCount->begin(); 
      while (!$rhi->isNull()) {
        my $rhnext = $tCount->next($rhi);
        $tCount->remove($rhi) or die("$!");
        $rhi = $rhnext;
      }     
    }

Note that it first remembers the next row for iteration and only then removes the current row.

There isn't any method to delete multiple rows at once. Every row has to be deleted by itself. Though of course nothing prevents anyone from writing a function  that would delete multiple or all rows. Such library functions will grow over time.

No comments:

Post a Comment