-- you will need this function if you are using row versioning
-- according to http://odbc.postgresql.org/psqlodbc.php?DocID=faq-advanced#rowversioning you might not need it at all...

drop function int4eq(xid,int4);
drop operator = (xid,int4) ;

create function int4eq(xid,int4) 
    returns bool 
    as '' 
    language 'internal'; 

create operator = ( 
    leftarg=xid, 
    rightarg=int4, 
    procedure=int4eq, 
    commutator='=', 
    negator='<>', 
    restrict=eqsel, 
    join=eqjoinsel 
);


-- we need operators which can complare int and bool (because boolean type
-- in Access are really integers when they finish thair way through optimizer

DROP OPERATOR = (bool, int4);
DROP OPERATOR = (int4, bool);

DROP FUNCTION MsAccessBool1 (bool, int4);
CREATE FUNCTION MsAccessBool1 (bool, int4) RETURNS BOOL AS '
BEGIN
  IF $1 ISNULL THEN
    RETURN NULL;
  END IF;

  IF $1 IS TRUE THEN
    IF $2 <> 0 THEN
      RETURN TRUE;
    END IF;
  ELSE
    IF $2 = 0 THEN
      RETURN TRUE;
    END IF;
  END IF;
  RETURN FALSE;
END;
' LANGUAGE 'plpgsql';

CREATE OPERATOR = (
  LEFTARG = BOOL,
  RIGHTARG = INT4,
  PROCEDURE = MsAccessBool1,
  COMMUTATOR = '=',
  NEGATOR = '<>',
  RESTRICT = EQSEL,
  JOIN = EQJOINSEL
);

-- this is reverse of above

DROP FUNCTION MsAccessBool2 (int4, bool);
CREATE FUNCTION MsAccessBool2 (int4, bool) RETURNS BOOL AS '
BEGIN
  IF $2 ISNULL THEN
    RETURN NULL;
  END IF;

  IF $2 IS TRUE THEN
    IF $1 <> 0 THEN
      RETURN TRUE;
    END IF;
  ELSE
    IF $1 = 0 THEN
      RETURN TRUE;
    END IF;
  END IF;
  RETURN FALSE;
END;
' LANGUAGE 'plpgsql';

CREATE OPERATOR = (
  LEFTARG = int4,
  RIGHTARG = bool,
  PROCEDURE = MsAccessBool2,
  COMMUTATOR = '=',
  NEGATOR = '<>',
  RESTRICT = EQSEL,
  JOIN = EQJOINSEL
);

-- this is generaly not possible. However, when using boolean fields in
-- PostgreSQL and Access you will need not on int type.
-- so, if possible, rename this function to not

DROP FUNCTION xnot (int4);
CREATE FUNCTION xnot (int4) RETURNS BOOL AS '
BEGIN
  IF $1 IS NULL THEN
    RETURN NULL;
  END IF;

  IF $1 == 0 THEN
    RETURN TRUE;
  END IF;
  RETURN FALSE;
END;
' LANGUAGE 'plpgsql';

