<?php

/* (c) ZonaExterior 2014 , rchaer@zonaexterior.net */

class TDB_ds {

    // data set
    var $hds; // handle del data set
    var $row;
    var $krow;
    var $campos;

    function TDB_ds($con, $sql) {
        $this->hds = $con->hcon->query($sql);
        $this->krow = 0;
        $campos = '';
    }

    function ncols() {
        $res = $this->hds->field_count;
        return $res;
    }

    function nrows() {
        $res = $this->hds->num_rows;
        return $res;
    }

    function go($krow) {
        $this->krow = 0;
        $res = $this->hds->data_seek($krow) && ($this->row = $this->hds->fetch_array(MYSQLI_BOTH));
        if ($res) {
            return $this->row;
        } else {
            return false;
        }
    }

    function first() {
        $this->krow = 0;
        $res = $this->hds->data_seek(0) && ($this->row = $this->hds->fetch_array(MYSQLI_BOTH));
        if ($res) {
            return $this->row;
        } else {
            return false;
        }
    }

    function next() {
        if ($this->row = $this->hds->fetch_array(MYSQLI_BOTH)) {
            $this->krow++;
            return $this->row;
        } else {
            return false;
        }
    }

    function go_obj($krow) {
        $this->krow = 0;
        $res = $this->hds->data_seek($krow) && ($this->row = $this->hds->fetch_object());
        if ($res) {
            return $this->row;
        } else {
            return false;
        }
    }

    function locate_k($campo, $valor) {
        $buscando = true;
        $k = 0;
        $n = $this->nrows();
        while ($buscando && ( $k < $n)) {
            $obj = $this->go($k);
            if ($obj[$campo] == $valor) {
                $buscando = false;
            } else {
                $k++;
            }
        }
        if ($buscando) {
            return -1;
        } else {
            return $k;
        }
    }

    function first_obj() {
        $this->krow = 0;
        $res = $this->hds->data_seek(0) && ($this->row = $this->hds->fetch_object());
        if ($res) {
            return $this->row;
        } else {
            return false;
        }
    }

    function next_obj() {
        if ($this->row = $this->hds->fetch_object()) {
            $this->krow++;
            return $this->row;
        } else {
            return false;
        }
    }

    function fname($kcol) {
        if ($this->campos == '') {
            $this->campos = $this->hds->fetch_fields();
        }
        return $this->campos[$kcol]->name;
    }

    function ftype($kcol) {
        if ($this->campos == '') {
            $this->campos = $this->hds->fetch_fields();
        }
        return $this->campos[$kcol]->type;
    }

    function flen($kcol) {
        if ($this->campos == '') {
            $this->campos = $this->hds->fetch_fields();
        }
        return $this->campos[$kcol]->max_length;
    }

    function fgetval($kcol) {
        return $this->row[$kcol];
    }

}

class TDB_con {

    // conexión
    var $hcon; // handle de la conexión
    var $dbg_on;
    var $_rgxp_;
    var $base;
    var $usuario;
    var $clave;
    var $charset;
    
    function TDB_con( $host, $base, $usuario, $clave, $charset = 'latin2', $port='3306' ) {
        $this->dbg_on = false;
        $this->base = $base;
        
        $this->_rgxp_= 'REGEXP';

        if (isset($clave) && ($clave != '')) {
            $this->hcon = new mysqli($host, $usuario, $clave, $base, $port);
        } else {
            $this->hcon = new mysqli($host, $usuario, '', $base, $port);
        }

        if ($this->hcon->connect_errno) {
            echo "Failed to connect to MySQL: (" . $this->hcon->connect_errno . ") " . $this->hcon->connect_error;
        } else {
           if ( $charset != '' ){
              $this->hcon->set_charset( $charset );
           }
	}
    }

    
    function query($sql_str) {
        $ds = new TDB_ds($this, $sql_str);
        if ($ds->hds) {
            return $ds;
        } else {
            if ($this->dbg_on)
                echo ("ERROR query_sql: $sql_str <br> " . $this->hcon->error );
            return false;
        }
    }

    function exec($sql_str, $dbg_on_mask = 1) {
        $res = @$this->hcon->query($sql_str);
        if ($res) {
            return $this->hcon->affected_rows;
        } else {
            if ($this->dbg_on && $dbg_on_mask)
                echo ("ERROR exec_sql: $sql_str <br> " . $this->hcon->error );
            return false;
        }
    }

    function close() {
        return $this->hcon->close();
    }

    function BEGIN_WORK() {
        $sql = 'BEGIN WORK;';
        return $this->exec($sql);
    }

    function COMMIT() {
        $sql = 'COMMIT;';
        return $this->exec($sql);
    }

    function ROLLBACK() {
        $sql = 'ROLLBACK;';
        return $this->exec($sql);
    }

    function nextval($nombresecuencia, $autocrear = 0) {
        $this->BEGIN_WORK();
        $sql = " select nextval as nid from secuencias where nombre = '" . $nombresecuencia . "'; ";
        $pgres = $this->query($sql);
        if ($pgres->nrows() != 1) {
            if ($autocrear) {
                $sql2 = "insert into secuencias ( nombre, nextval, incval ) values " .
                        "('$nombresecuencia', 1, 1 ) ";
                $this->exec($sql2);
                $pgres = $this->query($sql);
            } else {
                $this->COMMIT();
                echo "ERROR- nexval ( $nombresecuencia ) , secuencia desconocida ";
                return false;
            }
        }

        $r = $pgres->next();
        $nid = $r["nid"];
        $sql = " update secuencias set nextval=nextval+incval where nombre = '" . $nombresecuencia . "'; ";
        $this->exec($sql);
        $this->COMMIT();
        return $nid;
    }

    // retorna un valor es como evaluar la funcion sql
    function f($sql) {
        $ds = $this->query($sql);
        if ($ds != '') {
            $r = $ds->next();
            return $r[0];
        } else {
            return '';
        }
    }

    function f_obj($sql) {
        $ds = $this->query($sql);
        if ($ds != '') {
            $r = $ds->next_obj();
            return $r;
        } else {
            return '';
        }
    }

    function f_rec($sql) {
        $ds = $this->query($sql);
        if ($ds != '') {

            $r = $ds->next();
            return $r;
        } else {
            return '';
        }
    }

    function booleval($aval) {
        return $aval;
    }

    function error() {
        return $this->hcon->error;
    }

    function now() {
        return $this->f("SELECT DATE_FORMAT(now(), '%d/%m/%Y&nbsp;%H:%i') ");
    }

    function table_exists( $tabla ){
        $sql = "SELECT COUNT(*)
FROM information_schema.tables 
WHERE table_schema = '".$this->base ."' 
AND table_name = '".$tabla."'";
        return( (0+$this->f( $sql )) );
    }
}

?>
