<?php
include_once 'includes/datasets_conf/_base.class.php';
class datasets_conf_create_table extends datasets_conf {

function create_table($datasets_id,$command) {
	$this->init($datasets_id);

	$data_name = $this->dsn['dataname'];
	$db_name = $this->dsn['dbname'];
	$sql_dir = $this->application_path.'/etc/sql/'.$this->dsn['system'];
	if(file_exists($sql_dir.'/'.$data_name.'.sql'))
		$create_sqlfile = file_get_contents($sql_dir.'/'.$data_name.'.sql');
	if(file_exists($sql_dir.'/alter_'.$data_name.'.sql'))
		$alter_sqlfile = file_get_contents($sql_dir.'/alter_'.$data_name.'.sql');

	$data_set = $this->new_data_obj($data_name);
	if($this->dsn['system']=='sqlite' OR $this->dsn['system']=='sqlite3')
		make_dir($this->application_path.'/var/sqlite',0777);
	$tmp = $this->home_dir;
	$this->home_dir = $this->application_path;

	$view_conf_dir = $this->application_path.'/etc/data_view';
	$data_set->bind_data_view($data_name.'.view.conf',$view_conf_dir);
	$set_conf_dir = $this->application_path.'/etc/data_set';
	$data_set->bind_data_set($data_name.'.set.conf',$set_conf_dir);
	if($this->dsn['system']=='sqlite' OR $this->dsn['system']=='sqlite3')
		$data_set->set_dsn('path',$this->application_path.'/var/sqlite');
	$this->home_dir = $tmp;
	
	switch($command) {
		case 'create_table':
			if(!$create_sqlfile) return false;
			$data_set->set_ignore_no_table();
			$sqls = explode(';',$create_sqlfile);
			foreach($sqls as $sql) {
				$sql = trim(str_replace("\n",'',$sql));
				if($sql) {
					$result = $data_set->exec_sql($sql);
				}
			}
			$data_set->set_ignore_no_table(false);
			$message .= 'create table:'.$data_name.' -> '.$db_name."\n";
			$message .= "以下のsqlでテーブルを作成しました。\n\n";
			$message .= "---- create table\n";
			$message .= $create_sqlfile."\n";
			break;
		case 'add_column':
			if(!$alter_sqlfile) return false;
			if($this->dsn['system']=='sqlite') {
				$message = "SQLite 2.xはテーブルへのカラム追加をサポートしていません。\n\n";
			} else {
				$sqls = explode(';',$alter_sqlfile);
				foreach($sqls as $sql) {
					$sql = trim(str_replace("\n",'',$sql));
					if($sql) {
						$result = $data_set->exec_sql($sql);
					}
				}
				$message .= 'alter table:'.$data_name.'('.$db_name.")\n\n";
				$message .= "以下のsqlでテーブルにカラムを追加しました。\n\n";
				$message .= "---- add column\n";
				$message .= $alter_sqlfile."\n";
			}
			break;
		case 'no_exec':
			$message .= "テーブルは作成されません。\n";
			$message .= "現在のSQLは以下の通りです。\n\n";
			$message .= "---- create table\n";
			$message .= $create_sqlfile."\n\n";
			if($alter_sqlfile) {
				$message .= "---- add column\n";
				$message .= $alter_sqlfile."\n";
			}
	}
	$result['message'] = $message;
	return $result;
}

} // end of class datasets_conf_create_table
?>