<?php
require_once(searchinc('base.inc'));

class and_select
{
	var $clauses = array();
	
	function __construct($clauses)
	{
		$this->clauses = is_array($clauses)?$clauses:array($clauses);
	}
	
	function string()
	{
		$ret = '';
		foreach($clauses as $clause)
		{
			if (strlen($ret)>0) $ret .= ') && (';
			if (is_object($clause) && method_exists($clause, 'string'))
			{
				$ret .= $clause->string();
			}
			else
			{
				$ret .= $clause;
			}
		}
		return '('.$ret.')';
	}
}

class or_select
{
	var $clauses = array();
	
	function __construct($clauses)
	{
		$this->clauses = is_array($clauses)?$clauses:array($clauses);
	}
	
	function string()
	{
		$ret = '';
		foreach($clauses as $clause)
		{
			if (strlen($ret)>0) $ret .= ') || (';
			if (is_object($clause) && method_exists($clause, 'string'))
			{
				$ret .= $clause->string();
			}
			else
			{
				$ret .= $clause;
			}
		}
		return '('.$ret.')';
	}
}

class not_select
{
	var $clause;
	
	function __construct($clause)
	{
		$this->clause = $clause;
	}
	
	function string()
	{
		$ret = '';
		if (is_object($clause) && method_exists($clause, 'string'))
		{
			$ret .= $clause->string();
		}
		else
		{
			$ret .= $clause;
		}
		return '!('.$ret.')';
	}
}

class db_table extends basedb
{
	var $_table;
	var $_selection;
	var $_order = array();
	
	function __construct($table, $dbase, $dbuser, $mode=DEFAULT_TRIGGER_ON_ERROR)
	{
		$proc = __CLASS__.'::'.__FUNCTION__.': ';
		$this->dbgecho($proc.'('.$table.') entering', DEBUG_PROC_TRACE);
		$this->clear_error();

		$this->_table = $table;

		parent::__construct($dbase, $dbuser, get_mysql_password($dbuser), null, $mode);
		
		if (!$this->is_ok())
		{
			$this->trigger_error();
		}
		$this->dbgecho($proc.'leaving - '.($this->is_ok()?'succeeded':'failed'), DEBUG_PROC_TRACE);
//		return $this->is_ok();
	}
	
	function _ck_selection($item)
	{
		$ck = false;
		if (is_string($item))
		{
			$ck = true;
		}
		else if (is_object($item))
		{
			if (is_a($item, 'and_select') || is_a($item, 'or_select'))
			{
				foreach($item->clauses as $clause)
				{
					if (!($ck = $this->_ck_selection($clause))) break;
				}
			}
			elseif (is_a($item, 'not_select'))
			{
				$ck = $this->_ck_selection($item->clause);
			}
		}
		return $ck;
	}
	
	function select($selection=null)
	{
		$proc = __CLASS__.'::'.__FUNCTION__.': ';
		$this->dbgecho($proc.'entering', DEBUG_PROC_TRACE);
		$this->clear_error();
		
		if (isset($selection))
		{
			if (!$this->_ck_selection($selection))
			{
				$this->set_error('', __FILE__, __LINE__);
			}
			else
			{
				$this->_selection = $selection;
			}
		}
		$this->dbgecho($proc.'leaving - '.($this->is_ok()?$this->select_string():'failed'), DEBUG_PROC_TRACE);
		return $this->is_ok($this->_selection, RETURN_NULL_OK);
	}
	
	function select_string()
	{
		if (is_object($this->_selection) && method_exists($this->_selection, 'string'))
		{
			$ret = $this->_selection->string();
		}
		else
		{
			$ret = $this->_selection;
		}
		return $ret;
	}
	
	function order($order=null)
	{
		$proc = __CLASS__.'::'.__FUNCTION__.': ';
		$this->dbgecho($proc.'entering', DEBUG_PROC_TRACE);
		$this->clear_error();
		
		if (isset($order))
		{
			if (is_array($order))
			{
				$this->_order = $order;
			}
			else
			{
				$this->_order = array($order);
			}
		}
		$this->dbgecho($proc.'leaving - '.($this->is_ok()?$this->order_string():'failed'), DEBUG_PROC_TRACE);
		return $this->is_ok($this->_order, RETURN_NULL_OK);
	}
	
	function order_string()
	{
		$proc = __CLASS__.'::'.__FUNCTION__.': ';
		$this->dbgecho($proc.'$this->_order - '.look_r($this->_order), DEBUG_DETAIL_TRACE);
		return implode(', ', $this->_order);
	}
	
	function get_table()
	{
		return $this->_table;
	}
	
	function do_select($fields='*', $selection=null, $limit=null, $offset=null)
	{
		$proc = __CLASS__.'::'.__FUNCTION__.': ';
		$this->dbgecho($proc.'entering', DEBUG_PROC_TRACE);
		$this->clear_error();
		
		if (is_array($fields)) $fields = implode(', ', $fields);
		$sel_str = $this->select_string();
		if (strlen($sel_str)>0)
		{
			if (strlen($selection)>0)
				$sel_str = '('.$sel_str.') && ('.$selection.')';
		}
		else
		{
			$sel_str = $selection;
		}
		$ord_str = $this->order_string();
		$query = 'select '.$fields.' from '.$this->_table.
			((strlen($sel_str)>0)?(' where '.$sel_str):'').
			((strlen($ord_str)>0)?(' order by '.$ord_str):'').
			(isset($limit)?(' limit '.(isset($offset)?($offset.', '):'').$limit):'');
			
		$res = $this->query($query);
		
		$this->dbgecho($proc.'leaving - '.($this->is_ok()?'succeeded':'failed'), DEBUG_PROC_TRACE);
		return $this->is_ok($res);
	}
	
	function do_insert($fields)
	{
		$proc = __CLASS__.'::'.__FUNCTION__.': ';
		$this->dbgecho($proc.'entering', DEBUG_PROC_TRACE);
		$this->clear_error();
		
		if (!is_array($fields))
		{
			$this->set_error('Field values not specified in correct format.',__FILE__, __LINE__);
		}
		else
		{
			$assignments='';
			foreach($fields as $name => $value)
			{
				if (strlen($assignments)>0) $assignments .= ', ';
				$assignments .= '`'.$name.'`='.$value;
			}
			if(strlen($assignments)>0)
			{
				$query = 'insert into '.$this->_table.' set '.$assignments;
				if ($this->query($query))
				{
					// get id of record inserted
					$id = $this->last_insert_id();
				}
			}
		}
		
		$this->dbgecho($proc.'leaving - '.($this->is_ok()?'succeeded':'failed'), DEBUG_PROC_TRACE);
		return $this->is_ok($id);
	}
	
	function do_update($fields, $selection=null, $limit=null)
	{
		$proc = __CLASS__.'::'.__FUNCTION__.': ';
		$this->dbgecho($proc.'entering', DEBUG_PROC_TRACE);
		$this->clear_error();
		
		if (!is_array($fields))
		{
			$this->set_error('Field values not specified in correct format.',__FILE__, __LINE__);
		}
		else
		{
			$num = 0;
			$assignments='';
			foreach($fields as $name => $value)
			{
				if (strlen($assignments)>0) $assignments .= ', ';
				$assignments .= '`'.$name.'`='.$value;
			}
			if(strlen($assignments)>0)
			{
				$sel_str = $this->select_string();
				if (strlen($sel_str)>0)
				{
					if (strlen($selection)>0)
						$sel_str = '('.$sel_str.') && ('.$selection.')';
				}
				else
				{
					$sel_str = $selection;
				}
				$query = 'update '.$this->_table.' set '.$assignments.
						((strlen($sel_str)>0)?(' where '.$sel_str):'').
						(isset($limit)?(' limit '.$limit):'');
				
				if ($this->query($query))
				{
					$num = $this->affected_rows();
				}
			}
		}
		$this->dbgecho($proc.'leaving - '.($this->is_ok()?('updated'.$num.' rows'):'failed'), DEBUG_PROC_TRACE);
		return $this->is_ok($num);
	}
	
	function do_delete($selection=null, $limit=null, $order=null)
	{
		$proc = __CLASS__.'::'.__FUNCTION__.': ';
		$this->dbgecho($proc.'entering', DEBUG_PROC_TRACE);
		$this->clear_error();
		
		$sel_str = $this->select_string();
		if (strlen($sel_str)>0)
		{
			if (strlen($selection)>0)
				$sel_str = '('.$sel_str.') && ('.$selection.')';
		}
		else
		{
			$sel_str = $selection;
		}
		if (is_array($order))
		{
			$ord_str = implode(', ', $order);
		}
		$query = 'delete from '.$this->_table.
			((strlen($sel_str)>0)?(' where '.$sel_str):'').
			((strlen($ord_str)>0)?(' order by '.$ord_str):'').
			(isset($limit)?(' limit '.$limit):'');
			
		if ($this->query($query))
		{
			$num = $this->affected_rows();
		}
		
		$this->dbgecho($proc.'leaving - '.($this->is_ok()?$this->order_string():'failed'), DEBUG_PROC_TRACE);
		return $this->is_ok($num);
	}
}

// class definition used for specifying reference
// attributes of a database field
class db_field_ref
{
	var $db;
	var $table;
	var $field;
}

// class describing a database field
class db_field_desc extends base
{
	var $name;
	var $type;
	var $precision;
	var $scale;
	var $unsigned;
	var $allownull;
	var $deflt;
	var $primarykey;
	var $autoincrement;
	var $valuelist = array();
	var $reference;
	var $index_refs = array();	// array of references to any index desc object for each
								// index this field is a part of
								
	function __construct($name,
	                       $type,
	                       $precision=null,
						   $scale=null,
						   $unsigned=false,
						   $allownull=true,
						   $binary=false,
						   $primarykey=false,
						   $default=null,
						   $autoincrement=false,
						   $reference=null,
						   $valuelist=null,
						   $mode=DEFAULT_TRIGGER_ON_ERROR)
	{
		$all_types = array('tinyint', 'smallint', 'mediumint','int', 'integer', 'bigint',
		                   'float', 'double', 'double precision', 'real',
						   'dec', 'decimal', 'numeric',
						   'date', 'datetime', 'timestamp', 'time', 'year',
						   'char', 'character', 'nchar', 'national char', 'bit', 'bool',
						   'varchar', 'character varying', 'national varchar',
						   'text', 'mediumtext', 'longtext',
						   'blob', 'mediumblob', 'longblob',
						   'enum', 'set');
		
		// validate name - alpha numerics
		if (!preg_match ('/^[0-9a-zA-Z_$]+$/', $name))
		{
			$this->set_error('DB field name "'.$name.'" contains illegal identifiers', __FILE__, __LINE__);
		}
		else
		{
			// init base class
			parent::__construct($mode);
			
			$this->name = $name;
			
			// validate type
			if (!in_array(strtolower($type), $all_types))
			{
				$this->set_error('DB field type "'.$type.'" not recognized', __FILE__, __LINE__);
			}
			else
			{
				$this->type = $this->norm_type($type);
				$this->deflt = $default;
				if (isset($reference))
				{
					$this->reference = new db_field_ref();
					$this->reference->db = $reference['db'];
					$this->reference->table = $reference['table'];
					$this->reference->field = $reference['field'];
				}
				
				// validate precision
				// validate scale
				// validate unsigned
				// validate autoincrement
				// validate valuelist
				switch(strtolower($type))
				{
				case 'tinyint':
					$maxprec = 3;
				case 'smallint':
					if (!isset($maxprec)) $maxprec = 5;
				case 'mediumint':
					if (!isset($maxprec)) $maxprec = 8;
				case 'int':
				case 'integer':
					if (!isset($maxprec)) $maxprec = 10;
				case 'bigint':
					if (!isset($maxprec)) $maxprec = 20;
					if (isset($precision) && ($precision>$maxprec))
					{
						$this->set_error('Precision of '.$precision.' is greater than maximum of '.$maxprec.' for type '.$type, __FILE__, __LINE__);
					}
					elseif (isset($precision) && ($precision<1))
					{
						$this->set_error('Precision of '.$precision.' is less than minimum of 1 for type '.$type, __FILE__, __LINE__);
					}
					elseif ($autoincrement && !$primarykey)
					{
						$this->set_error('', __FILE__, __LINE__);
					}
					else
					{
						if (isset($precision)) $this->precision = $precision+1;
						$this->unsigned = $unsigned;
						$this->allownull = $allownull;
						$this->primarykey = $primarykey;
						$this->autoincrement = $autoincrement;
					}
					break;
				case 'float':
					$maxprec = (isset($scale)?24:53);
				case 'double':
				case 'double precision':
				case 'real':
					if (!isset($maxprec)) $maxprec = 53;
					if (strtolower($type)!='float' && isset($precision) && !isset($scale))
					{
						$this->set_error('Precision must be defined if scale is defined for type '.$type, __FILE__, __LINE__);
					}
					elseif (isset($scale) && !isset($precision))
					{
						$this->set_error('Scale must be defined if precision is defined for type '.$type, __FILE__, __LINE__);
					}
					elseif (isset($precision) && ($precision>$maxprec))
					{
						$this->set_error('Precision of '.$precision.' is greater than maximum of '.$maxprec.' for type '.$type, __FILE__, __LINE__);
					}
					elseif (isset($precision) && ($precision<2))
					{
						$this->set_error('Precision of '.$precision.' is less than minimum of 2 for type '.$type, __FILE__, __LINE__);
					}
					elseif(isset($precision) && isset($scale) && ($scale>30))
					{
						$this->set_error('Scale of '.$scale.' is greater than maximum of 30 for type '.$type, __FILE__, __LINE__);
					}
					elseif(isset($precision) && isset($scale) && ($scale>$precision-2))
					{
						$this->set_error('Scale of '.$scale.' is less than maximum of '.($precision-2).' for type '.$type.'('.$precision.')', __FILE__, __LINE__);
					}
					else
					{
						if (isset($precision)) $this->precision = $precision+1;
						if (isset($scale)) $this->scale = $scale;
						$this->allownull = $allownull;
						$this->primarykey = $primarykey;
					}
					break;
				case 'dec':
				case 'decimal':
				case 'numeric':
					if (isset($precision) && ($precision>53))
					{
						$this->set_error('Precision of '.$precision.' is greater than maximum of 53 for type '.$type, __FILE__, __LINE__);
					}
					elseif (isset($precision) && ($precision<2))
					{
						$this->set_error('Precision of '.$precision.' is less than minimum of 1 for type '.$type, __FILE__, __LINE__);
					}
					elseif (!isset($precision) && isset($scale))
					{
						$this->set_error('Scale ('.$scale.') only allowed when precision is specified for type '.$type, __FILE__, __LINE__);
					}
					elseif(isset($scale) && ($scale>30))
					{
						$this->set_error('Scale of '.$scale.' is greater than maximum of 30 for type '.$type, __FILE__, __LINE__);
					}
					elseif(isset($scale) && ($scale<0))
					{
						$this->set_error('Scale of '.$scale.' cannot be negative for type '.$type, __FILE__, __LINE__);
					}
					else
					{
						if (isset($precision)) $this->precision = $precision;
						if (isset($scale)) $this->scale = $scale;
						$this->allownull = $allownull;
						$this->primarykey = $primarykey;
					}
					break;
				case 'timestamp':
					if (isset($precision) && (($precision!=14) && ($precision!=12) && ($precision!=8) && ($precision!=6)))
					{
						$this->set_error('Precision of '.$precision.' is not supported.  Use one of 14,12,8 or 6 for '.$type, __FILE__, __LINE__);
					}
					if (isset($precision)) $this->precision = $precision;
				case 'date':
				case 'datetime':
				case 'time':
					if ($this->is_ok())
					{
						$this->allownull = $allownull;
						$this->primarykey = $primarykey;
					}
					break;
				case 'year':
					if (isset($precision) && (($precision!=4) && ($precision!=2)))
					{
						$this->set_error('Precision of '.$precision.' is not supported.  Use one of 4 or 2 for '.$type, __FILE__, __LINE__);
					}
					if (isset($precision)) $this->precision = $precision;
					$this->allownull = $allownull;
					$this->primarykey = $primarykey;
					break;
				case 'char':
				case 'character':
				case 'nchar':
				case 'national char':
					if (isset($precision) && ($precision>255))
					{
						$this->set_error('Precision of '.$precision.' is greater than maximum of 255 for type '.$type, __FILE__, __LINE__);
					}
					elseif (isset($precision) && ($precision<0))
					{
						$this->set_error('Precision ('.$precision.') cannot be negative for type '.$type, __FILE__, __LINE__);
					}
					else
					{
						if (isset($precision)) $this->precision = $precision;
					}
				case 'bit':
				case 'bool':
					if ($this->is_ok())
					{
						$this->allownull = $allownull;
						$this->primarykey = $primarykey;
						$this->binary = $binary;
					}
					break;
				case 'varchar':
				case 'character varying':
				case 'national varchar':
					if (!isset($precision))
					{
						$this->set_error('Precision is required to be specified for type '.$type, __FILE__, __LINE__);
					}
					elseif ($precision>255)
					{
						$this->set_error('Precision of '.$precision.' is greater than maximum of 255 for type '.$type, __FILE__, __LINE__);
					}
					elseif ($precision<1)
					{
						$this->set_error('Precision of '.$precision.' is less than minimum of 1 for type '.$type, __FILE__, __LINE__);
					}
					else
					{
						$this->precision = $precision;
						$this->allownull = $allownull;
						$this->primarykey = $primarykey;
						$this->binary = $binary;
					}
					break;
				case 'text':
				case 'mediumtext':
				case 'longtext':
				case 'blob':
				case 'mediumblob':
				case 'longblob':
					$this->primarykey = $primarykey;
					break;
				case 'enum':
					$maxnum = 65535;
				case 'set':
					if (!isset($maxnum)) $maxnum=64;
					if (!is_array($valuelist) || count($valuelist)==0)
					{
						$this->set_error('List of possible values must be specified for type '.$type, __FILE__, __LINE__);
					}
					elseif (count($valuelist)>$maxnum)
					{
						$this->set_error('Number possible values ('.count($valuelist).') must be mot be more than maximum of '.$maxnum.' for type '.$type, __FILE__, __LINE__);
					}
					else
					{
						$this->valuelist = $valuelist;
						$this->allownull = $allownull;
						$this->primarykey = $primarykey;
					}
					break;
				default:
					$this->set_error('Type '.$type.' is not supported', __FILE__, __LINE__);
				}
			}
		}
	}
	
	function def_string()
	{
		$def = '`'.$this->name.'` '.$this->type;
		switch($this->type)
		{
		case 'tinyint':
		case 'smallint':
		case 'mediumint':
		case 'int':
		case 'bigint':
		case 'char':
		case 'varchar':
		case 'timestamp':
		case 'year':
			$def .= (isset($this->precision)?'('.$this->precision.')':'').(isset($this->binary)?' binary':'');
			break;
		case 'float':
		case 'double':
		case 'dec':
			$def .= (isset($this->precision)?'('.$this->precision.(isset($this->scale)?','.$this->scale:'').')':'');
			break;
		case 'date':
		case 'datetime':
		case 'time':
		case 'bool':
		case 'text':
		case 'mediumtext':
		case 'longtext':
		case 'blob':
		case 'mediumblob':
		case 'longblob':
			break;
		case 'enum':
		case 'set':
			$def .= '("'.implode('", "', $this->valuelist).'")';
			break;
		default:
			$type = null;
		}
		$def .= (isset($this->unsigned)?' unsigned':'').
		        ($this->allownull?'':' not null').
				(isset($this->deflt)?' default '.$this->wrapvalue($this->deflt):'').
				($this->autoincrement?' auto_increment':'').
				($this->primarykey?' primary key':'').
				(isset($this->reference)?' references '.(isset($this->reference->db)?($this->reference->db.'.'):'').
				                         $this->reference->table.
										 (isset($this->reference->field)?
										 	'('.(is_array($this->reference->field)?implode(',',$this->reference->field):$this->reference->field):'').')'
										:'');
		return $def;
	}
	
	function wrapvalue($val)
	{
		if (isset($val))
		{
			switch($this->type)
			{
			case 'char':
				if ($this->precision == 0) $val='';
				// fall through
			case 'varchar':
			case 'bool':
			case 'text':
			case 'mediumtext':
			case 'longtext':
			case 'blob':
			case 'mediumblob':
			case 'longblob':
			case 'date':
			case 'datetime':
			case 'time':
			case 'timestamp':
			case 'year':
				$val = '\''.$val.'\'';
				break;
			case 'enum':
			case 'set':
				if (!is_numeric($val))
				{
					$val = '\''.$val.'\'';
				}
				break;
			case 'tinyint':
			case 'smallint':
			case 'mediumint':
			case 'int':
			case 'bigint':
			case 'float':
			case 'double':
			case 'dec':
				break;
			}
		}
		else
		{
			$val = 'null';
		}
		return $val;
	}
	
	function norm_type($type)
	{
		$type = strtolower($type);
		switch($type)
		{
		case 'integer':
			$type = 'int';
			break;
		case 'double precision':
		case 'real':
			$type = 'double';
			break;
		case 'numeric':
		case 'decimal':
			$type = 'dec';
			break;
		case 'character':
		case 'nchar':
		case 'national char':
			$type = 'char';
			break;
		case 'bit':
			$type = 'bool';
			break;
		case 'character varying':
		case 'national varchar':
			$type = 'varchar';
			break;
		case 'tinyint':
		case 'smallint':
		case 'mediumint':
		case 'int':
		case 'bigint':
		case 'float':
		case 'double':
		case 'dec':
		case 'timestamp':
		case 'date':
		case 'datetime':
		case 'time':
		case 'year':
		case 'char':
		case 'bool':
		case 'varchar':
		case 'text':
		case 'mediumtext':
		case 'longtext':
		case 'blob':
		case 'mediumblob':
		case 'longblob':
		case 'enum':
		case 'set':
			break;
		default:
			$type = null;
		}
		
		return $type;
	}
}

// class describing one column of an database index
class db_index_component
{
	var $fieldname;
	var $size;
	var $nullok;
	var $field_desc_ref;	// reference to the field structure
}

// class describing an entire database index
class db_index_desc extends base
{
	var $name;
	var $unique;
	var $fulltext;
	var $cols = array();	// array of db_component_objects
	
	function __construct($name,
						 $cols,
	                     $unique=true,
						 $fulltext=false,
						 $mode=DEFAULT_TRIGGER_ON_ERROR)
	{
		parent::__construct($mode);
		if (!is_array($cols))
		{
			$this->set_error('Index specification '.$name.' does not specify any column(s)', __FILE__, __LINE__);
		}
		else
		{
			$this->name = $name;
			$this->unique = $unique;
			$this->fulltext = $fulltext;
			foreach($cols as $fieldname => $info)
			{
				$comp = new db_index_component();
				$comp->fieldname = $fieldname;
				$comp->size = (isset($info['size'])?$info['size']:NULL);
				$comp->nullok = (isset($info['nullok'])?$info['nullok']:false);
				if (!empty($comp->fieldname))
				{
					$this->cols[$fieldname] = $comp;
				}
				else
				{
					$this->set_error('Index specification '.$name.' missing column name', __FILE__, __LINE__);
					break;
				}
			}
		}
		
		if (!$this->is_ok())
		{
			$this->trigger_error();
		}
//		return $this->is_ok();
	}
	
	function def_string()
	{
		if ($this->unique)
		{
			$def = 'unique index ';
		}
		elseif ($this->fulltext)
		{
			$def = 'fulltext index ';
		}
		elseif (strtolower($this->name)=='primary')
		{
			$def = 'primary key ';
		}
		else
		{
			$def = 'index ';
		}
		$coldef='';
		foreach($this->cols as $name => $compinfo)
		{
			if (strlen($coldef)>0) $coldef .= ', ';
			$coldef .= '`'.$name.'`'.(!empty($compinfo->size)?('('.$compinfo->size.')'):'');
		}
		$def .= '`'.$this->name.'`'.' ('.$coldef.')';
		return $def;
	}
}

class db_table_ex extends db_table
{
	var $tablename;	// application defined table name
	var $fielddesc;	// nested arrays specifying application required table fields.
					// This should be overridden in child db_table classes with a
					// description of the tables required
	var $keydesc;	// nested arrays specifying application required indicies.  This
					// should be overridden in child db_table classes with a
					// description of the indicies required
	var $comment;	// comment to describe table.  This  should be overridden in
	                // child db_table classes.
	
	var $fields;	// application specified fields, array of db_field_desc objects
					// created by constructor from information in field desc array
	var $indicies;	// application specified indicies, array of dn_index_desc object
					// created by constructor from information in key desc array.
	var $prikey;	// primary key field, if there is one
	
	function __construct($dbase, $dbuser, $mode=DEFAULT_TRIGGER_ON_ERROR)
	{
		$proc = __CLASS__.'::'.__FUNCTION__.': ';
		$this->dbgecho($proc.'('.$this->tablename.') entering', DEBUG_PROC_TRACE);
		
		// construct the field objects from the field description array
		if ($this->create_described_fields($dbase, $this->tablename, $mode))
		{
			if ($this->create_described_indicies($dbase, $this->tablename, $mode))
			{
				// check for a primary or unique single column index to flag as primary
				$this->flag_primary_key();
				
				parent::__construct($this->tablename, $dbase, $dbuser, $mode);
			}
		}
		
		if (!$this->is_ok())
		{
			$this->trigger_error();
		}
		$this->dbgecho($proc.'leaving - '.($this->is_ok()?'succeeded':'failed'), DEBUG_PROC_TRACE);
//		return $this->is_ok();
	}
	
	function create_described_fields($dbase, $table, $mode)
	{
		$proc = __CLASS__.'::'.__FUNCTION__.': ';
		$this->dbgecho($proc.'entering', DEBUG_PROC_TRACE);
		
		if (is_array($this->fielddesc))
		{
			foreach($this->fielddesc as $name => $desc)
			{
                               $fld = new db_field_desc($name,
                                                   $desc['type'],
                                                   isset($desc['precision'])?$desc['precision']:NULL,
						   isset($desc['scale'])?$desc['scale']:NULL,
						   isset($desc['unsigned'])?$desc['unsigned']:NULL,
						   isset($desc['allownull'])?$desc['allownull']:NULL,
						   isset($desc['binary'])?$desc['binary']:NULL,
						   isset($desc['primarykey'])?$desc['primarykey']:NULL,
						   isset($desc['default'])?$desc['default']:NULL,
						   isset($desc['autoincrement'])?$desc['autoincrement']:NULL,
						   isset($desc['reference'])?$desc['reference']:NULL,
						   isset($desc['valuelist'])?$desc['valuelist']:NULL,
						   $mode);
				if (!$fld->is_ok())
				{
					$this->copy_error($fld);
					$this->set_error('Unable to create field descriuptor for field '.$name.' of '.$dbase.'.'.$table, __FILE__, __LINE__);
					break;
				}
				else
				{
					$this->fields[$name] = $fld;
				}
			}
		}
		
		$this->dbgecho($proc.'leaving - '.($this->is_ok()?'succeeded':'failed'), DEBUG_PROC_TRACE);
		return $this->is_ok();
	}
	
	function create_described_indicies($dbase, $table, $mode)
	{
		$proc = __CLASS__.'::'.__FUNCTION__.': ';
		$this->dbgecho($proc.'entering', DEBUG_PROC_TRACE);
		
		$this->indicies = array();
		if (is_array($this->keydesc))
		{
			foreach($this->keydesc as $name => $desc)
			{
				$idx = new db_index_desc($name,
					                     isset($desc['cols'])?$desc['cols']:NULL,
                                                             isset($desc['unique'])?$desc['unique']:NULL,
                                                             isset($desc['fulltext'])?$desc['fulltext']:NULL,
                                                             $mode);
				if (!$idx->is_ok())
				{
					$this->copy_error($idx);
					$this->set_error('Unable to create index descriuptor for index '.$name.' of '.$dbase.'.'.$table, __FILE__, __LINE__);
					break;
				}
				else
				{
					$this->indicies[$name] = $idx;
				}
			}
		}
		
		$this->dbgecho($proc.'leaving - '.($this->is_ok()?'succeeded':'failed'), DEBUG_PROC_TRACE);
		return $this->is_ok();
	}
	
	function _ensure_tables_exist()
	{
		$proc = __CLASS__.'::'.__FUNCTION__.': ';
		$this->dbgecho($proc.'entering', DEBUG_PROC_TRACE);
		
		// TBD - load table description from data base
		
		// TBD - compare with application table description
		
		// TBD - make any modifications necessary
		
		// just create the table based on the field descriptions
		$defs = '';
		foreach($this->fields as $fielddef)
		{
			if (strlen($defs)>0) $defs .= ', ';
			$defs .= $fielddef->def_string();
		}
		foreach($this->indicies as $idxdef)
		{
			if (strlen($defs)>0) $defs .= ', ';
			$defs .= $idxdef->def_string();
		}
		$query = 'create table if not exists '.$this->_table.' ('.$defs.')'.
		         (isset($this->_comment)?' comment="'.$this->_comment.'"':'');
		$this->query($query);
		
		$this->dbgecho($proc.'leaving - '.($this->is_ok()?'succeeded':'failed'), DEBUG_PROC_TRACE);
		return $this->is_ok();
	}
	
	function flag_primary_key()
	{
		// check for 
		$continue = true;
		foreach($this->fields as $fielddef)
		{
			// seach for an existing field marked as the primary key
			if ($fielddef->primarykey)
			{
				$this->prikey = $fielddef->name;
				$continue = false;
				break;
			}
		}
		if ($continue)
		{
			foreach($this->indicies as $idxdef)
			{
				// seach for an index manked "primary"
				if (strtolower($idxdef->name)=='primary')
				{
					// if it has only one column, flag that column as the primary key
					if (count($idxdef->cols)==1)
					{
						$pkcol = reset($idxdef->cols);
						// this is a primary key that can be flagged
						$this->fields[$pkcol->fieldname]->primarykey = true;
						$this->prikey = $pkcol->fieldname;
					}
					$continue = false;
					break;
				}
			}
			if ($continue)
			{
				// find the first unique index with only one column
				foreach($this->indicies as $idxdef)
				{
					if ($idxdef->unique && (count($idxdef->cols)==1))
					{
						// flag that column as the primary key
						$pkcol = reset($idxdef->cols);
						// this is a primary key that can be flagged
						$this->fields[$pkcol->fieldname]->primarykey = true;
						$this->prikey = $pkcol->fieldname;
						break;
					}
				}
			}
		}
	}
	
	function list_fields()
	{
		return array_keys($this->fields);
	}
	
	function is_unique_field($field)
	{
		$proc = __CLASS__.'::'.__FUNCTION__.': ';
		$this->dbgecho($proc.'('.$field.') entering', DEBUG_PROC_TRACE);
		$this->clear_error();
		
		if (!isset($this->fields[$field]))
		{
			$this->set_error('Field '.$field.' is not present in table definition for table '.$this->_table, __FILE__, __LINE__);
		}
		else
		{
			// check to see if primary key attribute is checked for this field
			$uniq = $this->fields[$field]->primarykey;
			if (!$uniq)
			{
				// seach index definitions for a unique index with this as it's only column
				foreach($this->indicies as $idxdef)
				{
					if ($uniq = ($idxdef->unique && (count($idxdef->cols)==1) && isset($idxdef->cols[$field])))
					{
						break;
					}
				}
			}
		}
		$this->dbgecho($proc.'leaving - '.($this->is_ok()?'succeeded':'failed'), DEBUG_PROC_TRACE);
		return $this->is_ok($uniq);
	}
	
	// creates a mapping between this table and this class that wraps it
	static public function catalog($db, $table, $class)
	{
		$GLOBALS['db_table_ex_catalog'][$db][$table] = $class;
	}
	
	// returns the wrapping class name for thespecified table and database
	public function cataloged($db, $table)
	{
		return (isset($GLOBALS['db_table_ex_catalog'][$db][$table])?$GLOBALS['db_table_ex_catalog'][$db][$table]:false);
	}
	
	function get_referenced_table_object($field)
	{
		$proc = __CLASS__.'::'.__FUNCTION__.': ';
		$this->dbgecho($proc.'('.$field.') entering', DEBUG_PROC_TRACE);
		$this->clear_error();
		
		if (!isset($this->fields[$field]))
		{
			$this->set_error('Field '.$field.' is not present in table definition for table '.$this->_table, __FILE__, __LINE__);
		}
		elseif (!isset($this->fields[$field]->reference))
		{
			$this->set_error('Field '.$field.' is not a reference field in table '.$this->_table, __FILE__, __LINE__);
		}
		else
		{
			$ref = $this->fields[$field]->reference;
			
			// check to see if there is a class cataloged for this table
			$refclass = $this->cataloged($ref->db, $ref->table);
			if (!empty($refclass))
			{
				$ref_tbl_obj = new $refclass($ref->db, $this->get_db_user(), $this->_mode);
				if (!$ref_tbl_obj->is_ok())
				{
					$this->copy_error($ref_tbl_obj);
					$this->set_error('Unable to create referenced table object of class '.$refclass.' for field '.$field.' in table '.$this->_table, __FILE__, __LINE__);
				}
			}
		}
		$this->dbgecho($proc.'leaving - '.($this->is_ok()?'succeeded':'failed'), DEBUG_PROC_TRACE);
		return $this->is_ok($ref_tbl_obj, RETURN_NULL_OK);
	}
	
	// returns the db_field_desc object that describes a field
	function get_field_desc($field)
	{
		$proc = __CLASS__.'::'.__FUNCTION__.': ';
		$this->dbgecho($proc.'('.$field.') entering', DEBUG_PROC_TRACE);
		$this->clear_error();
		
		$desc_obj = $this->fields[$field];
		
		$this->dbgecho($proc.'leaving - '.($this->is_ok()?'succeeded':'failed'), DEBUG_PROC_TRACE);
		return $this->is_ok($desc_obj, RETURN_NULL_OK);
	}
}

class unique_indexed_table extends db_table_ex
{
//	var $_debug = DEBUG_DETAIL_TRACE;
	
	var $record;
	var $loaded_record=false;
	
	function __construct($dbase, $dbuser, $mode=DEFAULT_TRIGGER_ON_ERROR)
	{
		$proc = __CLASS__.'::'.__FUNCTION__.': ';
		$this->dbgecho($proc.'('.$this->tablename.') entering', DEBUG_PROC_TRACE);
		
		// construct
		parent::__construct($dbase, $dbuser, $mode);
		if ($this->is_ok())
		{
			// check for one and only one primary key
			if (!isset($this->prikey))
			{
				$this->set_error('No key defined for table '.$table, __FILE__, __LINE__);
			}
		}
		
		if (!$this->is_ok())
		{
			$this->trigger_error();
		}
		$this->dbgecho($proc.'leaving - '.($this->is_ok()?'succeeded':'failed'), DEBUG_PROC_TRACE);
//		return $this->is_ok();
	}
	
	function is_key_field($field)
	{
		return ($field == $this->prikey);
	}
	
	function key($new=null)
	{
		$proc = __CLASS__.'::'.__FUNCTION__.': ';
		$this->dbgecho($proc.'('.$this->_table.') entering', DEBUG_PROC_TRACE);
		$this->clear_error();
		
		if (isset($new))
		{
			if ($res = $this->do_select('*', '`'.$this->prikey.'`='.$this->fields[$this->prikey]->wrapvalue($this->escape_string($new))))
			{
				$this->record = $res->fetch_array();
				if (!$res->is_ok())
				{
					$this->copy_error($res);
					$this->set_error('Uanble to fetch result from database where '.$this->prikey.' is '.$new, __FILE__, __LINE__);
				}
				else
				{
					$this->dbgecho($proc.'record fetched: '.look_r($this->record), DEBUG_DETAIL_TRACE);
					$this->loaded_record = true;
				}
				$res->free();
			}
		}
		else
		{
			$this->dbgecho($proc.'primary key is: '.$this->prikey.', has record: '.look_r($this->record).', primary key value is '.look_r($this->record[$this->prikey]), DEBUG_DETAIL_TRACE);
		}
		
		$this->dbgecho($proc.'leaving - '.($this->is_ok()?'succeeded':'failed'), DEBUG_PROC_TRACE);
		return $this->is_ok($this->record[$this->prikey], RETURN_NULL_OK);
	}
	
	function set_field($field, $value=null)
	{
		if (($field==$this->prikey) && ($this->record[$field] != $value))
		{
			$this->loaded_record = false;
		}
		$this->record[$field] = $value;
	}
	
	function clear_fields()
	{
		$this->record = array();
		$this->loaded_record = false;
	}
	
	function get_field($field)
	{
		return $this->record[$field];
	}
	
	function get_generic($field, $code=null)
	{
		$proc = __CLASS__.'::'.__FUNCTION__.': ';
		$this->dbgecho($proc.'('.$field.') entered', DEBUG_PROC_TRACE);
		$this->clear_error();
		
		// check for cashed record
		if (isset($code) && (!$this->loaded_record || ($this->key()!=$code)))
		{
			$this->key($code);
		}
		if ($this->is_ok())
		{
			$val = $this->get_field($field);
		}
		
		$this->dbgecho($proc.'leaving - '.($this->is_ok()?'succeeded '.look_r($val):'failed'), DEBUG_PROC_TRACE);
		return $this->is_ok($val, RETURN_NULL_OK);
	}
	
	function set_generic($field, $new, $code=null)
	{
		$proc = __CLASS__.'::'.__FUNCTION__.': ';
		$this->dbgecho($proc.'('.$field.','.$new.') entered', DEBUG_PROC_TRACE);
		$this->clear_error();
		
		// check for cashed record
		if (isset($code) && (!$this->loaded_record || ($this->key()!=$code)))
		{
			$this->key($code);
		}
		if ($this->is_ok())
		{
			$this->set_field($field, $new);
			$this->put_record();
		}
		
		$this->dbgecho($proc.'leaving - '.($this->is_ok()?'succeeded':'failed'), DEBUG_PROC_TRACE);
		return $this->is_ok();
	}
	
	function get_record()
	{
		return $this->record;
	}
	
	function get_keys($selection)
	{
		$proc = __CLASS__.'::'.__FUNCTION__.': ';
		$this->dbgecho($proc.'('.$selection.', '.$this->_table.') entering', DEBUG_PROC_TRACE);
		$this->clear_error();
		
		if ($res = $this->do_select('`'.$this->prikey.'`', $selection))
		{
			$ret = array();
			while($row = $res->fetch_row())
			{
				$ret[] = $row[0];
			}
			if (!$res->is_ok())
			{
				$this->copy_error($res);
				$this->set_error('Unable to fetch selected key values of '.$this->prikey.' from database', __FILE__, __LINE__);
			}
			$res->free();
		}
		
//		$this->dbgecho($proc.'leaving - '.($this->is_ok()?'succeeded':'failed'), DEBUG_PROC_TRACE);
		$this->dbgecho($proc.'leaving - '.($this->is_ok()?look_r($ret):'failed'), DEBUG_PROC_TRACE);
		return $this->is_ok($ret);
	}
	
	function num_records()
	{
		$proc = __CLASS__.'::'.__FUNCTION__.': ';
		$this->dbgecho($proc.'('.$this->_table.') entering', DEBUG_PROC_TRACE);
		$this->clear_error();
		
		if ($res = $this->do_select('count(*)'))
		{
			if($row = $res->fetch_row())
			{
				$ret = $row[0];
			}
			if (!$res->is_ok())
			{
				$this->copy_error($res);
				$this->set_error('Unable to fetch the number of selected records from database', __FILE__, __LINE__);
			}
			$res->free();
		}
		
		$this->dbgecho($proc.'leaving - '.($this->is_ok()?'succeeded':'failed'), DEBUG_PROC_TRACE);
		return $this->is_ok($ret);
	}
	
	function put_record()
	{
		$proc = __CLASS__.'::'.__FUNCTION__.': ';
		$this->dbgecho($proc.'entering', DEBUG_PROC_TRACE);
		$this->clear_error();
		
		$insert = !$this->loaded_record;
		$this->dbgecho($proc.($insert?'Inserting':'Updating').' record: '.look_r($this->record), DEBUG_DETAIL_TRACE);
		
		// create the record values
		$vals = array();
		foreach($this->fields as $name => $info)
		{
			$this->dbgecho($proc.'$this->record['.$name.']: '.(isset($this->record[$name])?look_r($this->record[$name]):'null'), DEBUG_DETAIL_TRACE);
			// special handling for char(0) type fields
			if (($info->type == 'char') && ($info->precision == 0) &&
			    (isset($this->record[$name])) && ($this->record[$name]!==''))
			{
				$this->dbgecho($proc.'Making char(0) conversion to '.look_r($this->record[$name]), DEBUG_DETAIL_TRACE);
				// convert to null or empty string 
				$this->record[$name] = (((boolean)($this->record[$name]))?'':null);
				$this->dbgecho($proc.'Converted to '.look_r($this->record[$name]), DEBUG_DETAIL_TRACE);
			}
			if (($name != $this->prikey) || ($this->fields[$name]->autoincrement==false))
			{
				$vals[$name] = $info->wrapvalue($this->escape_string($this->record[$name]));
			}
		}
		$this->dbgecho($proc.'Vals: '.look_r($vals), DEBUG_DETAIL_TRACE);
		
		// try and figure out whether we are doing a insert or update
		if ($insert)
		{
			// do an insert
			if ($id = $this->do_insert($vals))
			{
				if ($this->fields[$this->prikey]->autoincrement)
				{
					$this->record[$this->prikey] = $id;
				}
				$this->loaded_record = true;
			}
		}
		else
		{
			// do an update
			$this->do_update($vals, '`'.$this->prikey.'`='.$this->fields[$this->prikey]->wrapvalue($this->escape_string($this->record[$this->prikey])));
		}
		
		$this->dbgecho($proc.'leaving - '.($this->is_ok()?'succeeded':'failed'), DEBUG_PROC_TRACE);
		return $this->is_ok($this->record[$this->prikey]);
	}
	
	function remove_record($key)
	{
		$proc = __CLASS__.'::'.__FUNCTION__.': ';
		$this->dbgecho($proc.'entering', DEBUG_PROC_TRACE);
		$this->clear_error();
		
		if (!isset($key))
		{
			$this->set_error('No key value specified for the record to remove.', __FILE__, __LINE__);
		}
		else
		{
			$this_record = ($key == $this->key());
			if ($this->do_delete('`'.$this->prikey.'`='.$this->fields[$this->prikey]->wrapvalue($this->escape_string($key))))
			{
				if ($this_record) $this->clear_fields();
			}
		}
		
		$this->dbgecho($proc.'leaving - '.($this->is_ok()?'succeeded':'failed'), DEBUG_PROC_TRACE);
		return $this->is_ok();
	}
}

class relationship_table extends db_table_ex
{
	var $relate_fields;				// array specifying the TWO fields of this table that establish
									// the relationship linkage.  This MUST be overridden in child
									// relationship_table classes
	
	var $one2one = false;
	var $one2many = false;
	var $many2many = true;
	
	var $relative_tbl = array();
	
	var $identity_field;				// field name of the element for which relationships are to be found
										// can be set to either of the relate_fields for one-to-one or
										// many-to-many relationships, but is always the master field for
										// one-to-many relationships
	var $identity_value;				// value for of the element for which relationships are to be found
	var $relation_records = array();	// store for the relationships for this identity
	var $loaded_record = false;			// whether relationship records have been loaded
	
	var $relation_field;
	
	function __construct($dbase, $dbuser, $mode=DEFAULT_TRIGGER_ON_ERROR)
	{
		$proc = __CLASS__.'::'.__FUNCTION__.': ';
		$this->dbgecho($proc.'('.$this->tablename.') entering', DEBUG_PROC_TRACE);
		
		// construct
		parent::__construct($dbase, $dbuser, $mode);
		if ($this->is_ok())
		{
			// check that there are two relate fields
			if (!is_array($this->relate_fields) ||
				(count($this->relate_fields) != 2) || 
			    !isset($this->fields[$this->relate_fields[0]]) ||
			    !isset($this->fields[$this->relate_fields[1]]))
			{
				$this->set_error('Pair of relationship fields are not defined or not present in table.', __FILE__, __LINE__);
			}
			else
			{
				// determine whether this is table expresses one-to-one, one-to-many
				// or many-to-many relationships
				$uniq0 = $this->is_unique_field($this->relate_fields[0]);
				$uniq1 = $this->is_unique_field($this->relate_fields[1]);
				if ($uniq0 && $uniq1)
				{
					$this->one2one = true;
				}
				elseif(!$uniq0 && !$uniq1)
				{
					$this->many2many = true;
				}
				else
				{
					$this->one2many = true;
					$this->identity_field = $this->relate_fields[($uniq0?1:0)];
					$this->relation_field = $this->relate_fields[($uniq0?0:1)];
				}
				
				// setup any access classes to the related tables
				for($i=0; $i<=1; $i++)
				{
					if (is_a($this->fields[$this->relate_fields[0]]->reference, 'db_field_ref'))
					{
						$ref = $this->fields[$this->relate_fields[0]]->reference;
						if ($rclass = $this->cataloged($ref->db, $ref->table))
						{
                                                        $this->relative_tbl[$this->relate_fields[0]] = new $rclass($ref->db, $dbuser, $mode);
							if (!$this->relative_tbl[$this->relate_fields[0]]->is_ok())
							{
								$this->copy_error($this->relative_tbl[$this->relate_fields[0]]);
								$this->set_error('Unable to initialize access object for field '.$this->relate_fields[0], __FILE__, __LINE__);
								break;
							}
						}
					}
				}
			}
		}
		
		if (!$this->is_ok())
		{
			$this->trigger_error();
		}
		$this->dbgecho($proc.'leaving - '.($this->is_ok()?'succeeded':'failed'), DEBUG_PROC_TRACE);
//		return $this->is_ok();
	}
	
	function identity_field($new=null)
	{
		$proc = __CLASS__.'::'.__FUNCTION__.': ';
		$this->dbgecho($proc.'('.$new.') entering', DEBUG_PROC_TRACE);
		$this->clear_error();
		
		if (isset($new))
		{
//			if ($this->one2many && ($new != $this->identity_field))
//			{
//				$this->set_error('Identity field is fixed to '.$this->identity_field.' for one-to-many relationship table '.$this->_table, __FILE__, __LINE__);
//			}
/*			else*/ if (!in_array($new, $this->relate_fields))
			{
				$this->set_error('Identity field can only be set to one of the relate fields for relationship table '.$this->_table, __FILE__, __LINE__);
			}
			else
			{
				if ($new != $this->identity_field)
				{
					$this->clear_identity();
					$this->identity_field = $new;
					if ($new == $this->relate_fields[0])
					{
						$this->relation_field = $this->relate_fields[1];
					}
					else
					{
						$this->relation_field = $this->relate_fields[0];
					}
				}
			}
		}
		
		$this->dbgecho($proc.'leaving - '.($this->is_ok()?'succeeded':'failed'), DEBUG_PROC_TRACE);
		return $this->is_ok($this->identity_field, RETURN_NULL_OK);
	}
	
	function identity($new=null)
	{
		$proc = __CLASS__.'::'.__FUNCTION__.': ';
		$this->dbgecho($proc.'('.$new.') entering', DEBUG_PROC_TRACE);
		$this->clear_error();
		
		if (isset($new))
		{
			if ($new != $this->identity_value)
			{
				$this->clear_identity();
				$this->identity_value = $new;
				$this->_load_relationships();
			}
		}
		
		$this->dbgecho($proc.'leaving - '.($this->is_ok()?look_r($this->identity_value):'failed'), DEBUG_PROC_TRACE);
		return $this->is_ok($this->identity_value, RETURN_NULL_OK);
	}
	
	function clear_identity()
	{
		$proc = __CLASS__.'::'.__FUNCTION__.': ';
		$this->dbgecho($proc.'entering', DEBUG_PROC_TRACE);
		$this->clear_error();
		
		$this->identity_value = null;
		$this->relation_records = array();
		$this->loaded_record = false;
		
		$this->dbgecho($proc.'leaving - '.($this->is_ok()?'succeeded':'failed'), DEBUG_PROC_TRACE);
		return $this->is_ok();
	}
	
	function add_relationship($relate, $info=null)
	{
		$proc = __CLASS__.'::'.__FUNCTION__.': ';
		$this->dbgecho($proc.'('.$relate.') entering', DEBUG_PROC_TRACE);
		$this->clear_error();
		
		if (!$this->loaded_record)
		{
			$this->set_error('Must set an identity before a relationship may be added to table '.$this->_table, __FILE__,__LINE__);
		}
		else
		{
			$assignments=array();
			if (is_array($info))
			{
				foreach($info as $field => $value)
				{
					if (!isset($this->fields[$field]))
					{
						$this->set_error('Info field `'.$field.'` does not exist in table definition for table '.$this->_table, __FILE__,__LINE__);
						break;
					}
					$assignments[$field] = $this->fields[$field]->wrapvalue($this->escape_string($value));
				}
			}
			if ($this->is_ok())
			{
				// check for existing relationship for this
				if (isset($this->relation_records[$relate]))
				{
					// update this one
					$selection = '`'.$this->identity_field.'`='.$this->fields[$this->identity_field]->wrapvalue($this->escape_string($this->identity_value)).
				    	         ' && `'.$this->relation_field.'`='.$this->fields[$this->relation_field]->wrapvalue($this->escape_string($relate));
					$this->do_update($assignments, $selection, 1);
				}
				else
				{
					// insert a new one
					$assignments[$this->identity_field] = $this->fields[$this->identity_field]->wrapvalue($this->escape_string($this->identity_value));
					$assignments[$this->relation_field] = $this->fields[$this->relation_field]->wrapvalue($this->escape_string($relate));
					$this->do_insert($assignments);
				}
				if ($this->is_ok())
				{
					// refresh the relationships
					$this->_load_relationships();
				}
			}
		}
		
		$this->dbgecho($proc.'leaving - '.($this->is_ok()?'succeeded':'failed'), DEBUG_PROC_TRACE);
		return $this->is_ok();
	}
	
	function remove_relationship($value=null)
	{
		$proc = __CLASS__.'::'.__FUNCTION__.': ';
		$this->dbgecho($proc.'('.$value.') entering', DEBUG_PROC_TRACE);
		$this->clear_error();
		
		if (!$this->loaded_record)
		{
			$this->set_error('Must set an identity before a relationship may be removed from table '.$this->_table, __FILE__,__LINE__);
		}
		elseif (!isset($value) && !$this->one2one)
		{
			$this->set_error('Value must be set to specify a relationship in table '.$this->_table, __FILE__,__LINE__);
		}
		else
		{
			$selection = '`'.$this->identity_field.'`='.$this->fields[$this->identity_field]->wrapvalue($this->escape_string($this->identity_value));
			if (isset($value))
				$selection .= ' && `'.$this->relation_field.'`='.$this->fields[$this->relation_field]->wrapvalue($this->escape_string($value));
				
			$this->do_delete($selection, 1);
			if ($this->is_ok())
			{
				// refresh the relationships
				$this->_load_relationships();
			}
		}
		
		$this->dbgecho($proc.'leaving - '.($this->is_ok()?'succeeded':'failed'), DEBUG_PROC_TRACE);
		return $this->is_ok();
	}
	
	function remove_all_relationships()
	{
		$proc = __CLASS__.'::'.__FUNCTION__.': ';
		$this->dbgecho($proc.'entering', DEBUG_PROC_TRACE);
		$this->clear_error();
		
		if (!$this->loaded_record)
		{
			$this->set_error('Must set an identity before relationships may be removed from table '.$this->_table, __FILE__,__LINE__);
		}
		else
		{
			$selection = '`'.$this->identity_field.'`='.$this->fields[$this->identity_field]->wrapvalue($this->escape_string($this->identity_value));
				
			$this->do_delete($selection);
			if ($this->is_ok())
			{
				// refresh the relationships
				$this->_load_relationships();
			}
		}
		
		$this->dbgecho($proc.'leaving - '.($this->is_ok()?'succeeded':'failed'), DEBUG_PROC_TRACE);
		return $this->is_ok();
	}
	
	function has_relationship($value, $ret_info=false)
	{
		$proc = __CLASS__.'::'.__FUNCTION__.': ';
		$this->dbgecho($proc.'('.$field1.','.$field2.') entering', DEBUG_PROC_TRACE);
		$this->clear_error();
		
		if (!$this->loaded_record)
		{
			$this->set_error('Must set an identity before relationships may be obtained from table '.$this->_table, __FILE__,__LINE__);
		}
		else
		{
			if (isset($this->relation_records[$value]))
			{
				if ($ret_info)
				{
					$info = $this->relation_records[$value];
				}
				else
				{
					$info = true;
				}
			}
			else
			{
				$info = false;
			}
		}
		
		$this->dbgecho($proc.'leaving - '.($this->is_ok()?'succeeded':'failed'), DEBUG_PROC_TRACE);
		return $this->is_ok($info);
	}
	
	function all_relationships($inc_info=false)
	{
		$proc = __CLASS__.'::'.__FUNCTION__.': ';
		$this->dbgecho($proc.'('.($inc_info?'all info':'keys only').') entering', DEBUG_PROC_TRACE);
		$this->clear_error();
		
		if (!$this->loaded_record)
		{
			$this->set_error('Must set an identity before relationships may be obtained from table '.$this->_table, __FILE__,__LINE__);
		}
		else
		{
			if ($inc_info)
			{
				$rels = $this->relation_records;
			}
			else
			{
				$rels = array_keys($this->relation_records);
			}
			$this->dbgecho($proc.'relationships: '.look_r($rels), DEBUG_DETAIL_TRACE);
		}
		
		$this->dbgecho($proc.'leaving - '.($this->is_ok()?'succeeded':'failed'), DEBUG_PROC_TRACE);
		return $this->is_ok($rels);
	}
	
	function _load_relationships()
	{
		$proc = __CLASS__.'::'.__FUNCTION__.': ';
		$this->dbgecho($proc.'entering', DEBUG_PROC_TRACE);
		$this->clear_error();
		
//		$this->dbgecho($proc.'$this: '.look__r($this, null, $tmp = array()), DEBUG_DETAIL_TRACE);
		
		if (!isset($this->identity_field) || !isset($this->identity_value))
		{
			$this->set_error('Identity field and identity value must be set before relationships may be obtained from table '.$this->_table, __FILE__,__LINE__);
		}
		else
		{
			$selection = '`'.$this->identity_field.'`='.($this->fields[$this->identity_field]->wrapvalue($this->escape_string($this->identity_value)));
			// get a list of all fields except the identity field
			$tmp =  $this->fields;
			unset($tmp[$this->identity_field]);
			$fields = '`'.implode('`,`',array_keys($tmp)).'`';
			// retrieve all applicable records
			if ($res = $this->do_select($fields, $selection))
			{
				$this->relation_records = array();
				while($row = $res->fetch_array())
				{
					$relation_value = $row[$this->relation_field];
					unset($row[$this->relation_field]);
					$this->relation_records[$relation_value] = $row;
				}
			}
			if ($this->is_ok())
			{
				$this->loaded_record = true;
				$this->dbgecho($proc.count($this->relation_records).'relationship records returned', DEBUG_DETAIL_TRACE);
			}
		}
		
		$this->dbgecho($proc.'leaving - '.($this->is_ok()?'succeeded':'failed'), DEBUG_PROC_TRACE);
		return $this->is_ok();
	}
	
	function get_relative_tbl_obj($value)
	{
		$proc = __CLASS__.'::'.__FUNCTION__.': ';
		$this->dbgecho($proc.'('.$value.') entering', DEBUG_PROC_TRACE);
		$this->clear_error();
		
		if (!$this->loaded_record)
		{
			$this->set_error('Must set an identity before table objects may be obtained.', __FILE__,__LINE__);
		}
		else
		{
			if (isset($this->relative_tbl[$this->relation_field]))
			{
				$ptab = $this->relative_tbl[$this->relation_field];
				if (is_a($patb, 'unique_indexed_table') && 
				    $ptab->is_key_field($this->fields[$this->relation_field]->reference->field))
				{
					$ptab->key($value);
				}
				elseif (is_a($ptab, 'relationship_table') && 
				    $ptab->identity_field($this->fields[$this->relation_field]->reference->field))
				{
					$ptab->identity($value);
				}
				else
				{
					$this->set_error('Relative table object of class '.get_class($ptab).' is unsupported', __FILE__, __LINE__);
				}
			}
		}
		
		$this->dbgecho($proc.'leaving - '.($this->is_ok()?'succeeded':'failed'), DEBUG_PROC_TRACE);
		return $this->is_ok($ptab, RETURN_NULL_OK);
	}
	
	function get_identity_tbl_obj()
	{
		$proc = __CLASS__.'::'.__FUNCTION__.': ';
		$this->dbgecho($proc.'entering', DEBUG_PROC_TRACE);
		$this->clear_error();
		
		if (!$this->loaded_record)
		{
			$this->set_error('Must set an identity before table objects may be obtained.', __FILE__,__LINE__);
		}
		else
		{
			if (isset($this->relative_tbl[$this->identity_field]))
			{
				$ptab = $this->relative_tbl[$this->identity_field];
				if (is_a($patb, 'unique_indexed_table') && 
				    $ptab->is_key_field($this->fields[$this->relation_field]->reference->field))
				{
					$ptab->key($this->identity_value);
				}
				elseif (is_a($ptab, 'relationship_table') && 
				    $ptab->identity_field($this->fields[$this->relation_field]->reference->field))
				{
					$ptab->identity($this->identity_value);
				}
				else
				{
					$this->set_error('Identity table object of class '.get_class($ptab).' is unsupported', __FILE__, __LINE__);
				}
			}
		}
		
		$this->dbgecho($proc.'leaving - '.($this->is_ok()?'succeeded':'failed'), DEBUG_PROC_TRACE);
		return $this->is_ok($ptab, RETURN_NULL_OK);
	}
}

class join_table extends basedb
{
	                    // a tree of info about the linkage of tables in this join.
						// each link description consists of an array with the following fields
						// array('field' => <name of linkage field>,
						//       'alias' => <alias to be used for table (must be unique in links tree)>,
						//       'required' => <true or false (if required inner join is used, otherwise left join)>,
						//       'classname' => <classname of db_table_ex based object for table>,
						//       'links' => array(<field name> => <nested link description>,
						//                        ...)
						//       )
						// join string will be generated from 
	var $_table_links = array();
	
	var $_table_join;	// SQL select command with correct joins.  Created by determine_join_string
	                    // method called in the constructor
	
						// an array of selection criteria, indexed by table alias (as defined
						// in _table_descs member.  Contents must be a array with a key giving
						// the db field and the value specifying the value and optionally relationship
						// betweem the two.
						// an complicated example, using two tables aliased 'a' and 'b'.
						//
						// array('a' => array('field1' => 'value1',					// a.field1 = value1
						//                    'field2' => array('value2' => '>='),  // a.field2 >= value2
						//					  'field3' => 'value3'),				// a.field3 = value3
						//       'b' => array('fielda' => array('value4' => '<'));	// b.valuea < value4
						//
						// This member may be defined by the derived class or may be specified at runtime
						// via the select() method, in which case the method is overwritten.
	var $_selects =	array();
	
						// array of order criteria, consisting of an ordinary (numerically indexed) array
						// of elements specifying table alias, field and direction.
						//
						// array('a.field1',					// sort ascending by default
						//       array('a.field2' => 'desc'),	// sort decending
						//       array('b.fielda' => 'asc'));	// sort ascending (explicit)
						//
						// This member may be defined by the derived class or may be specified at runtime
						// via the select() method, in which case the method is overwritten.
	var $_order = array();
	var $_grouping = array();
	
	var $_tbl_objs;		// array of table objects indexed by alias
	
	var $_records = array();
	
	function __construct($dbase, $dbuser, $mode=DEFAULT_TRIGGER_ON_ERROR)
	{
		$proc = __CLASS__.'::'.__FUNCTION__.': ';
		$this->dbgecho($proc.'entering', DEBUG_PROC_TRACE);
		
		parent::__construct($dbase, $dbuser, get_mysql_password($dbuser), null, $mode);
		if ($this->is_ok())
		{
			if (!$this->create_join_str($this->_table_join, $this->_table_links))
			{
				$this->dbgecho($proc.'error creating table join string', DEBUG_DETAIL_TRACE);
				$this->set_error('Unable to create a join string for this join table object', __FILE__, __LINE__);
			}
		}
		if (!$this->is_ok())
		{
			$this->trigger_error();
		}
		$this->dbgecho($proc.'leaving - '.($this->is_ok()?'succeeded':'failed'), DEBUG_PROC_TRACE);
		return $this->is_ok();
	}
	
	function create_join_str(&$join_str, $table_link, $from=null)
	{
		$proc = __CLASS__.'::'.__FUNCTION__.': ';
		$this->dbgecho($proc.'entering', DEBUG_PROC_TRACE);
		$this->clear_error();
		
		// do some validation
		if (!isset($table_link['field']) ||
		    !isset($table_link['alias']) ||
			!isset($table_link['classname']))
		{
			$this->set_error('Link descriptor is missing required fields.', __FILE__, __LINE__);
		}
		else
		{
			if (isset($this->_tbl_objs[$table_link['alias']]))
			{
				$tabobj = $this->_tbl_objs[$table_link['alias']];
			}
			else
			{
				$tabobj = new $table_link['classname'](null, $this->get_db_user(), $this->_mode);
			}
			if (!$tabobj->is_ok())
			{
				$this->copy_error($tabobj);
				$this->set_error('Unable to create declared object of type '.$table_link['classname'], __FILE__, __LINE__);
			}
			else
			{
				// save the table object under it's alias
				if (!isset($this->_tbl_objs[$table_link['alias']]))
					$this->_tbl_objs[$table_link['alias']] = $tabobj;
				
				$db_prefix = ($this->get_db()!=$tabobj->get_db()?$tabobj->get_db().'`.`':'');
				
				if (strlen($join_str)==0)
				{
					$join_str = '`'.$db_prefix.$tabobj->get_table().'` as '.$table_link['alias'];
				}
				else
				{
					$join_str = '('.$join_str.' '.($table_link['required']?'inner':'left').' join '.'`'.$db_prefix.$tabobj->get_table().'` as '.$table_link['alias'].
								' on `'.$from['alias'].'`.`'.$from['field'].'`=`'.$table_link['alias'].'`.`'.$table_link['field'].'`)';
				}
				
				if (is_array($table_link['links']))
				{
					foreach($table_link['links'] as $link_field => $next_link)
					{
						$this_link = $table_link;
						$this_link['field'] = $link_field;
						$this->create_join_str($join_str, $next_link, $this_link);
						if (!$this->is_ok()) break;
					}
				}
			}
		}
		
		$this->dbgecho($proc.'leaving - '.($this->is_ok()?look_r($join_str):'failed'), DEBUG_PROC_TRACE);
		return $this->is_ok();
	}
	
	function enumerate_fields(&$fields, $table_link)
	{
		$proc = __CLASS__.'::'.__FUNCTION__.': ';
		$this->dbgecho($proc.'entering', DEBUG_PROC_TRACE);
		$this->clear_error();
		
		// do some validation
		if (!isset($table_link['alias']) ||
			!isset($table_link['classname']))
		{
			$this->set_error('Link descriptor is missing required fields.', __FILE__, __LINE__);
		}
		else
		{
			if (isset($this->_tbl_objs[$table_link['alias']]))
			{
				$tabobj = $this->_tbl_objs[$table_link['alias']];
			}
			else
			{
				$tabobj = new $table_link['classname'](null, $this->get_db_user(), $this->_mode);
			}
			if (!$tabobj->is_ok())
			{
				$this->copy_error($tabobj);
				$this->set_error('Unable to create declared object of type '.$table_link['classname'], __FILE__, __LINE__);
			}
			else
			{
				// save the table object under it's alias
				if (!isset($this->_tbl_objs[$table_link['alias']]))
					$this->_tbl_objs[$table_link['alias']] = $tabobj;
				
				$tmpfields = $tabobj->list_fields();
				foreach($tmpfields as $field)
				{
					if (strlen($fields)>0) $fields .= ', ';
					$fields .= '`'.$table_link['alias'].'`.`'.$field.'` as `'.$table_link['alias'].'.'.$field.'`';
				}
				
				if (is_array($table_link['links']))
				{
					foreach($table_link['links'] as $next_link)
					{
						$this->enumerate_fields($fields, $next_link);
						if (!$this->is_ok()) break;
					}
				}
			}
		}
		$this->dbgecho($proc.'leaving - '.($this->is_ok()?look_r($fields):'failed'), DEBUG_PROC_TRACE);
		return $this->is_ok();
	}
	
	// an array of selection criteria, indexed by table alias (as defined
	// in _table_descs member.  Contents must be a array with a key giving
	// the db field and the value specifying the value and optionally relationship
	// betweem the two.
	// an complicated example, using two tables aliased 'a' and 'b'.
	//
	// array('a' => array('field1' => 'value1',					// a.field1 = value1
	//                    'field2' => array('value2' => '>='),  // a.field2 >= value2
	//					  'field3' => 'value3'),				// a.field3 = value3
	//       'b' => array('fielda' => array('value4' => '<'));	// b.valuea < value4
	//
	function select($selection=null)
	{
		$proc = __CLASS__.'::'.__FUNCTION__.': ';
		$this->dbgecho($proc.'entering', DEBUG_PROC_TRACE);
		$this->clear_error();
		
		if (is_array($selection))
		{
			$this->_selects = $selection;
		}
		$this->dbgecho($proc.'leaving - '.($this->is_ok()?$this->_select_string():'failed'), DEBUG_PROC_TRACE);
		return $this->is_ok($this->_selects);
	}
	
	function _select_string()
	{
		$proc = __CLASS__.'::'.__FUNCTION__.': ';
		$this->dbgecho($proc.'('.$permission.') entered', DEBUG_PROC_TRACE);
		$this->clear_error();
		
		$sel = '';
		foreach($this->_selects as $prefix => $fldinfo)
		{
			foreach($fldinfo as $name => $value)
			{
				if (strlen($sel)>0) $sel .= ' && ';
				$sel .= $prefix.'.`'.$name.'`'.(isset($value)?'=':' is ').$this->wrapvalue($prefix,$name,$this->escape_string($value));
			}
		}
		
		$this->dbgecho($proc.'leaving - '.($this->is_ok()?look_r($sel):'failed'), DEBUG_PROC_TRACE);
		return $this->is_ok($sel);
	}
	
	function order($order=null)
	{
		$proc = __CLASS__.'::'.__FUNCTION__.': ';
		$this->dbgecho($proc.'entering', DEBUG_PROC_TRACE);
		$this->clear_error();
		
		if (isset($order))
		{
			if (is_array($order))
			{
				$this->_order = $order;
			}
			else
			{
				$this->_order = array($order);
			}
		}
		$this->dbgecho($proc.'leaving - '.($this->is_ok()?$this->order_string():'failed'), DEBUG_PROC_TRACE);
		return $this->is_ok($this->_order, RETURN_NULL_OK);
	}
	
	function order_string()
	{
		return implode(', ', $this->_order);
	}
	
	function grouping($grouping=null)
	{
		$proc = __CLASS__.'::'.__FUNCTION__.': ';
		$this->dbgecho($proc.'entering', DEBUG_PROC_TRACE);
		$this->clear_error();
		
		if (isset($grouping))
		{
			if (is_array($grouping))
			{
				$this->_grouping = $grouping;
			}
			else
			{
				$this->_grouping = array($grouping);
			}
		}
		$this->dbgecho($proc.'leaving - '.($this->is_ok()?$this->grouping_string():'failed'), DEBUG_PROC_TRACE);
		return $this->is_ok($this->_order, RETURN_NULL_OK);
	}
	
	function grouping_string()
	{
		return implode(', ', $this->_grouping);
	}
	
	function do_select($fields='*', $selection=null, $limit=null, $offset=null)
	{
		$proc = __CLASS__.'::'.__FUNCTION__.': ';
		$this->dbgecho($proc.'entering('.look_r($selection).')', DEBUG_PROC_TRACE);
		$this->clear_error();
		
		if (is_array($fields)) $fields = implode(', ', $fields);
		$sel_str = $this->_select_string();
		$this->dbgecho($proc.'$sel_str: '.look_r($sel_str).')', DEBUG_DETAIL_TRACE);
		if (strlen($sel_str)>0)
		{
			if (strlen($selection)>0)
				$sel_str = '('.$sel_str.') && ('.$selection.')';
		}
		else
		{
			$sel_str = $selection;
		}
		$this->dbgecho($proc.'final $sel_str: '.look_r($sel_str).')', DEBUG_DETAIL_TRACE);
		$grp_str = $this->grouping_string();
		$ord_str = $this->order_string();
		$query = 'select '.$fields.' from '.$this->_table_join.
			((strlen($sel_str)>0)?(' where '.$sel_str):'').
			((strlen($grp_str)>0)?(' group by '.$grp_str):'').
			((strlen($ord_str)>0)?(' order by '.$ord_str):'').
                        (isset($limit)?(' limit '.(isset($offset)?($offset.', '):'').$limit):'');
			
		$res = $this->query($query);
		
		$this->dbgecho($proc.'leaving - '.($this->is_ok()?'succeeded':'failed'), DEBUG_PROC_TRACE);
		return $this->is_ok($res);
	}
	
	function wrapvalue($tbl, $field, $val)
	{
		if (!isset($this->_tbl_objs[$tbl]))
		{
			// seach for table with this name
			foreach($this->_tbl_objs as $table_obj)
			{
				if ($table_obj->_table == $tbl) break;
			}
		}
		else
		{
			$table_obj = $this->_tbl_objs[$tbl];
		}
		if (isset($table_obj) && isset($table_obj->fields[$field]))
		{
			$val = $table_obj->fields[$field]->wrapvalue($val);
		}
		return $val;
	}
	
	function load_records($selection=null)
	{
		$proc = __CLASS__.'::'.__FUNCTION__.': ';
		$this->dbgecho($proc.'entering', DEBUG_PROC_TRACE);
		$this->clear_error();
		
		$this->enumerate_fields($field_list, $this->_table_links);
		if ($this->is_ok())
		{
			if ($res = $this->do_select($field_list, $selection))
			{
				$this->_records = $res->fetch_data();
				$res->free();
			}
		}
		
		$this->dbgecho($proc.'leaving - '.($this->is_ok()?'succeeded':'failed'), DEBUG_PROC_TRACE);
		return $this->is_ok($this->num_records());
	}
	
	function num_records()
	{
		return count($this->_records);
	}
	
	function get_record($index=0)
	{
		return $this->_records[$index];
	}
	
	function get_field($fieldname, $alias=null, $index=0)
	{
		$proc = __CLASS__.'::'.__FUNCTION__.': ';
		$this->dbgecho($proc.'('.$fieldname.') entering', DEBUG_PROC_TRACE);
		$this->clear_error();
		
		if (!isset($alias))
		{
			foreach($this->_tbl_objs as $a => $tabobj)
			{
				if (isset($tabobj->fields[$fieldname]))
				{
					$alias = $a;
					break;
				}
			}
		}
		if (isset($alias))
		{
			if (isset($this->_records[$index]))
			{
				$this->dbgecho($proc.'$_records['.$index.']: '.look_r(array_keys($this->_records[$index])), DEBUG_DETAIL_TRACE);
				if (array_key_exists($alias.'.'.$fieldname, $this->_records[$index]))
				{
					$res = $this->_records[$index][$alias.'.'.$fieldname];
				}
				else
				{
					$this->set_error('Field '.$alias.'.'.$fieldname.' not found in this table join', __FILE__, __LINE__);
				}
			}
			else
			{
				$this->set_error('Record '.$index.' does not exist for this table query', __FILE__, __LINE__);
			}
		}
		
		$this->dbgecho($proc.'leaving - '.($this->is_ok()?'succeeded':'failed'), DEBUG_PROC_TRACE);
		return $this->is_ok($res, RETURN_NULL_OK);
	}
	
	function clear_records()
	{
		$this->_records = array();
	}
}

// the next two class definitions are used for 
class jt_join_reference extends base
{
//	var $_debug = DEBUG_DETAIL_TRACE;
	
	var $from_db;
	var $from_tab;
	var $from_field;
	var $from_tab_obj;	// reference for jt_join_table 
	
	var $to_db;
	var $to_tab;
	var $to_field;
	var $to_tab_obj;	// reference for jt_join_table 
	
	function __construct($db, $tablename, $fieldname, $mode=DEFAULT_TRIGGER_ON_ERROR)
	{
		$proc = __CLASS__.'::'.__FUNCTION__.': ';
		$this->dbgecho($proc.'('.$db.','.$tablename.'.'.$fieldname.')entering', DEBUG_PROC_TRACE);
		
		parent::__construct($mode);
		if ($this->is_ok())
		{
			$this->from_db = $db;
			$this->from_tab = $tablename;
			$this->from_field = $fieldname;
		}
		if (!$this->is_ok())
		{
			$this->trigger_error();
		}
		$this->dbgecho($proc.'leaving - '.($this->is_ok()?'succeeded':'failed'), DEBUG_PROC_TRACE);
//		return $this->is_ok();
	}
	
	function db()
	{
		return $this->from_db;
	}
	
	function table()
	{
		return $this->from_tab;
	}
	
	function field()
	{
		return $this->from_field;
	}
	
	function token()
	{
		return ($this->from_tab.'.'.$this->from_field.'=>'.$this->to_token());
	}
	
	function refers_to($db, $tablename, $fieldname)
	{
		$proc = __CLASS__.'::'.__FUNCTION__.': ';
		$this->dbgecho($proc.'('.$tablename.'.'.$fieldname.')entering', DEBUG_PROC_TRACE);
		$this->clear_error();
		
		$this->to_db = $db;
		$this->to_tab = $tablename;
		$this->to_field = $fieldname;
			
		$this->dbgecho($proc.'leaving - '.($this->is_ok()?'succeeded':'failed'), DEBUG_PROC_TRACE);
		return $this->is_ok();
	}
	
	function to_db()
	{
		return $this->to_db;
	}
	
	function to_table()
	{
		return $this->to_tab;
	}
	
	function to_field()
	{
		return $this->to_field;
	}
	
	function to_token()
	{
		return ($this->to_tab.'.'.$this->to_field);
	}
	
	function refers_to_same($jt_join_reference)
	{
		return (($this->to_tab===$jt_join_reference->to_tab) && ($this->to_field===$jt_join_reference->to_field));
	}
	
	function set_table_obj(&$jt_join_table)
	{
		$proc = __CLASS__.'::'.__FUNCTION__.': ';
		$this->dbgecho($proc.'('.$jt_join_table->table.')entering', DEBUG_PROC_TRACE);
		$this->clear_error();
		
		$this->from_tab_obj = &$jt_join_table;
		
		$this->dbgecho($proc.'leaving - '.($this->is_ok()?'succeeded':'failed'), DEBUG_PROC_TRACE);
		return $this->is_ok();
	}
	
	function set_refers_to_table_obj(&$jt_join_table)
	{
		$proc = __CLASS__.'::'.__FUNCTION__.': ';
		$this->dbgecho($proc.'('.$jt_join_table->table.')entering', DEBUG_PROC_TRACE);
		$this->clear_error();
		
		$this->to_tab_obj = &$jt_join_table;
		
		$this->dbgecho($proc.'leaving - '.($this->is_ok()?'succeeded':'failed'), DEBUG_PROC_TRACE);
		return $this->is_ok();
	}
	
	function mk_join($join_str, &$tables, &$visited, $forward=true)
	{
		$proc = __CLASS__.'::'.__FUNCTION__.': ';
		$this->dbgecho($proc.'('.$this->token().')entering', DEBUG_PROC_TRACE);
		$this->clear_error();
		
		if (strlen($join_str)==0)
		{
			if ($forward)
			{
				$this->dbgecho($proc.'initializing join string with '.$this->from_tab, DEBUG_DETAIL_TRACE);
				$alias = $this->from_tab_obj->alias();
				$join_str = $this->from_db.'.'.$this->from_tab.(isset($alias)?(' as '.$alias):'');
				$tables[] = $this->from_db.'.'.$this->from_tab;
			}
			else
			{
				$this->dbgecho($proc.'initializing join string with '.$this->to_tab, DEBUG_DETAIL_TRACE);
				$alias = $this->to_tab_obj->alias();
				$join_str = $this->to_db.'.'.$this->to_tab.(isset($alias)?(' as '.$alias):'');
				$tables[] = $this->to_db.'.'.$this->to_tab;
			}
		}
		else
		{
			$join_str = '('.$join_str.')';
		}
		$this->dbgecho($proc.'$tables: '.look_r($tables), DEBUG_DETAIL_TRACE);
		$this->dbgecho($proc.'$this->to_tab: '.look_r($this->to_tab), DEBUG_DETAIL_TRACE);
		$this->dbgecho($proc.'$this->from_tab: '.look_r($this->from_tab), DEBUG_DETAIL_TRACE);
		if (!in_array($this->to_db.'.'.$this->to_tab, $tables))
		{
			$this->dbgecho($proc.'joining to next table '.$this->to_tab.' from field '.$this->from_field, DEBUG_DETAIL_TRACE);
			$join_target = $this->to_db.'.'.$this->to_tab;
			$join_field = $this->to_field;
			$targ_tab_obj = &$this->to_tab_obj;
			$origtable = $this->from_db.'.'.$this->from_tab;
			$origalias = $this->from_tab_obj->alias();
			$origfield = $this->from_field;
		}
		elseif (!in_array($this->from_db.'.'.$this->from_tab, $tables))
		{
			$this->dbgecho($proc.'joining to prev table '.$this->from_tab.' from field '.$this->to_field, DEBUG_DETAIL_TRACE);
			$join_target = $this->from_db.'.'.$this->from_tab;
			$join_field = $this->from_field;
			$targ_tab_obj = &$this->from_tab_obj;
			$origtable = $this->to_db.'.'.$this->to_tab;
			$origalias = $this->to_tab_obj->alias();
			$origfield = $this->to_field;
		}
		else
		{
			$this->dbgecho($proc.'no table to join', DEBUG_DETAIL_TRACE);
			unset($join_target);
		}
		if (isset($join_target))
		{
			$tables[] = $join_target;
			$alias = $targ_tab_obj->alias();
			$req = $targ_tab_obj->required();
			$join_str .= ' '.($req?'inner':'left').' join '.$join_target.(isset($alias)?(' as '.$alias):'').
						 ' on '.(isset($origalias)?$origalias:$origtable).'.'.$origfield.
						 '='.(isset($alias)?$alias:$join_target).'.'.$join_field;
			$this->dbgecho($proc.'compiling join string: '.$join_str, DEBUG_DETAIL_TRACE);
			
			if ($forward)
			{
				$join_str = $this->to_tab_obj->mk_join($join_str, $tables, $visited);
			}
			else
			{
				$join_str = $this->from_tab_obj->mk_join($join_str, $tables, $visited);
			}
		}
		
		$this->dbgecho($proc.'leaving - '.($this->is_ok()?'succeeded':'failed'), DEBUG_PROC_TRACE);
		return $this->is_ok($join_str);
	}
}

class jt_join_table extends base
{
//	var $_debug = DEBUG_DETAIL_TRACE;
	
	var $db;
	var $table;
	var $table_alias;
	var $required;
	var $iskey;
	
	var $to_refs = array();
	var $from_refs = array();
	
	function __construct($db, $tablename, $alias=null, $required=true, $iskey=false, $mode=DEFAULT_TRIGGER_ON_ERROR)
	{
		$proc = __CLASS__.'::'.__FUNCTION__.': ';
		$this->dbgecho($proc.'('.$tablename.','.$alias.','.($required?'req':'').','.($iskey?'key':'').')entering', DEBUG_PROC_TRACE);
		
		parent::__construct($mode);
		if ($this->is_ok())
		{
			$this->db = $db;
			$this->table = $tablename;
			$this->table_alias = $alias;
			$this->required = $required;
			$this->iskey = $iskey;
		}
		if (!$this->is_ok())
		{
			$this->trigger_error();
		}
		$this->dbgecho($proc.'leaving - '.($this->is_ok()?'succeeded':'failed'), DEBUG_PROC_TRACE);
		return $this->is_ok();
	}
	
	function to_ref(&$jt_join_reference)
	{
		$proc = __CLASS__.'::'.__FUNCTION__.': ';
		$this->dbgecho($proc.'('.$this->table.') entering', DEBUG_PROC_TRACE);
		$this->clear_error();
		
		$this->dbgecho($proc.'$this->table: '.look_r($this->table).') entering', DEBUG_DETAIL_TRACE);
		$this->dbgecho($proc.'$jt_join_reference->table(): '.look_r($jt_join_reference->table()).') entering', DEBUG_DETAIL_TRACE);
		
		if ($jt_join_reference->table()!=$this->table)
		{
			$this->set_error('Reference of '.$jt_join_reference->table().'.'.$jt_join_reference->field().' does not match table being applied to', __FILE__, __LINE__);
		}
		else
		{
			$jt_join_reference->set_table_obj($this);
			$this->to_refs[] = $jt_join_reference;
		}
		
		$this->dbgecho($proc.'leaving - '.($this->is_ok()?'succeeded':'failed'), DEBUG_PROC_TRACE);
		return $this->is_ok();
	}
	
	function from_ref(&$jt_join_reference)
	{
		$proc = __CLASS__.'::'.__FUNCTION__.': ';
		$this->dbgecho($proc.'entering', DEBUG_PROC_TRACE);
		$this->clear_error();
		
		if ($jt_join_reference->to_table()!=$this->table)
		{
			$this->set_error('Reference does not match table being applied to', __FILE__, __LINE__);
		}
		else
		{
			$jt_join_reference->set_refers_to_table_obj($this);
			$this->from_refs[] = $jt_join_reference;
		}
		
		$this->dbgecho($proc.'leaving - '.($this->is_ok()?'succeeded':'failed'), DEBUG_PROC_TRACE);
		return $this->is_ok();
	}
	
	function mk_join($join_str, &$tables, &$visited)
	{
		$proc = __CLASS__.'::'.__FUNCTION__.': ';
		$this->dbgecho($proc.'('.$this->table.')entering', DEBUG_PROC_TRACE);
		$this->clear_error();
                
		$this->dbgecho($proc.'from_refs: '.$this->refs2str($this->from_refs), DEBUG_DETAIL_TRACE);
		foreach($this->from_refs as $ref)
		{
			if (!in_array($ref->token(), $visited))	// this link not visited yet
			{
				$this->dbgecho($proc.$ref->token().' has not been visited. Processing...', DEBUG_DETAIL_TRACE);
				$visited[] = $ref->token();
				$join_str = $ref->mk_join($join_str, $tables, $visited, false);
				if (false===$join_str)
				{
					$this->set_error('Failure creating join string via reference '.$ref->token(), __FILE__, __LINE__);
					break;
				}
                                else
                                {
                                    $this->dbgecho($proc.'join for '.$ref->token().' is '.$join_str, DEBUG_DETAIL_TRACE);
                                }
			}
			else
			{
				$this->dbgecho($proc.$ref->token().' has already been visited. Skipping...', DEBUG_DETAIL_TRACE);
			}
		}
		if ($this->is_ok())
		{
        		$this->dbgecho($proc.'to_refs: '.$this->refs2str($this->to_refs), DEBUG_DETAIL_TRACE);
			foreach($this->to_refs as $ref)
			{
				if (!in_array($ref->token(), $visited))	// this link not visited yet
				{
					$this->dbgecho($proc.$ref->token().' has not been visited. Processing...', DEBUG_DETAIL_TRACE);
					$visited[] = $ref->token();
					$join_str = $ref->mk_join($join_str, $tables, $visited, true);
					if (false===$join_str)
					{
						$this->set_error('Failure creating join string via reference '.$ref->token(), __FILE__, __LINE__);
						break;
					}
                                        else
                                        {
                                            $this->dbgecho($proc.'join for '.$ref->token().' is '.$join_str, DEBUG_DETAIL_TRACE);
                                        }
				}
				else
				{
					$this->dbgecho($proc.$ref->token().' has already been visited. Skipping...', DEBUG_DETAIL_TRACE);
				}
			}
		}
		
		$this->dbgecho($proc.'leaving - '.($this->is_ok()?$join_str:'failed'), DEBUG_PROC_TRACE);
		return $this->is_ok($join_str);
	}
	
	function alias()
	{
		return $this->table_alias;
	}
	
	function required()
	{
		return $this->required;
	}
	
	function iskey()
	{
		return $this->iskey;
	}
        
        // show reference tables
        function refs2str($which)
        {
            $str = '';
            foreach($which as $ref)
            {
                if(strlen($str)==0) {$str = '['; $idx=1 ;} else {$str .= ', ';}
                $str .= $idx++.'->'.$ref->token();
            }
            $str .= ']';
            return $str;
        }
}

class table_linkages extends base
{
	
	var $tables = array();
	var $refs = array();
	
	function __construct($table_objs, $mode=DEFAULT_TRIGGER_ON_ERROR)
	{
//           $this->_debug = DEBUG_MINUTIA_TRACE;
            
		$proc = __CLASS__.'::'.__FUNCTION__.': ';
		$this->dbgecho($proc.'entering', DEBUG_PROC_TRACE);
		
		parent::__construct($mode);
		if ($this->is_ok())
		{
			foreach($table_objs as $alias => $table_obj)
			{
				$this->tables[$table_obj->tablename] = new jt_join_table($table_obj->get_db(), $table_obj->tablename, $alias, $table_obj->required, $table_obj->iskey, $mode);
			}
			$this->dbgecho($proc.'Tables to link'.look_r($this->tables), DEBUG_DETAIL_TRACE);
		
			// now compile a list of foreign references in those tables that refer to
			// another table in our list.  These will be the linking fields we will use
			// for joining our tables.  The list takes the form of an array indexed by a
			// sourcetable.sourcefield string containing a desttable.destfield string
			foreach($table_objs as $table_obj)
			{
				$this->dbgecho($proc.'Processing table object '.get_class($table_obj), DEBUG_DETAIL_TRACE);
				foreach($table_obj->fields as $fname => $finfo)
				{
					$this->dbgecho($proc.'Processing field '.$fname, DEBUG_DETAIL_TRACE);
					if (isset($finfo->reference))
					{
						$this->dbgecho($proc.'Field '.$fname.' is a reference to '.$finfo->reference->table, DEBUG_DETAIL_TRACE);
						if (array_key_exists($finfo->reference->table, $this->tables))
						{
							$this->dbgecho($proc.'In table list.  We care about this one', DEBUG_DETAIL_TRACE);
							$ref = new jt_join_reference($table_obj->get_db(), $table_obj->tablename, $fname, $mode);   // reference assignment removed =& as depreciated
							$ref->refers_to($finfo->reference->db, $finfo->reference->table, $finfo->reference->field);
							$this->tables[$table_obj->tablename]->to_ref($ref);
							$this->tables[$finfo->reference->table]->from_ref($ref);
							$this->refs[] = $ref;   // reference assignment removed to make work?
							
							$this->dbgecho($proc.'Table linkage from '.$table_obj->tablename.'.'.$fname.' to '.$finfo->reference->table.'.'.$finfo->reference->field.' created', DEBUG_DETAIL_TRACE);
						}
					}
				}
			}
			$this->dbgecho($proc.'All table linkage references created', DEBUG_DETAIL_TRACE);
                        $tmp = array();
			$this->dbgecho($proc.'References: '.$this->refs2str(), DEBUG_DETAIL_TRACE);
			$this->dbgecho($proc.'References: '.look__r($this->refs, 20, null, $tmp), DEBUG_MINUTIA_TRACE);
		
			// now compile the implicit references, where both references refer to the same thing
			$this->dbgecho($proc.'checking for implicit reference among '.count($this->refs).' explicit references', DEBUG_DETAIL_TRACE);
			for($i=0; $i<count($this->refs); $i++)
			{
				for($j=$i+1; $j<count($this->refs); $j++)
				{
					$this->dbgecho($proc.'implicit reference between '.$this->refs[$i]->table().'.'.$this->refs[$i]->field().' and '.$this->refs[$j]->table().'.'.$this->refs[$j]->field().' being checked', DEBUG_DETAIL_TRACE);
					if ($this->refs[$i]->refers_to_same($this->refs[$j]))
					{
						// create two brand new references
						$ref1 = new jt_join_reference($this->refs[$i]->db(), $this->refs[$i]->table(), $this->refs[$i]->field(), $mode);   // reference assignment removed =& as depreciated
						$ref1->refers_to($this->refs[$j]->db(), $this->refs[$j]->table(), $this->refs[$j]->field());
						$this->tables[$this->refs[$i]->table()]->to_ref($ref1);
						$this->tables[$this->refs[$j]->table()]->from_ref($ref1);
						$this->dbgecho($proc.'created ref '.$this->refs[$i]->table().'.'.$this->refs[$i]->field().'=>'.$this->refs[$j]->table().'.'.$this->refs[$j]->field(), DEBUG_DETAIL_TRACE);
						
						$ref2 = new jt_join_reference($this->refs[$j]->db(), $this->refs[$j]->table(), $this->refs[$j]->field(), $mode);   // reference assignment removed =& as depreciated
						$ref2->refers_to($this->refs[$i]->db(), $this->refs[$i]->table(), $this->refs[$i]->field());
						$this->tables[$this->refs[$j]->table()]->to_ref($ref2);
						$this->tables[$this->refs[$i]->table()]->from_ref($ref2);
						$this->dbgecho($proc.'created ref '.$this->refs[$j]->table().'.'.$this->refs[$j]->field().'=>'.$this->refs[$i]->table().'.'.$this->refs[$i]->field(), DEBUG_DETAIL_TRACE);
					}
				}
			}
			$this->dbgecho($proc.'All implicit references created', DEBUG_DETAIL_TRACE);
			$this->dbgecho($proc.'References: '.$this->refs2str(), DEBUG_DETAIL_TRACE);
			$this->dbgecho($proc.'References: '.look__r($this->refs, 20, null, $tmp), DEBUG_MINUTIA_TRACE);
		}
		if (!$this->is_ok())
		{
			$this->trigger_error();
		}
		$this->dbgecho($proc.'leaving - '.($this->is_ok()?'succeeded':'failed'), DEBUG_PROC_TRACE);
//		return $this->is_ok();
	}
	
	function sorted_tables()
	{
		$key_tab = array();
		$required_tabs = array();
		$other_tabs = array();
		
		foreach($this->tables as $idx => $tab)
		{
			if ($tab->iskey())
			{
				$key_tab[] = $idx;
			}
			elseif ($tab->required())
			{
				$required_tabs[] = $idx;
			}
			else
			{
				$other_tabs[] = $idx;
			}
		}
		
		return array_merge($key_tab, $required_tabs, $other_tabs);
	}
	
	// find a reference that refers to all tables
	function find_master_ref()
	{
		$proc = __CLASS__.'::'.__FUNCTION__.': ';
		$this->dbgecho($proc.'entering', DEBUG_PROC_TRACE);
		$this->clear_error();
		
		$join = false;
		$to_visit = $this->sorted_tables();
		foreach($to_visit as $try)
		{
			$tables = array();
			$visited = array();
			$this->dbgecho($proc.'Trying start at table '.$try, DEBUG_DETAIL_TRACE);
			$join = $this->tables[$try]->mk_join('', $tables, $visited);
			
			// were all the tables visited?
			$this->dbgecho($proc.count($tables).' tables out of '.count($to_visit).' visited', DEBUG_DETAIL_TRACE);
			if (count($to_visit)===count($tables)) break;
                        $join=false;
		}
		if (false===$join)
		{
			$this->set_error('No master reference could be determined for this set of tables', __FILE__, __LINE__);
		}
		
		$this->dbgecho($proc.'leaving - '.($this->is_ok()?'succeeded':'failed'), DEBUG_PROC_TRACE);
		return $this->is_ok($join);
	}
	
	// create the join expression
	function create_join_str($route=null)
	{
		$proc = __CLASS__.'::'.__FUNCTION__.': ';
		$this->dbgecho($proc.'entering', DEBUG_PROC_TRACE);
		$this->clear_error();
		
		$join_str = $this->find_master_ref();
		
		$this->dbgecho($proc.'leaving - '.($this->is_ok()?$join_str:'failed'), DEBUG_PROC_TRACE);
		return $this->is_ok($join_str);
	}
        
        // show reference table
        function refs2str()
        {
            $str = '';
            foreach($this->refs as $ref)
            {
                if(strlen($str)==0) {$str = '['; $idx=1 ;} else {$str .= ', ';}
                $str .= $idx++.'->'.$ref->token();
            }
            $str .= ']';
            return $str;
        }
}

class auto_join_table extends basedb
{
	                    // an array of info about tables to join, indexed by classname
						// must include an 'alias' element and may include a
						// 'required' element.  This member must be defined by any
						// derived class of auto_join_table
	var $_table_descs = array();
	
	var $_table_join;	// SQL select command with correct joins.  Created by determine_join_string
	                    // method called in the constructor
	
						// an array of selection criteria, indexed by table alias (as defined
						// in _table_descs member.  Contents must be a array with a key giving
						// the db field and the value specifying the value and optionally relationship
						// betweem the two.
						// an complicated example, using two tables aliased 'a' and 'b'.
						//
						// array('a' => array('field1' => 'value1',					// a.field1 = value1
						//                    'field2' => array('value2' => '>='),  // a.field2 >= value2
						//					  'field3' => 'value3'),				// a.field3 = value3
						//       'b' => array('fielda' => array('value4' => '<'));	// b.valuea < value4
						//
						// This member may be defined by the derived class or may be specified at runtime
						// via the select() method, in which case the method is overwritten.
	var $_selects =	array();
	
						// array of order criteria, consisting of an ordinary (numerically indexed) array
						// of elements specifying table alias, field and direction.
						//
						// array('a.field1',					// sort ascending by default
						//       array('a.field2' => 'desc'),	// sort decending
						//       array('b.fielda' => 'asc'));	// sort ascending (explicit)
						//
						// This member may be defined by the derived class or may be specified at runtime
						// via the select() method, in which case the method is overwritten.
	var $_order = array();
	
	var $_tbl_objs;		// array of table objects indexed by alias
	
	var $_records = array();
	
	function __construct($dbase, $dbuser, $mode=DEFAULT_TRIGGER_ON_ERROR)
	{
//           $this->_debug = DEBUG_MINUTIA_TRACE;
            
		$proc = __CLASS__.'::'.__FUNCTION__.': ';
		$this->dbgecho($proc.'('.$dbase.','.$dbuser.') entering', DEBUG_PROC_TRACE);
		
		parent::__construct($dbase, $dbuser, get_mysql_password($dbuser), null, $mode);
		if ($this->is_ok())
		{
			// create the table objects from the list of descriptions
			foreach($this->_table_descs as $classname => $info)
			{
				$this->dbgecho($proc.'creating component table object of class '.$classname, DEBUG_DETAIL_TRACE);
				$tmpobj = new $classname(null, $dbuser, $mode);
				if (!$tmpobj->is_ok())
				{
					$this->copy_error($tmpobj);
					$this->set_error('Unable to initialize internal '.$classname.' object', __FILE__, __LINE__);
					break;
				}
				else
				{
					// check that all tables are db_table_ex object
					if (!is_a($tmpobj, 'db_table_ex'))
					{
						$this->set_error('Object '.$info['alias'].' of class '.$classname.' is not a valid table object of class db_table_ex', __FILE__, __LINE__);
						break;
					}
					else
					{
						$this->dbgecho($proc.'adding table object of class '.get_class($tmpobj).' as entry '.$info['alias'], DEBUG_DETAIL_TRACE);
						$tmpobj->required = (isset($info['required'])?$info['required']:FALSE);
						$tmpobj->iskey = (isset($info['iskey'])?$info['iskey']:FALSE);
						$this->_tbl_objs[$info['alias']] = $tmpobj;
					}
				}
			}
			if ($this->is_ok())
			{
				$this->dbgecho($proc.'creating table linkage object', DEBUG_DETAIL_TRACE);
				$links =  new table_linkages($this->_tbl_objs, $mode);
				$this->dbgecho($proc.'done creating table linkage object', DEBUG_DETAIL_TRACE);
				if (!$links->is_ok())
				{
					$this->dbgecho($proc.'error creating table linkage object', DEBUG_DETAIL_TRACE);
					$this->copy_error($links);
					$this->set_error('Unable to create table linkage helper object', __FILE__, __LINE__);
				}
				else
				{
					$this->dbgecho($proc.'succeeded creating table linkage object', DEBUG_DETAIL_TRACE);
					$this->_table_join = $links->create_join_str();
					if (!$links->is_ok())
					{
						$this->dbgecho($proc.'error creating table linkage join string', DEBUG_DETAIL_TRACE);
						$this->copy_error($links);
						$this->set_error('Unable to determine a tablejoin string for this join table object', __FILE__, __LINE__);
					}
				}
			}
		}
		if (!$this->is_ok())
		{
			$this->trigger_error();
		}
		$this->dbgecho($proc.'leaving - '.($this->is_ok()?'succeeded':'failed'), DEBUG_PROC_TRACE);
                
//		return $this->is_ok();
	}
	
	// an array of selection criteria, indexed by table alias (as defined
	// in _table_descs member.  Contents must be a array with a key giving
	// the db field and the value specifying the value and optionally relationship
	// betweem the two.
	// an complicated example, using two tables aliased 'a' and 'b'.
	//
	// array('a' => array('field1' => 'value1',					// a.field1 = value1
	//                    'field2' => array('value2' => '>='),  // a.field2 >= value2
	//					  'field3' => 'value3'),				// a.field3 = value3
	//       'b' => array('fielda' => array('value4' => '<'));	// b.valuea < value4
	//
	function select($selection=null)
	{
		$proc = __CLASS__.'::'.__FUNCTION__.': ';
		$this->dbgecho($proc.'entering', DEBUG_PROC_TRACE);
		$this->clear_error();
		
		if (is_array($selection))
		{
			$this->_selects = $selection;
		}
		$this->dbgecho($proc.'leaving - '.($this->is_ok()?$this->_select_string():'failed'), DEBUG_PROC_TRACE);
		return $this->is_ok($this->_selects);
	}
	
	function _select_string()
	{
		$proc = __CLASS__.'::'.__FUNCTION__.': ';
		$this->dbgecho($proc.'entering', DEBUG_PROC_TRACE);
		$this->clear_error();
		
		$sel = '';
		foreach($this->_selects as $prefix => $fldinfo)
		{
			foreach($fldinfo as $name => $value)
			{
				if (strlen($sel)>0) $sel .= ' && ';
				$sel .= $prefix.'.`'.$name.'`'.(isset($value)?'=':' is ').$this->wrapvalue($prefix,$name,$this->escape_string($value));
			}
		}
		
		$this->dbgecho($proc.'leaving - '.($this->is_ok()?'succeeded':'failed'), DEBUG_PROC_TRACE);
		return $this->is_ok($sel);
	}
	
	function order($order=null)
	{
		$proc = __CLASS__.'::'.__FUNCTION__.': ';
		$this->dbgecho($proc.'entering', DEBUG_PROC_TRACE);
		$this->clear_error();
		
		if (isset($order))
		{
			if (is_array($order))
			{
				$this->_order = $order;
			}
			else
			{
				$this->_order = array($order);
			}
		}
		$this->dbgecho($proc.'leaving - '.($this->is_ok()?$this->order_string():'failed'), DEBUG_PROC_TRACE);
		return $this->is_ok($this->_order, RETURN_NULL_OK);
	}
	
	function order_string()
	{
		return implode(', ', $this->_order);
	}
	
	function do_select($fields='*', $selection=null, $limit=null, $offset=null)
	{
		$proc = __CLASS__.'::'.__FUNCTION__.': ';
		$this->dbgecho($proc.'entering', DEBUG_PROC_TRACE);
		$this->clear_error();
		
		if (is_array($fields)) $fields = implode(', ', $fields);
		$sel_str = $this->_select_string();
		if (strlen($sel_str)>0)
		{
			if (strlen($selection)>0)
				$sel_str = '('.$sel_str.') && ('.$selection.')';
		}
		else
		{
			$sel_str = $selection;
		}
		$ord_str = $this->order_string();
		$query = 'select '.$fields.' from '.$this->_table_join.
			((strlen($sel_str)>0)?(' where '.$sel_str):'').
			((strlen($ord_str)>0)?(' order by '.$ord_str):'').
                        (isset($limit)?(' limit '.(isset($offset)?($offset.', '):'').$limit):'');			
		$res = $this->query($query);
		
		$this->dbgecho($proc.'leaving - '.($this->is_ok()?'succeeded':'failed'), DEBUG_PROC_TRACE);
		return $this->is_ok($res);
	}
	
	function wrapvalue($tbl, $field, $val)
	{
		if (!isset($this->_tbl_objs[$tbl]))
		{
			// seach for table with this name
			foreach($this->_tbl_objs as $table_obj)
			{
				if ($table_obj->_table == $tbl) break;
			}
		}
		else
		{
			$table_obj = $this->_tbl_objs[$tbl];
		}
		if (isset($table_obj) && isset($table_obj->fields[$field]))
		{
			$val = $table_obj->fields[$field]->wrapvalue($val);
		}
		return $val;
	}
	
	function load_records($selection=null)
	{
		$proc = __CLASS__.'::'.__FUNCTION__.': ';
		$this->dbgecho($proc.'entering', DEBUG_PROC_TRACE);
		$this->clear_error();
		
		if ($res = $this->do_select('*', $selection))
		{
			$this->_records = $res->fetch_data();
			$res->free();
		}
		
		$this->dbgecho($proc.'leaving - '.($this->is_ok()?'succeeded':'failed'), DEBUG_PROC_TRACE);
		return $this->is_ok($this->num_records());
	}
	
	function num_records()
	{
		return count($this->_records);
	}
	
	function get_record($index=0)
	{
		return $this->_records[$index];
	}
	
	function get_field($fieldname, $alias=null, $index=0)
	{
		$proc = __CLASS__.'::'.__FUNCTION__.': ';
		$this->dbgecho($proc.'('.$fieldname.','.$alias.','.$index.')entering', DEBUG_PROC_TRACE);
		$this->clear_error();
		
		if (!isset($alias))
		{
			$alias = $this->get_field_alias($fieldname);
		}
		if (isset($alias))
		{
			if (isset($this->_records[$index]))
			{
				if (array_key_exists($fieldname, $this->_records[$index]))
				{
					$res = $this->_records[$index][$fieldname];
				}
				elseif (array_key_exists($alias.'.'.$fieldname, $this->_records[$index]))
				{
					$res = $this->_records[$index][$alias.'.'.$fieldname];
				}
				else
				{
					$this->set_error('Field '.$alias.'.'.$fieldname.' not found in this table join', __FILE__, __LINE__);
				}
			}
			else
			{
				$this->set_error('Record '.$index.' does not exist for this table query', __FILE__, __LINE__);
			}
		}
		
		$this->dbgecho($proc.'leaving - '.($this->is_ok()?'succeeded':'failed'), DEBUG_PROC_TRACE);
		return $this->is_ok($res, RETURN_NULL_OK);
	}
	
	function get_field_alias($fieldname, $limit=1)
	{
		$proc = __CLASS__.'::'.__FUNCTION__.': ';
		$this->dbgecho($proc.'entering', DEBUG_PROC_TRACE);
		$this->clear_error();
		
		$res = array();
		foreach($this->_tbl_objs as $a => $tabobj)
		{
			if (isset($tabobj->fields[$fieldname]))
			{
				$res[] = $a;
				if (count($res)==$limit) break;
			}
		}
		if ($limit==1) $res = ((count($res)>0)?$res[0]:null);
		
		$this->dbgecho($proc.'leaving - '.($this->is_ok()?'succeeded':'failed'), DEBUG_PROC_TRACE);
		return $this->is_ok($res, RETURN_NULL_OK);
	}
	
	function clear_records()
	{
		$this->_records = array();
	}
}
 ?>