The padcounter.cpp sample program

The padcounter.cpp sample program contains two UDFs, padcounter() and getpadcount(), which use a SPUPad to obtain a row count of a table.

This example uses getFilePad() to create the SPUPad in file-backed memory.

#include "udxinc.h"

/*
* These functions obtain a row count of a table using a simple SPUPad.
*
* To compile and register the functions:
*
* nzudxcompile padcounter.cpp --sig "padcounter()" --ret int4 
*              --class PadCounter

* then alter function padcounter() to make it NOT DETERMINISTIC
*
* nzudxcompile padcounter.cpp --sig "getpadcount()" --ret int8 
*              --class GetPadCount
*  then alter function getpadcount() to make it NOT DETERMINISTIC
*
* You need a table with 1 row per SPU; for example: one_per;
*
* This will return the row count in table <TBL>:
*  select sum(getpadcount()) from one_per where exists 
*    (select count(padcounter()) from <TBL>);
*/

using namespace nz::udx;

struct Root
{
  int64 myCount;
};

class PadCounter: public Udf
{
private:

public:
  static Udf* instantiate();
  virtual ReturnValue evaluate()
  {
   CPad* pad = getFilePad("PadCount");
   Root *ro = (Root*) pad->getRootObject(sizeof(Root));
   setReturnNull(false);
   if(!ro)
    {
      ro=PAD_NEW(pad,Root);
      ro->myCount = 1;
      pad->setRootObject(ro, sizeof(Root));
      NZ_UDX_RETURN_INT32(1);
    }
    else
    {
      ro->myCount += 1;
      NZ_UDX_RETURN_INT32(1);
    }
   }
  };

Udf* PadCounter::instantiate()
{
  return new PadCounter;
}

class GetPadCount: public Udf
{
private:

public:
  static Udf* instantiate();
  virtual ReturnValue evaluate()
  {
   CPad* pad = getFilePad("PadCount");
   Root *ro = (Root*) pad->getRootObject(sizeof(Root));
   setReturnNull(false);
   if(!ro)
    {
      NZ_UDX_RETURN_INT64(0);
    }
   else
    {
      NZ_UDX_RETURN_INT64(ro->myCount);
    }
   }
};

Udf* GetPadCount::instantiate()
{
  return new GetPadCount;
}