<?php defined('SYSPATH') or die('No direct access allowed.');

/**
 * TSM database connection using DB2.
 *
 * @package    PTA
 * @subpackage TSM
 * @category   Drivers
 * @author     Deon George
 * @copyright  (c) 2010 phpTSMadmin Development Team
 * @license    http://phptsmadmin.sf.net/license.html
 */
class Database_TSM_DB2 extends Database_TSM {
	public function connect() {
		if ($this->_connection)
			return;

		// Extract the connection parameters, adding required variabels
		extract($this->_config['connection'] + array(
			'database'   => '',
			'hostname'   => '',
			'username'   => '',
			'port'       => '',
			'password'   => '',
			'persistent' => FALSE,
		));

		// Get user login details from user session - these are set by login
		if (! $username)
			$username = Session::instance()->get_once(Kohana::config('auth.session_key'));
		if (! $password)
			$password = Session::instance()->get_once('password');

		// Prevent this information from showing up in traces
		unset($this->_config['connection']['username'], $this->_config['connection']['password']);

		if (! $username OR ! $password)
			HTTP::redirect('login');

		try {
			if ($persistent) {
				// Create a persistent connection
				throw new Kohana_Exception('Cant do persistant connections');

			} else {
				// Create a connection and force it to be a new link
				$constring = sprintf('DATABASE=%s;HOSTNAME=%s;PORT=%s;PROTOCOL=%s;UID=%s;PWD=%s',
					$database,$hostname,$port,'TCPIP',$username,$password);

				$this->_connection = db2_connect($constring,NULL,NULL);
echo debug::vars(array('s'=>$constring,'em'=>db2_conn_errormsg()));die();

				if ($this->_connection) {
					$result = DB::query(Database::SET,'SET SCHEMA='.$database)->execute(Kohana::config('config.client_type'));
					$result = $this->query(Database::SELECT,'SELECT server_name,platform,version,release,level,sublevel FROM status');

					return TSM::instance()->set($username,$password,$result);

				} else
					HTTP::redirect(Request::detect_uri());
			}

		} catch (ErrorException $e) {
			// No connection exists
			$this->_connection = NULL;

			throw new Database_Exception(':error', array(
					':error' => sprintf('%s error in %s (%s)',$e->getMessage(),$e->getFile(),$e->getLine()),
				),
				$e->getCode());
		}

		// \xFF is a better delimiter, but the PHP driver uses underscore
		$this->_connection_id = sha1($hostname.'_'.$username.'_'.$password);

		if ( ! empty($this->_config['charset'])) {
			// Set the character set
			$this->set_charset($this->_config['charset']);
		}
	}

	protected function execute($sql) {
		$result = @db2_exec($this->_connection,$sql);
		$this->execute_stderr = db2_stmt_errormsg();
		$this->execute_rc = db2_stmt_error();

		return $result;
	}

	public function list_columns($table, $like = NULL, $add_prefix = TRUE) {
		// Make sure the database is connected
		$this->_connection or $this->connect();

		// Quote the table name
		$table = ($add_prefix === TRUE) ? $this->quote_table($table) : $table;

		if (is_string($like))
			// Search for column names
			throw new Kohana_Exception('Like queries not implemented');
		else
			// Find all column names
			$result = db2_columns($this->_connection,NULL,NULL,$table);

		$count = 0;
		$columns = array();
		while ($row = db2_fetch_assoc($result)) {
			list($type, $length) = $this->_parse_type($row['TYPE_NAME']);

			$column = $this->datatype($type);

			$column['column_name']      = $row['COLUMN_NAME'];
			$column['data_type']        = $type;
			$column['is_nullable']      = ($row['IS_NULLABLE'] == 'YES');
			$column['ordinal_position'] = ++$count;

			switch (strtolower($column['data_type'])) {
				case 'float':
					if (isset($length))
						list($column['numeric_precision'], $column['numeric_scale']) = explode(',', $length);
					break;

				case 'int':
					if (isset($length))
						// MySQL attribute
						$column['display'] = $length;
					break;

				case 'string':
					switch ($column['data_type']) {
						case 'binary':
						case 'varbinary':
							$column['character_maximum_length'] = $length;
							break;

						case 'char':
						case 'varchar':
							$column['character_maximum_length'] = $length;
						case 'text':
						case 'tinytext':
						case 'mediumtext':
						case 'longtext':
							$column['collation_name'] = $row['Collation'];
							break;

						case 'enum':
						case 'set':
							$column['collation_name'] = $row['Collation'];
							$column['options'] = explode('\',\'', substr($length, 1, -1));
							break;
					}

					break;
			}

			// TSM attributes
			$column['comment']        = $row['REMARKS'];
			$columns[$row['COLUMN_NAME']] = $column;
		}

		return $columns;
	}
}
?>
