<?php
/**
 * oracle_model.php - Oracle modle file for batches
 *
 * @author $Author: dtong $
 * @version $Id: oracle_model.php,v 1.4 2011/02/11 09:09:27 dtong Exp $
 * @copyright Copyright (c) 2009, Tiller Software Co., Ltd.
*/

class Oracle_model extends CI_Model {
	private $db_resource = FALSE;

	function __construct() {
		parent::__construct();
	}
	/*
	 * Function for connecting to Oracle.
	 *
	 * No input paramters
	 * $return oracle_connection|false
	*/
	function connect($server, $user, $password, $db_dbname) {
		$oracle_dbstr = "$server/$db_dbname";
		$conn = oci_connect($user, $password, $oracle_dbstr);
		$this->db_resource = $conn;
		if ( $conn === FALSE ) {
			echo ("Failed to connect to Oracle database, aborted.");
			return FALSE;
		}
		/*
		$this->db_resource = mysql_connect($server,$user,$password);
		if ( ! mysql_select_db($schema,$this->db_resource) ) {
			$this->db_resource = FALSE;
		}
		*/
		return $this->db_resource;
	} // connect_ps_oracle()

	/*
	 * Function for execute query and fetch all array data.
	 *
	 * No input paramters
	 * $return oracle_connection|false
	*/
	function query($sql, $torows=true) {
		if ($this->db_resource === FALSE)
			return FALSE;

		$res = FALSE;
		$conn =& $this->db_resource;
		$stid = oci_parse($conn, $sql);
		if (oci_execute($stid))
			oci_fetch_all($stid, $res);

		$temp = FALSE;
		if ($res !== false && is_array($res)) {
			foreach($res as $key => $value) {
				$temp[strtolower($key)] = $value;
			}
		}

		if ($torows) {
			$rows = array();
			foreach($temp as $key => $values) {
				$index = 0;
				if (is_array($values)) {
					foreach($values as $id => $data) {
						$rows[$index][$key] = trim($data);
						$index+= 1;
					}
				}
			}
			$temp = $rows;
		}


		//echo '<pre>'.print_r($rows , true).'</pre>';
		/*if ( $this->db_resource == FALSE )
			return FALSE;
		$result = mysql_query($sql, $this->db_resource);
		if ( ! $result )
			return FALSE;
		$ret = array();
		while ( $row = mysql_fetch_assoc($result) ) {
			$ret[] = $row;
		}
		return $ret;*/

		//echo '<pre>'.print_r($res , true).'</pre>';

		/*
		$conn =& $this->db_resource;
		$stmt = oci_parse($conn, $sql);
		if ( $stmt == FALSE ) {
			echo "Failed oci_parse() with SQL : " . $sql . "\n";
			return FALSE;
		}
		$res = oci_execute($stmt, OCI_DEFAULT);
		if ( $res == FALSE ) {
			echo "Failed oci_execute() with SQL : " . $sql . "\n";
			return FALSE;
		}
		*/
		return $temp;
	} //my_oracle_query

	/*
	 * Function for disconnect to Oracle.
	 *
	 * No input paramters
	 * $return oracle_connection|false
	*/
	function close() {
		if ( $this->db_resource !== FALSE) {
			//oci_free_statement($stid);
			$conn =& $this->db_resource;
			oci_close($conn);
		}
		//mysql_close($this->db_resource);
	}
}
?>