<?php

/**
* MYSQL用のSQLビルダ
*
* PHP version 5
*
* @package    components.db
* @author     stk2k <stk2k@sazysoft.com>
* @copyright  2008 stk2k, sazysoft
*/
class MySQL_SQLBuilder extends DefaultSQLBuilder
{
	/*
	 *	コンストラクタ
	 */
	public function __construct()
	{
	}

	/*
	 * SQLビルダ名を取得
	 */
	public function getSQLBuilderName()
	{
		return "MySQL SQL builder";
	}

	/*
	 *	SQL作成(CREATE DATABASE)
	 */
	public  function buildCreateDatabaseSQL( $db_name, $charset = NULL )
	{
		return "CREATE DATABASE $db_name DEFAULT CHARACTER SET $charset";
	}

	/*
	 *	SQL作成(CREATE TABLE)
	 */
	public  function buildCreateTableSQL( ITableModel $model )
	{
		$field_list = $model->getFieldList();

		$SQL_pk_list    = array();
		$SQL_field_list = array();

		foreach( $field_list as $name )
		{
			$pk       = $model->getAnnotation( $name, 'pk' );
			$type     = $model->getAnnotation( $name, 'type' );
			$notnull  = $model->getAnnotation( $name, 'notnull' );
			$charset  = $model->getAnnotation( $name, 'charset' );
			$serial   = $model->getAnnotation( $name, 'serial' );
			$default  = $model->getAnnotation( $name, 'default' );

			$type_name = $this->mapType( $type->getValue() );
			$length    = $type->getParameter();

			if ( $length ){
				$field_expr = "`$name` $type_name($length)";
			}
			else{
				$field_expr = "`$name` $type_name";
			}

			if ( $pk ){
				$SQL_pk_list[] = "`$name`";
				if ( $notnull ){
					$field_expr .= ' NOT NULL';
				}
				if ( $serial ){
					$field_expr .= ' AUTO_INCREMENT';
				}
			}
			else{
				if ( $default ){
					$field_expr .= ' DEFAULT ' . $default->getValue();
				}
				if ( $charset ){
					$field_expr .= " CHARACTER SET $charset";
				}
				if ( $notnull ){
					$field_expr .= ' NOT NULL';
				}
			}

			$SQL_field_list[] = $field_expr;
		}

		$SQL_field_list = implode( ",\n", $SQL_field_list );
		$SQL_pk_list    = implode( ',', $SQL_pk_list );

		$table_name = $model->getTableName();
		$sql = "CREATE TABLE $table_name (\n $SQL_field_list \n ,PRIMARY KEY( $SQL_pk_list ) )";

		return $sql;
	}

	/*
	 *	SQL作成(LAST_INSERT_ID)
	 */
	public  function buildLastIdSQL()
	{
		return "select LAST_INSERT_ID()";
	}

}
